Django之forms.ModelForm

Usually in the Django project, most of them written in our Django model closely mapped form. For example, you may have a Book model, and you want to create a form form to add and edit book information into the model. In this case, in the form definition of the form fields will be redundant because we have defined those fields in the model.

 

  For this reason, Django provides a helper class so that we can from Django to create a model Form , which is ModelForm .

 

modelForm defined

    form and model ultimate binding, based on your model converted to the corresponding fields in the form field, and generates an operation and you labels.

 

    models in the table is the following:

class Book(models.Model):

    nid = models.AutoField(primary_key=True)

    title = models.CharField( max_length=32)

    publishDate=models.DateField()

    price=models.DecimalField(max_digits=5,decimal_places=2)

    publish=models.ForeignKey(to="Publish",to_field="nid")

    authors=models.ManyToManyField(to='Author',)

    def __str__(self):

        return self.title

 

modelform class writing:

class BookForm(forms.ModelForm):

    class Meta:

        model = models.Book

        fields = "__all__"

        labels = {

            "title": "书名",

            "price": "价格"

        }

        widgets = {

            "password": forms.PasswordInput(attrs={"class": "c1"}),

 

            "publishDate": forms.DateInput(attrs={"type": "date"}),

        }

class Meta the common parameters:

= models.Book Model  # corresponding Model class

= Fields [] # specified field

= Fields "__all__"  # field, if it is __all__, is to represent all the fields listed

= the exclude []  # negative field

= Labels {}  # message

= help_texts {}  # help information

= {Widgets # custom plug

            "password": forms.PasswordInput(attrs={"class": "c1"}),

            "publishDate": forms.DateInput(attrs={"type": "date"}),

        }

 = {error_messages, # custom error message

    'title' : { 'required' : ' can not be empty ' , ...}  # all errors for each field can be written

}

 In succession forms.ModelForm time class, Models in Onetoone and Manytomany property is automatically converted into ModelChoiceField and ModelMultipleChocieField automatically read data. 

 

In ModelForm add a data component in use, it can be used directly save () method , using the save time method, if the second object has the specified keyword parameter when instantiated instance , compared with the update operation!

 

Guess you like

Origin www.cnblogs.com/open-yang/p/11223192.html
Recommended