Django Forms

Django Forms can be used to move data in or out from models. An alternative to this is ModelAdmin but it is recommended to be used by the superuser or staff users only. An end-user of your web app must submit data from forms in template pages. We can choose to create fields in the form using HTML or ModelForm. In both cases, we begin by creating a new file named under our app directory.

        └── ...    
        └── ...

Django ModelForm

Similar to ModelAdmin we can use the ModelForm class and make a form object linking to the fields defined under

    from django import forms
    from .models import Blog
    class BlogForm(forms.ModelForm):
        class Meta:
            model = Blog
            fields = '__all__'

__all__ includes all fields under the model class. You may alternatively use a tuple of field names.

Now, this ModelForm object will be used under as below:

    from django.shortcuts import render, redirect
    from .forms import BlogForm
    def my_view_function(request):
        form = BlogForm(request.POST or None)
        if form.is_valid():
            return redirect('/mypageurl/')
        return render(request, 'my_template_page.html', {'form':form})
  • redirect: This function can redirect request objects to the given URL path.
  • request.POST: It will submit data posted in HTML form elements.
  • is_valid(): This function validates the form data against model field types and options.
  • save(): This function saves the data in the database.

Lastly, we are required to make a form element in our template page as below:

templates -- my_template_page.html

<form method="post">

<input type="submit" value="Submit">
  • method="POST": It refers to the HTTP POST request. The default is GET.
  • csrf_token: It is a security token to prevent Cross-site reference forgery.
  • The form requires a submit button apart from model field elements, to trigger form submission.