Creating forms from models

Original: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/

ModelForm

Beispiel:

>>> from django.forms import ModelForm

# Create the form class.
>>> class ArticleForm(ModelForm):
...     class Meta:
...         model = Article

# Creating a form to add an article.
>>> form = ArticleForm()

# Creating a form to change an existing article.
>>> article = Article.objects.get(pk=1)
>>> form = ArticleForm(instance=article)

Field types

Model field Form field
CharField CharField
DateField DateField
...  
ForeignKey ModelChoiceField
ManyToManyField ModelMultipleChoiceField
TextField CharField mit widget=Textarea

A full example

Beispiel:

from django.db import models
from django.forms import ModelForm

TITLE_CHOICES = (
    ('MR', 'Mr.'),
    ('MRS', 'Mrs.'),
    ('MS', 'Ms.'),
)

class Author(models.Model):
    name = models.CharField(max_length=100)
    title = models.CharField(max_length=3, choices=TITLE_CHOICES)
    birth_date = models.DateField(blank=True, null=True)

    def __unicode__(self):
        return self.name

class Book(models.Model):
    name = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)

class AuthorForm(ModelForm):
    class Meta:
        model = Author

class BookForm(ModelForm):
    class Meta:
        model = Book

...

The save() method

# Create a form instance from POST data.
>>> f = ArticleForm(request.POST)

# Save a new Article object from the form’s data.
>>> new_article = f.save() # SQL INSERT

# Create a form to edit an existing Article.
>>> a = Article.objects.get(pk=1)
>>> f = ArticleForm(instance=a)
>>> f.save()

# Create a form to edit an existing Article, but use
# POST data to populate the form.
>>> a = Article.objects.get(pk=1)
>>> f = ArticleForm(request.POST, instance=a)
>>> f.save() # SQL UPDATE

...

Using a subset of fields on the form

...

Overriding the default field types

...

Previous topic

Next topic