Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I create form objects or generate them from model

Tags:

django

I recently found out that I can generate forms from models. I've read the docs and am wondering why someone would opt not to do this in favor creating their own form objects.

like image 547
Johnd Avatar asked Mar 08 '26 09:03

Johnd


2 Answers

Not all forms are directly related to a Model. While most of the time you might end up using a ModelForm, sometimes you want to create a form for something that is better expressed as an individual form and then you can patch the data together in the view. In my experience this isn't often, but it happens sometimes.

like image 171
Paolo Bergantino Avatar answered Mar 10 '26 02:03

Paolo Bergantino


Riffing off of Paolo's answer, if you are collecting data from the user to store in your database, you will probably already have a model set up with fields for the information that needs to be collected. In this case, use a ModelForm. On the other hand, sometimes you have scenarios where instead of collecting data from the user, you're using their input to perform some action on data already in the database, perhaps, say, generating a view that's a mashup of information from multiple models. In this case, you will want to use Form. The Form will still allow you to perform validation on the user input comparatively easily.

like image 27
gotgenes Avatar answered Mar 10 '26 02:03

gotgenes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!