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 object 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

{% csrf_token %} {{ from.as_p }}
  • method="POST": It refers to the Http POST request. The default is GET.
  • csrf_token: It is a security token to prevent against Cross site reference forgery.
  • The form requires an submit button apart from model field elements, to trigger form submisison.