Django – Forms

Objective: Create a Contact Us form.

  1. Stage 1: User sees a form to input his details. On submit a generic
    “Thank you” message would be displayed.
  2. Stage 2: Read the details and show him a customized “Thank you” message.

Stage 1: Standard Thanks Message

  1. Steps
    1. Create a form in forms.py
    2. Create two html templates – one for displaying form, one for “thanks” message
    3. Create two views – one for form, one for “thanks” message
    4. Add urls for the views
  2. Forms.py
    1. Create forms.py file under application ‘blog’ directory
    2. Image
  3. Html templates
    1. Contact_us.html
    2. Image
    3. Csrf_token: cross site request forgery protection
    4. Form.as_p : wraps all the form elements in <p> tag. ( alternatives: form.as_table , form.as_ul)
    5. action= “” : action is blank in template. view will define the action when form is submitted.
    6. Contact_success.html
  4. Views.py
    1. Import the from: from .forms import ContactUsForm
    2. Image:
    3. On submit -> code in request.method ==”POST” executes.
    4. When page is accessed -> template will render the form and displays input fields.
  5. Define urls
    1. Image
  6. Check output

Stage 2: Customized Thanks Message

  1. Steps
    1. Update contact_success.html to read context and show first_name and last_name
    2. Update view definition to read data from request.POST and send to template for rendering
  2. Contact_success.html
  3. Views.py
  4. Check results

 

No tags for this post.