0
0
Djangoframework~30 mins

Displaying forms in templates in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Displaying Forms in Django Templates
📖 Scenario: You are building a simple web page where users can submit their contact information using a form. You want to display this form on a webpage using Django templates.
🎯 Goal: Create a Django form in Python, configure it in your view, and display it properly in an HTML template.
📋 What You'll Learn
Create a Django form class with fields for name and email
Create a view function that creates an instance of this form
Pass the form instance to the template context
Display the form in the template using Django template syntax
💡 Why This Matters
🌍 Real World
Forms are essential for collecting user input on websites, such as contact forms, registration forms, and surveys.
💼 Career
Understanding how to display and handle forms in Django is a key skill for backend web developers working with Python and Django.
Progress0 / 4 steps
1
Create a Django form class
Create a Django form class called ContactForm in forms.py with two fields: name as a CharField and email as an EmailField.
Django
Need a hint?

Use forms.Form as the base class. Add name and email fields using forms.CharField() and forms.EmailField().

2
Create a view function with the form instance
In views.py, create a function called contact_view that creates an instance of ContactForm and stores it in a variable called form.
Django
Need a hint?

Define a function contact_view that takes request as a parameter. Inside, create form = ContactForm().

3
Pass the form to the template context
In the contact_view function, return a call to render with request, template name 'contact.html', and a context dictionary containing the key 'form' with the value form.
Django
Need a hint?

Use return render(request, 'contact.html', {'form': form}) to send the form to the template.

4
Display the form in the template
In the contact.html template, add the HTML code to display the form using Django template syntax: use {% csrf_token %} inside the <form> tag and display the form fields with {{ form.as_p }}. The form should use method post.
Django
Need a hint?

Use a <form method="post"> tag, include {% csrf_token %} for security, display the form fields with {{ form.as_p }}, and add a submit button.