Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

whats the difference between Django models and forms?

Tags:

I am new to Django and can't understand the models and forms. Can any one suggest me the differences and tutorials related to them.

like image 422
Vivek S Avatar asked Mar 30 '11 03:03

Vivek S


2 Answers

Basically, a model encapsulates information about something (i.e., it models it), and is stored in the database. For example, we could model a person:

from django import models

class Person(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()
    height = models.FloatField()
    weight = models.FloatField()

Whenever a model instance is created and saved, Django stores it in the database for you to retrieve and use at a later date.

On the other hand, forms correspond to HTML forms, i.e., a set of fields which are presented to the end user to fill some data in. A form can be completely independent of a model, for example a search form:

from django import forms

class SearchForm(forms.Form):
    search_terms = forms.CharField(max_length=100)
    max_results = forms.IntegerField()

When submitted, Django takes care of validating the values the user entered and converting them to Python types (such as integers). All you then have to do is write the code which does something with these values.

Of course, if you have created a model, you will often want to allow a user to create these models through a form. Instead of having to duplicate all the field names and create the form yourself, Django provides a shortcut for this, the ModelForm:

from django.forms import ModelForm

class PersonForm(forms.ModelForm)
    class Meta:
        model = Person

As for further reading, I would start with the Django documentation, which includes a tutorial on creating and using models, and a fairly in-depth look at forms. There are also plenty of Django books and online tutorials to help you along.

like image 142
Blair Avatar answered Oct 11 '22 07:10

Blair


Models are related to the database abstraction layer covered in Tutorial 1:

http://docs.djangoproject.com/en/dev/intro/tutorial01/

It covers everything from what they are, what the philosophy is, what it's abstracting (raw sql). Read it and come back if you have any questions, because it's really good.

Tutorial 4 covers forms.

http://docs.djangoproject.com/en/dev/intro/tutorial04/

The forms framework is just a helper for HTML forms. There are also ModelForms, based on the forms framework, that ties models together with forms, but the core of it is a framework for dealing with HTML form display, validation, and processing.

like image 32
Yuji 'Tomita' Tomita Avatar answered Oct 11 '22 08:10

Yuji 'Tomita' Tomita