This article mainly introduces how to compile Contact forms in the Django framework. Django is the most popular among the frameworks with different Python characteristics, for more information, see the example form that we have been using for book search and can improve it perfectly. However, this is quite simple: it only contains one field, q. In this simple example, we do not need to use the Django form Library for processing. However, complicated forms require multi-faceted processing. here is a complicated example: Site contact form.
This form contains the feedback submitted by the user and an optional email return address. After the form is submitted and the data passes verification, the system will automatically send an e-mail containing the information submitted by the question user to the site staff.
Start with the contact_form.html template:
Contact us Contact us {% if errors %}
{% for error in errors %}
- {{ error }}
{% endfor %}
{% endif %}
We have defined three fields: subject, email, and feedback. The other two fields are required. Note: Here we use method = "post" instead of method = "get", because this form has a server-side operation: send an email. In addition, we copied the code for displaying error messages in the previous template search_form.html.
If we follow the idea of writing the search () view in the previous section, the code of a contact () view should be as follows:
from django.core.mail import send_mailfrom django.http import HttpResponseRedirectfrom django.shortcuts import render_to_responsedef contact(request): errors = [] if request.method == 'POST': if not request.POST.get('subject', ''): errors.append('Enter a subject.') if not request.POST.get('message', ''): errors.append('Enter a message.') if request.POST.get('email') and '@' not in request.POST['email']: errors.append('Enter a valid e-mail address.') if not errors: send_mail( request.POST['subject'], request.POST['message'], request.POST.get('email', 'noreply@example.com'), ['siteowner@example.com'], ) return HttpResponseRedirect('/contact/thanks/') return render_to_response('contact_form.html', {'errors': errors})
(If you follow the example in the book, you may have a question: whether the contact () view should be placed in the file books/views. py. However, the contact () view is not associated with the books application, so this view should be available elsewhere? This does not matter. as long as the ing between the URL and view is correctly set in URLconf, Django will handle it correctly. I personally like to create a contact folder, which is the same as the books folder. This folder contains two empty files: _ init _. py and views. py.
Now let's analyze the above code:
Make sure that the value of request. method is 'post '. This value does not exist when the user browses the form. it only appears when the form is submitted. (In the following example, request. method will be set to 'get', because the browser uses GET instead of POST in normal web browsing ). Judging the value of request. method helps us isolate form display from form processing.
We use request. POST instead of request. GET to obtain the submitted data. This is because the form in contact_form.html uses method = "post ". If data is obtained through POST in the view, request. GET is null.
Here, there are two required items: subject and message, so you need to verify the two. Note: We use the request. POST. get () method and provide an empty string as the default value. this method can solve the key loss and null data problems.
Although email is not required, we also need to verify if the value of her is submitted. Our verification algorithm is quite weak. it only verifies whether the value contains @ characters. In practical applications, more robust verification mechanisms are required (Django provides these verification mechanisms and we will see them later ).
We use the django. core. mail. send_mail function to send e-mail. This function has four required parameters: Topic, body, sender and recipient list. Send_mail is a convenient packaging of Django's EmailMessage class. the EmailMessage class provides more advanced methods, such as attachments, multiple emails, and complete control over the mail header.
Note: If you want to use the send_mail () function to send emails, configure the server to be able to send emails externally and set the outbound server address in Django. See specification: http://docs.djangoproject.com/en/dev/topics/email/
After the email is successfully sent, we use the HttpResponseRedirect object to redirect the webpage to a page containing successful information. The page containing successful information is left to the reader for writing (a simple view/URL ing/template), but we need to explain why the page is redirected to the new page, instead of directly calling render_to_response () in the template for output.
The reason is: if you refresh a page containing the POST form, the request will be resent, causing repeated requests. This usually results in unexpected results, such as duplicate database records. In our example, two identical emails will be sent. If the user is redirected to another page after the POST form, duplicate requests will not be generated.
We should redirect the successful POST request every time. This is the best practice for web development.
The contact () view works normally, but its verification function is somewhat complicated. Imagine if a form contains a dozen fields, we must write the if judgment statement corresponding to each field?
Another problem is that the form is re-displayed. If the data verification fails, it is recommended that the fields in the returned form of the client be filled with the data originally submitted so that the user can check where an error occurs (the user does not need to fill in the correct field value again ). You can manually return the original submitted data to the template and edit the fields in HTML to fill in the original values.
# views.pydef contact(request): errors = [] if request.method == 'POST': if not request.POST.get('subject', ''): errors.append('Enter a subject.') if not request.POST.get('message', ''): errors.append('Enter a message.') if request.POST.get('email') and '@' not in request.POST['email']: errors.append('Enter a valid e-mail address.') if not errors: send_mail( request.POST['subject'], request.POST['message'], request.POST.get('email', `'noreply@example.com`_'), [`'siteowner@example.com`_'], ) return HttpResponseRedirect('/contact/thanks/') return render_to_response('contact_form.html', { 'errors': errors, **'subject': request.POST.get('subject', ''),** **'message': request.POST.get('message', ''),** **'email': request.POST.get('email', ''),** })# contact_form.html Contact us Contact us {% if errors %}
{% for error in errors %}
- {{ error }}
{% endfor %}
{% endif %}
This looks messy and prone to errors when writing. I hope you will understand the purpose of using the advanced database-to process forms and related verification tasks.