Python Automation Development Learning 24-django (Modelform)

Source: Internet
Author: User
Tags time zones tag name

Create with Modelform

The next table structure to use is as follows:

# 文件class UserType(models.Model):    caption = models.CharField(max_length=32)class UserInfo(models.Model):    username = models.CharField(max_length=32)    email = models.EmailField()    user_type = models.ForeignKey(to=‘UserType‘, on_delete=models.CASCADE)

After the table structure is written, build the database:
Python makemigrations
Python Migrate
As we said in the previous section, Modelform is very simple, so there are not too many things in the following lines:

# 文件class UserInfo(forms.ModelForm):    class Meta:        model = models.UserInfo        fields = ‘__all__‘

Processing functions

# 文件def user_info(request):    if request.method == ‘GET‘:        obj = forms.UserInfo()        return render(request, ‘user_info.html‘, {‘obj‘: obj})    elif request.method == ‘POST‘:        obj = forms.UserInfo(request.POST)        return render(request, ‘user_info.html‘, {‘obj‘: obj})

And finally, the page shows up.

<form action="." method="POST">    {% csrf_token %}    {{ obj.as_p }}    <input type="submit" value="提交"></form>

Finally open the page to see, but also can automatically generate HTML tags, and the effect and the previous use of the form basically no difference.

Custom Label

The name shown above in the page is the default variable name, if you want to display Chinese, you need to set a variable verbose_name in models.
The parameters of models were previously mentioned in the Python Automation development learning 19-django. The name of the field displayed in Verbose_name:admin, which is displayed by default as the variable name. We use Modelform is the same, because the admin used is modelform.
The modified code is in parallel with the contents of the following.

Display the contents of an option

Because the usertype table is empty now, there is no other option in the Select drop-down list. After you add a few pieces of data, you have the appropriate options on the page, but the content is displayed as objects. In order for him to display the content, a method must be set in the class __str__ .
Together with the Chinese label shown above, modify it to look like this:

# modelspy 文件class UserType(models.Model):    caption = models.CharField(max_length=32)    def __str__(self):        return self.captionclass UserInfo(models.Model):    username = models.CharField(verbose_name="用户名", max_length=32)    email = models.EmailField(verbose_name="电子邮件")    user_type = models.ForeignKey(verbose_name="用户类型", to=‘UserType‘, on_delete=models.CASCADE)
Customizing the fields displayed on the page

The fields of the Meta class in the above Modelform are set to display all the fields, or you can pass in a list, showing only those that are required. Or use exclude, which indicates which fields are excluded:

        # fields = ‘__all__‘        # fields = [‘username‘, ‘user_type‘]        exclude = [‘email‘]
function of Form in Modelform

First look at the relationship between Modelform and form.
Before learning to use the form, the inheritance is baseform. I use the Modelform, the parent class is Basemodelform, and then on the Internet to find the inheritance or baseform.
Before learning form, I talked about the 2 functions of form, validating and generating HTML tags. All are implemented in the BaseForm class. So these functions are the same in Modelform, and they are almost the same with form.

Parameters in the Meta class

Lecturer's blog Address:
In the above example, 3 parameters have been used, model, fields, exclude. Below you see what are the common parameters:

  • model: Which table corresponds to models
  • fields: The field displayed, __all__ representing all fields
  • exclude: Excluded Automatic
  • labels: Custom tag name, dictionary type labels = {‘username‘: "名字", ‘email‘: "邮箱", ‘user_type‘: "类型"} corresponds to the above example. How to still set the Verbose_name in the models, or the labels here prevail.
  • help_texts: A hint message that appears behind the input box. The dictionary type is the same as above.
  • widgets: Custom plug-ins, or form plug-ins, if the direct import will be the same name, to add aliases from django.forms import widgets as my_widgets . Examples of usage:widgets = {‘username‘: my_widgets.Textarea(attrs={‘class‘: ‘c1‘})}
  • error_messages: Custom error message, the key of the overall error message is the from django.core.exceptions import NON_FIELD_ERRORS‘__all__‘
  • field_classes: A class that customizes the form validation. The default models is Charfield, then the class for the form is also Charfield. This setting can get rid of implementation customizations. Examples of usage: field_classes = {‘username‘: forms.fields.EmailField} . If the direct import of fields will still have the same name problem, with as to get rid of
  • localized_fields: Localized to display data according to different time zones. Parameters are Ganso that require localized field names, such as:localized_fields=(‘create_time‘,)

Many of the field settings in the Meta class are the same as in the form. But the form is a field set in a field, and Modelform is set by the whole table. So the settings here are in the dictionary, key is the field name, and value is the same as the value set in the form.

function of Model in Modelform

The main thing here is to change the data and delete

Add data

Directly to the object, using the Is_valid () method to verify the pass, directly to the object with a save () method to complete the data can be added. Here are the processing functions that you can do to add data:

# 文件def user_info(request):    if request.method == ‘GET‘:        obj = forms.UserInfo()        return render(request, ‘user_info.html‘, {‘obj‘: obj})    elif request.method == ‘POST‘:        obj = forms.UserInfo(request.POST)        if obj.is_valid():          return render(request, ‘user_info.html‘, {‘obj‘: obj})
Many-to-many situations

The example is not written. If there are many-to-many associations, the default is to update the data for the third table with many-to-many associations.
In fact, the Save () method is split into 2-step execution, first manipulating the current table and then manipulating the third table of many-to-many associations. The Save () method has a default parameter that def save(self, commit=True): is the default setting that is performed above. If the argument is false, it does not automatically update the third table for us. If you want to use the false parameter, use the following:

instance =  # 不在任何操作  # 保存当前的表的数据obj.save_m2m()  # 保存第三张表的数据
Fill in the default value

To generate HTML, fill in the default values in the page. The first step is to do a model operation, go to the database to get a data object, and then the object as Modelform instance parameter passed in. The code is as follows:

    if request.method == ‘GET‘:        user_obj = models.UserInfo.objects.filter(id=1).first()        obj = forms.UserInfo(instance=user_obj)        return render(request, ‘user_info.html‘, {‘obj‘: obj})
Update data

Fill in the default values, which are often used when making changes. After the modification is submitted to the background, the data will be updated. You cannot use the direct Save () method here, as this will become new. Data Update with the Save () method, but to pass in a parameter, tell the system to update the new data to which bar of the table, or else it is new. The specific practice is as follows:

    elif request.method == ‘POST‘:        user_obj = models.UserInfo.objects.filter(id=1).first()        obj = forms.UserInfo(request.POST, instance=user_obj)        if obj.is_valid():          return render(request, ‘user_info.html‘, {‘obj‘: obj})

This is similar to the default values, except that the data that needs to be updated is passed in here.

Add extra Fields

For example, a login login application scenario. In addition to the user name and password on the page, you can also add a radio box "Remember Me." This extra field is not recorded in the database, but is written in a cookie or session. In this case, the field can be defined in the Modelform class as a public property (static property), defined as exactly the same as the field that defines the form:

# 文件class UserInfo(forms.ModelForm):    is_remembered = forms.fields.CharField(        widget=my_widgets.CheckboxInput(),        label="记住我",    )    class Meta:    # 元类里的内容就略了

This extra field will be displayed in the final page, with the full functionality of the form, validating and generating the HTML. But there is no model operation.

Python Automation Development Learning 24-django (Modelform)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.