the red penguin
HOME ABOUT SITEMAP BLOG LOGIN

31. Django forms (2) – using the ModelForm class

Django also provides a more straight-forward way to approach building forms against our models. We can actually just use the model itself to specify our forms.

There’s a class called ModelForm we can use instead – so let’s look at using that.

Let’s go first to index.html and create a link to a new path:

Create Gene Entry

Add Gene Entry

Next we go to urls.py and add this to urlpatterns:

path('create_gene/', views.create_gene, name='create_gene'),

We’ve now specified a function, create_gene, that is yet to exist. So we can go to views.py and add this function:

def create_gene(request):
    if request.method == 'POST':
        form = GeneForm(request.POST)
    else:
        master_genes = Gene.objects.all()
        form = GeneForm()
    return render(request, 'genedata/create_gene.html', {'form': form, 'master_genes': master_genes})

It’s very similar to the create_ec function in the last post. We can use this approach if we don’t need to clean data, like we did last time.

In forms.py we need to import ModelForm:

from django.forms import ModelForm

And we’re going to make use of the models we’ve already written, which will stop us needing to define specific fields like forms.CharField, etc.

from .models import *

Now we can create the GeneForm function we referred to in the create_gene function earlier:

class GeneForm(ModelForm):
    class Meta:
        model = Gene
        fields = ['gene_id', 'entity', 'start', 'stop', 'sense', 'start_codon', 'sequencing', 'ec']

This basically says we’re going to use our Gene model, and we can provide a list of fields that are going to be presented in the form.

We now need to make a create_gene.html template, which we create in templates/genedata:

As before we need this in the template:

{% extends "./base.html" %}
{% load bootstrap4 %}

{% block content %}
...
{% endblock%}

Then we need to add the form:

{% extends "./base.html" %}
{% load bootstrap4 %}

{% block content %}

Add New Gene

{% csrf_token %} {% bootstrap_form form %}
{% endblock%}

What happens here is that Bootstrap renders the form with nice styling and layout.

When we look at our form field, we come back to our form. sequencing and ec are foreign keys, so the relevant drop-down menus will be provided for us.

We can now go back to views.py and add a bit more code – if the form is valid, we can save it and return the user to a new url where they can add another gene if they so desire.

def create_gene(request):
    if request.method == 'POST':
        form = GeneForm(request.POST)
        if form.is_valid():
            gene = form.save()
            return HttpResponseRedirect('/create_gene/')
    else:
        master_genes = Gene.objects.all()
        form = GeneForm()
    return render(request, 'genedata/create_gene.html', {'form': form, 'master_genes': master_genes})

You can now see the form on the page:

We can now enter a new gene, and press submit. It will appear in the gene list on the side of the page.

Here is some more information in using ModelForms: https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/

Wednesday 17 November 2021, 452 views


Leave a Reply

Your email address will not be published. Required fields are marked *