Instructions for using django forms

Form:
Form in HTML:
purely from the front-end html, the form is used to submit data to the server, regardless of whether the background server uses Django, PHP or other languages. Just put the input tag in the form tag, and then add a submit button, then click the submit button later to submit the corresponding value in the input tag to the server.

Forms in Django:
Forms in Django enrich the forms in the traditional HTML language. Forms in Django mainly do the following two things:

Render the form template.
Form validation data is valid.
Form usage process in Django:
Before explaining the details of each part of the Django form. Let's first look at the overall usage process. Here is an example of making a message board. First, we define a form class in the background server, which inherits from django.forms.Form. The sample code is as follows:

forms.py

class MessageBoardForm(forms.Form):
title = forms.CharField(max_length=3,label='title',min_length=2,error_messages={"min_length":'The title character field does not meet the requirements!'}) content = forms
. CharField(widget=forms.Textarea,label='Content')
email = forms.EmailField(label='Email')
reply = forms.BooleanField(required=False,label='Reply')
Then in the view, according to GET Or POST request to do the corresponding operation. If it is a GET request, return an empty form, and if it is a POST request, then verify the submitted data. The sample code is as follows:

views.py

class IndexView(View):
def get(self,request):
form = MessageBoardForm()
return render(request,‘index.html’,{‘form’:form})

def post(self,request):
    form = MessageBoardForm(request.POST)
    if form.is_valid():
        title = form.cleaned_data.get('title')
        content = form.cleaned_data.get('content')
        email = form.cleaned_data.get('email')
        reply = form.cleaned_data.get('reply')
        return HttpResponse('success')
    else:
        print(form.errors)
        return HttpResponse('fail')

When using the GET request, we passed a form to the template, then the template can use the form to generate the html code of a form in the future. When using the POST request, we build a new form based on the data uploaded from the front end. This form is used to verify whether the data is legal. If the data is verified, then we can get the corresponding data through cleaned_data. The HTML code to render the form in the template is as follows:

    <tr>
        <td></td>
        <td><input type="submit" value="提交"></td>
    </tr>
</table>
We gave a form tag on the outside, and then used the table tag to beautify it. When using the form object to render, the table method is used. Of course, the ul method (as_ul) can also be used. p tag (as_p), and we also added a submit button later. This will generate a form

Guess you like

Origin blog.csdn.net/qq_17584941/article/details/125887237