The following article demonstrates an Example of Creating a Django Form.
- Create a new Django app.
python manage.py startapp myapp
- Open the “views.py” file inside your app’s directory and add the following.
from django.shortcuts import render
from .forms import MyForm
def my_view(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
# process form data
pass
else:
form = MyForm()
return render(request, 'my_template.html', {'form': form})
This defines a new view named “my_view” that uses a form named “MyForm”. The view checks whether the request method is “POST” (indicates form submission), and if so, it validates the form data and processes it. If the request method is not “POST”, it creates a new instance of the form.
- Create a new file named “forms.py” inside your app’s directory and add the following code:
from django import forms
class MyForm(forms.Form):
name = forms.CharField(label='Your name', max_length=100)
email = forms.EmailField(label='Your email')
message = forms.CharField(label='Your message', widget=forms.Textarea)
This defines a new form named “MyForm” with three fields: “name”, “email”, and “message”. The fields use various form field classes from Django’s forms module.
- Create a new file named “my_template.html” inside your app’s “templates” directory and add the following code.
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
This creates an HTML form that uses the “POST” method to submit data, includes a CSRF token for security, and renders the fields of the form using the “as_p” method of the form object.
- Finally, add a URL pattern for your new view in your project’s “urls.py” file.
from django.urls import path
from myapp.views import my_view
urlpatterns = [
path('my-form/', my_view, name='my_form'),
]
This maps the URL “/my-form/” to your new view.
Now you can run your Django development server and visit the URL “/my-form/” to see your new form in action!
Further Reading
Introduction to Django Framework and its Features
Examples of Array Functions in PHP
Registration Form Using PDO in PHP
Inserting Information from Multiple CheckBox Selection in a Database Table in PHP