demand

In the development process, there will be many forms need to select the enumeration class Settings of the drop-down menu, if one in the front end to write dead is very unreasonable. It should be configured directly when the Models data model is set up, and then the enumeration data is read directly from the front end, and then read directly from the template, or returned from JSON. Let’s write an example.

reference

Docs.djangoproject.com/zh-hans/2.1…

The sample

1) Create data model classes and form Settings

from django.db import models
from django import forms

class FormTestForm(forms.Form):
    """FormTest Data model form form field"""
    
    Pull-down data for task types
    task_type_choices = (
        (0, 'Regular tasks'),
        (1, 'Online Business Daily Polling'),
        (2, 'Full link task'),Set mandatory fields in the form
    task_type = forms.ChoiceField(label='Task Type :', widget=forms.Select(), choices=task_type_choices,initial=task_type_choices[0])
    comment = forms.CharField(label='note',max_length=30)

class FormTest(models.Model):
    """FormTest Data Model class"""
    
    Pull-down data for task types
    task_type = models.SmallIntegerField(default=0, choices=FormTestForm.task_type_choices, verbose_name='Task Type')
    comment = models.CharField(max_length=30, verbose_name='Remarks')

    class Meta:
        db_table = 'dp_form_test'
        verbose_name = 'Form Test'
        verbose_name_plural = verbose_name
        ordering = ['id'] # sort field
Copy the code

2) Perform data migration

python3 manage.py makemigrations
python3 manage.py migrate
Copy the code

View the generated data table:

mysql> desc dp_form_test;
+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| id        | int(11)     | NO   | PRI | NULL    | auto_increment |
| task_type | smallint(6) | NO   |     | NULL    |                |
| comment   | varchar(30) | NO   |     | NULL    |                |
+-----------+-------------+------+-----+---------+----------------+
3 rows in set(0.00 SEC) mysql >Copy the code

3) Write a view to process the form

from .models import FormTest,FormTestForm

# ex:/assetinfo/form_test
class FormTestView(View):

    def get(self,request):
        form_test_form =  FormTestForm() Create the form class

        context = {
            'form_test_form': form_test_form,
        }

        return render(request,'form_test/form_test.html',context=context)

    def post(self,request):

        form_test_form = FormTestForm(request.POST)  Create a form class that accepts the POST request parameters for data validation

        if form_test_form.is_valid(): Determine if the form data is correct
            task_type = request.POST.get('task_type'.' ')
            comment = request.POST.get('comment'.' ')

            Write data to database
            FormTest.objects.create(
                task_type=task_type,
                comment=comment,
            )

            return HttpResponse("task_type = %s, comment = %s" % (task_type, comment))

        else: Form validation failed, return error
            task_type = request.POST.get('taskTypeSelect'.' ')
            errors = form_test_form.errors # Print error information
            return HttpResponse("error, task_type = %s, errors = %s" % (task_type, errors))
Copy the code

4) Configure the URL

urlpatterns = [
    # ex:/assetinfo/form_test
    path('form_test', FormTestView.as_view(), name='form_test'),]Copy the code

5) Write a simple HTML page for a form form

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="post">
        {% csrf_token %}
        {Is_vaild does not have a required field in the form. The name of is_vaild must be the same as that of the form.
        <select class="form-control" id="taskTypeSelect" name="task_type">
            <option selected="" name="taskTypeSelect"> Select the task type </option> {%for key,value in form_test_form.task_type_choices %}
                <option value="{{ key }}" name="task_type">{{ value }}</option>
            {% endfor %}
        </select>

        <input type="text" name="comment" id="commemt">

        <button type="submit"</button> </form> </body> </ HTML >Copy the code

Note: The name set in is_vaild must be the same as the name set in the form form, otherwise the form cannot be retrieved

6) Start the service and test the normal request

If the request succeeds, the value requested by the browser is returned.

After multiple requests, check whether the value stored by mysql is correct as follows:

mysql> select * from dp_form_test; + - + -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- + | | id task_type | comment | + - + -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- + | | | 0 1 note | | 2 | 0 | note | | 3 Note 3 | 1 | | + - + -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- + 3 rowsin set(0.00 SEC) mysql >Copy the code

Request successful and save data successful!!

7) Test the error request

If a request is made directly without filling in the task data, the following error message is displayed:

As you can see, the form_test_form.errors parameter is used to get print-related error information. Of course, you can also customize error messages.