Reputation: 723
I am a newbie to MVC architecture. Can someone tell me what are forms, what do they exactly do and how they are related to models. According to django documentation forms takes care of a number of common form-related tasks. What are those tasks? I see forms are mentioned during registrations a lot, are they just used for it alone? Are forms just used as POST requests of Model fields? If so in Modelform/forms we cannot have fields that are not related to existing models?
Thank you!
Upvotes: 0
Views: 93
Reputation: 1027
Conceptually, forms serve as the handler for inputting data in your HTML in order to use that data somewhere in your application (in your views).
You'll find two common uses for forms in Django: working with your models (data defined by your database) or for the purposes of accomplishing some kind of task (like sending an e-mail - where you don't necessarily need to have an associated model).
Forms do a lot of things for both of these functions. These range from modularity, extensibility and ease of management (as they can be easily defined, interchanged, inherited etc. in Python) to validation (one of the biggies). Validation is crucial - and it's probably what you are referring to in terms of registration. Django Forms will validate against a definition either defined in your Form class or inherit validation code if you are using something like a ModelForm. In the case of a ModelForm, the Form will validate based on the attributes you assigned to your model fields (i.e., that no strings are entered into an Integer Field).
Considering the two common uses I mentioned earlier, you should thus check out the relevant links of documentation.
https://docs.djangoproject.com/en/dev/topics/forms/ https://docs.djangoproject.com/en/dev/topics/forms/modelforms/
To answer some of your other questions. You can have fields not associated with your Model in ModelForms - but you'll have to handle them appropriately in your view. You also don't necessarily need to have all of your Model fields available for input in a form (using exclude in class Meta).
Upvotes: 2