Social Icons

Friday, July 3, 2020

Django Model Form

1 - About Django Model Form


Suppose we have a model containing various fields, we don't need to recode the fields in the html file. Django does this automatically for us to reduce application development time. This is a class used to create an HTML form using the existing model. In addition, the form created will be dynamic, i.e. it allows data to be inserted into the database. It is an effective way to create a form without writing HTML code. For this reason, Django provides the ModelForm helper class which allows us to create a Form class from a Django model.

2 - Creating a form using the ModelForm class 

To make it simple, we are going to create a form for a small student management application containing the following fields:
  1. name 
  2. email 
  3. section 
Before proceeding to the creation of a model, you must first create app called for example manageStudents:
python manage.py startapp manageStudents
and register it in to the mysite/settings.py file:
Then save your app in the file: settings.py:
settings.py
INSTALLED_APPS = [
    'manageStudents.apps.ManagestudentsConfig',
     xxxxxxxxxxxxxxxxx,
     xxxxxxxxxxxxxxxxx,]
Now create the model Students in the file models.py
manageStudents/models.py
from django.db import models
class Students(models.Model):
    name       =  models.CharField(max_length=25)
    email      =  models.EmailField(max_length=40)
    section    =  models.CharField(max_length=25)

    def __str__(self):  
        return self.name
Once the manageStudents model is created, django can use it to create a SQLite table containing the same attributes: name, email, section. To do this, make the migrations:
python manage.py makemigrations manageStudents
and
python manage.py migrate

3 - Creation of the form via the ModelForm class 


We will now see how to generate an input form automatically using the ModelForm class, containing the fields:
  1. name 
  2. email 
  3. section
 Let's create a python file named form.py in the manageStudents app and import the ModelForm class from django.forms and the Students class from manageStudent.models and then create a StudentsForm class which will be used to generate the html form :
 manageStudents/models.py
from django.forms import ModelForm
from manageStudents.models import Students

class StudentsForm(ModelForm):
    class Meta:
        model = Students
        fields = ['name' , 'email' , 'section']
Now we can create the views:
manageStudents/views.py
from django.shortcuts import render, redirect
from manageStudents.form import StudentsForm

def index(request):
    # testing if there is a sended post request
    if request.method == "POST":
        # creating a form
        form = StudentsForm(request.POST)
        # testing if the form is valid
        if form.is_valid():
            # saving the data form
            model_instance = form.save()
            # redirect user
            return redirect("/students")
    else:
        # else we create a form without saving any data
        form = StudentsForm()
        return render(request , 'index.html' , {'form' : form})
Then we configure the urls.py
manageStudents/urls.py
from django.contrib import admin
from django.urls import path
from manageStudents import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('students/' , views.index )
]
Now , we have to code the template file index.html:
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>Students management</h2>
<!-- Creating html form -->
<form method="POST" class="post−form">
<!-- adding security tag -->
{% csrf_token %}
<!-- adding form as paragraph (as_p = as paragraph) -->
{{ form.as_p }}
<!-- adding submit button -->
<button type="submit" class="save btn btn−default">Save</button>
</form>

</body>
</html>
Now after starting the server and type the url address: http://127.0.0.1:8000/students/
We will see our nice form appear:


Note 

The above form is functional, you can verify that it inserts the data correctly into the database.

4 - Display of data from the Students table 


To display the data from the manageStudents_students table, just import the Students class from manageStudents.models:
from manageStudents.models import Students
and add the value: Students.objects.all() to the dictionary:
{ 'form': form , 'dataObject': Students.objects.all()} 
Here is the final code of views.py file:
manageStudents/views.py
from django.shortcuts import render, redirect
from manageStudents.form import StudentsForm
from manageStudents.models import Students

def index(request):
    if request.method == "POST":
        form = StudentsForm(request.POST)
        if form.is_valid():
            model_instance = form.save()
            return redirect("/students")
    else:
        form = StudentsForm()
        return render(request , 'index.html' , {'form' : form , 'dataObject' : Students.objects.all()})
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>Students management</h2>

<form method="POST" class="post−form">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn−default">Save</button>
</form>
<h3>Student list:</h3>
{% for stud in dataObject %}
Name: {{ stud.name }}<br />
Email: {{ stud.email }}<br />
Section: {{ stud.section }}<br />
-------------------------------<br />
{% endfor %}

</body>
</html> 
Now launch the server and insert some data to see the result:




Younes Derfoufi
my-courses.net

No comments:

Post a Comment

Category Of Mobile Courses

Actualités (644) Adsense (1) Affiliation (1) Algebraic Topology (1) Algorithmic (1) all-news (30) Android (5) Android App (8) Android app without code (4) Android Apps (169) Android Development (4) Android download (2) Android OS (3) AngularJS (1) Automata theory and formal language (5) C programming (5) Category and Functor (8) CMS (3) Computer Glossary (18) Create Mobile App With Ionic Framework (2) CSS (2) CSS-Cascading-Style-Sheets (4) Developpement Java (13) Differential Geometry (1) Django-Python-Framework (8) dropshiping (26) Earn Money by Internet (4) Emplois (23) Framework php (2) Fraud (2) HTML (7) Java For Beginners (10) Javascript (12) Kotlin Programming Language (8) Kotlin For Mobile Android (1) Linux Download (2) Marketing (5) Mobile (3) Mobile Courses (4) Mobile Marketing (4) MoneyGram (1) News (721) Node.js (5) Open Source (1) Photoshop (1) Protect Computer (1) Python (33) Python BeautifulSoup (1) Python For Data Science (2) Python-Books (6) Python-DVD-Training (1) Python-Exercises (140) Python-Framework (1) Python-IDE (1) Python-Modules (1) Python-pdf (2) Python-pyQt (1) Référencement (2) Script PHP (2) Security (6) SEO (1) Snipping Tool: Faq (1) Social Networks (1) Source Code (1) Statistics With SPSS (2) Surveillance Software (1) Travail à domicile (6) Tutoriels php en vidéos (2) Tutoriels-MySql (6) tutoriels-php (19) Utilitaires (1) VPS (1) Web Hosting (1) Webcam (1) Webmarketing (11) Western Union (1) Windows 10 (1) Windows 7 (4) Windows 7 Faq (2) Windows 8 (1) Windows Accessories (1) Windows Download (8) Windows Drivers (1) Windows Fonts (1) Windows Power Shell (2) Windows Registry (2) Windows Security (18) Windows Software (2) Windows Spyware (2) Windows utilities (3) Windows Virus (2) Windows Vista (3) Windows Wireless (1) Windows xp (1) Wordpress (1)
 

Sample text

Sample Text

 
Blogger Templates