Django is a free and open source python based web-framework that allows us to develop interactive web applications with easy to use syntax. Django is used by some of the leading websites in the world such as Pinterest, Instagram, Mozilla, The Washington Times, and Bitbucket. The main focus for django apps is re-usability, in addition to various other components that are present in the core package such as caching, internationalization, middleware, serialization, to name a few. In order to summarize flexibilty and nature of apps building in django, let us take a look at ModelForm in django.
ModelForm might come in handy if you are developing a Django app and want to represent a database model as a form. In essence, a ModelForm is a helper class that allows you to create a Django Form from a pre-existing model. To further explain the concept of ModelForm let us a consider a django app say for example myapp that has all the pre-requisites of a Django project, such as creating a project and creating an app inside the project directory.
Now, in models.py let us create a model ‘Comment’:
from django.db import models class Comment(models.Model): title = models.CharField(max_length=100) text = models.CharField(max_length=255) notes = models.CharField(max_length=255) def __str__(self): # __unicode__ on Python 2 return self.title
Let us attach this model to a form by creating a ModelForm for it. So add a file ‘forms.py’ and add modelform in it.
from django.forms import ModelForm from myapp.models import Comment class MyCommentForm(ModelForm): class Meta: model = Comment fields = ['title', 'text', 'notes']
Once the ModelForm is set, we can process it by writing a simple view in views.py file, which most Django developers are familiar with.
from django.core.shortcuts import render, redirect from django import forms from django.utils import timezone from myapp.forms import MyCommentForm def add_model(request): if request.method == "POST": form = MyCommentForm(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.timestamp = timezone.now() model_instance.save() return redirect('/') else: form = MyCommentForm() return render(request, "my_template.html", {'form': form})
We can render the view to a template. For this create a template namely ‘my_template.html’
<DOCTYPE html> <html> <head> <title>edit</title> </head> <body> <form method="post" > {% csrf_token %} {{form}} <button type="submit" class="btn btn-default">Submit</button> </form> </body> </html>
The new add_model() view adds several key pieces of functionality for handling forms. First, we check HTTP request method, to determine if it was a HTTP GET or POST. We can then handle different requests methods appropriately – i.e. whether we want to show a form (if it is a GET), or process form data (if it is a POST) – all from the same URL. The add_model() view function can handle three different scenarios:
- Show a new, blank form for adding a category.
- Save form data provided by user to the associated model, and rendering app homepage.
- If there are errors, re-display the form with error messages.
Summarizing usage of ModelForms,
- ModelForms render Model fields as HTML.
- ModelForms save a lot of time and HTML Hassle.
- ModelForms select validators based off Model field definitions.
- ModelForms don’t have to display/change all available fields.
- ModelForms save dictionaries to SQL tables.
Great post! Exactly what I was looking for. So concise. Thanks and keep it up.