Tutorials for writing contact forms in the Django framework

Source: Internet
Author: User
Tags contact form
While we have been using the sample form of book search and will improve it perfectly, this is still fairly rudimentary: it contains only one field, Q. For this simple example, we don't need to use a Django form library to handle it. But a more complicated form needs to be dealt with in many ways, so let's take a look at a more complex example: Site Contact form.

This form includes user-submitted feedback and an optional e-mail address. When this form is submitted and the data passes validation, an e-mail message containing the user's submitted information is automatically sent to the site staff.

Let's 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, e-mail and feedback. In addition to the E-mail field is optional, the other two fields are required. Note that we use method= "post" instead of method= "get" because this form will have a server-side operation: Send an e-mail. Also, we copied the code for the error message displayed in the previous template search_form.html.

If we follow the previous section of the idea of writing the search () view, then a contact () View code should look like this:

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, this may be a question: whether the contact () view is placed in the books/views.py file. But the contact () view is not associated with the books app, so should this view be placed somewhere else? This doesn't matter, as long as the mappings between URLs and views are correctly set in Urlconf, Django will handle them correctly. I personally like to create a contact folder with the Books folder sibling. This folder includes empty __init__.py and views.py two files.

Now let's analyze the above code:

Verify that the value of the Request.method is ' POST '. This value does not exist when the user browses the form and appears only when the form is submitted. (In the following example, Request.method will be set to ' get ' because the browser uses get, not post, in normal web browsing.) Judging the value of Request.method is a good way to isolate the form display from the form processing.

We use request. Post instead of Request.get to get the data submitted. This is necessary because the Contact_form.html form uses the method= "post". If you get the data through post in the view, request. Get will be empty.

Here, there are two required fields, subject and message, so you need to verify both. Note that we use request. The Post.get () method, and provides an empty string as the default value, which solves the problem of key loss and empty data in a good way.

Although email is not required, we also need to verify if there is a value submitted to her. Our validation algorithm is quite weak, and only verifies that the value contains the @ character. In real-world applications, a more robust validation mechanism is required (Django provides these validation mechanisms, which we'll see later in the process).

We used the Django.core.mail.send_mail function to send an e-mail. This function has four required parameters: subject, body, sender, and recipient list. Send_mail is a handy wrapper for the Django Emailmessage class, and the Emailmessage class provides more advanced methods, such as attachments, multipart messages, and complete control over the headers of the message.

Note that to use the Send_mail () function to send mail, the server needs to be configured to send messages externally and to set the outbound server address in Django. See specification: http://docs.djangoproject.com/en/dev/topics/email/

When the message is sent successfully, we use the Httpresponseredirect object to redirect the page to a page that contains successful information. Pages that contain success information are left here for the reader to write (very simply a view/url map/a template), but we want to explain why redirect to a new page instead of calling Render_to_response () directly in the template to output.

The reason: If a user refreshes a page that contains a post form, the request will be re-sent causing duplication. This usually results in undesirable outcomes, such as duplicate database records, which in our case will result in the sending of two identical messages. If the user is redirected to a different page after the Post form, no duplicate requests will be created.

We should redirect the successful post request every time. This is the best practice for web development.

The contact () view works fine, but her validation is somewhat complex. Imagine that if a form contains a typing segment, we would really have to write the IF Judgment statement for each domain?

Another problem is the re-display of the forms. If data validation fails, the fields in the form returned to the client are preferably filled with the data that was originally submitted so that the user can see where the error occurred (and the user does not need to fill in the correct field values again). We can manually return the original commit data to the template, and we must edit the fields in the HTML to populate 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  <title>Contact Us</title>  

Contact Us

{% If errors%}
      {% for error in errors%}
    • {{Error}}
    • {% ENDFOR%}
{% ENDIF%}

This looks cluttered and error-prone when writing. I hope you begin to understand the purpose of using the advanced library--to handle forms and related validation tasks.

  • 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: info-contact@alibabacloud.com 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.