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 %}{% endblock%}Add New Gene
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, 570 views
Next post: 32. Django validators Previous post: 30. Django forms (1)
Advanced Web Development index
- 38. Writing API tests
- 37. Testing in Django
- 36. Class-based views in the Django REST framework
- 35. Building a RESTful web service in Django
- 34. Introduction to CRUD, REST and APIs
- 33. Refactoring with generic views in Django
- 32. Django validators
- 31. Django forms (2) – using the ModelForm class
- 30. Django forms (1)
- 29. JavaScript basics
- 28. Adding CSS to the template
- 27. Django templating
- 26. Deleting and updating records
- 25. Joins, filters and chaining commands
- 24. Using the ORM in views.py
- 23. Adding to the database by writing a script
- 22. Adding to the database with Django Admin
- 21. Migrations
- 20. ORM – work through example
- 19. An introduction to the Object-Relational Mapper
- 18. Altering the database
- 17. SQL functions and summaries
- 16. SQL Query performance
- 15. Queries and table joins in SQL
- 14. Inserts and queries in SQL
- 13. Good practice in relational database design
- 12. Limitations to database modelling
- 11. Building a database using SQL
- 10. Introduction to PostgreSQL
- 9. How to start writing a new application in Django
- 8. Building a lightweight project
- 7. Django URLs
- 6. Django templates
- 5. Django models
- 4. Django views
- 3. Creating a new hello app
- 2. Creating a new virtual environment
- 1. Setting up Django
Leave a Reply