Django – Form Processing

Django – Form Processing ”; Previous Next Creating forms in Django, is really similar to creating a model. Here again, we just need to inherit from Django class and the class attributes will be the form fields. Let”s add a forms.py file in myapp folder to contain our app forms. We will create a login form. myapp/forms.py #-*- coding: utf-8 -*- from django import forms class LoginForm(forms.Form): user = forms.CharField(max_length = 100) password = forms.CharField(widget = forms.PasswordInput()) As seen above, the field type can take “widget” argument for html rendering; in our case, we want the password to be hidden, not displayed. Many others widget are present in Django: DateInput for dates, CheckboxInput for checkboxes, etc. Using Form in a View There are two kinds of HTTP requests, GET and POST. In Django, the request object passed as parameter to your view has an attribute called “method” where the type of the request is set, and all data passed via POST can be accessed via the request.POST dictionary. Let”s create a login view in our myapp/views.py − #-*- coding: utf-8 -*- from myapp.forms import LoginForm def login(request): username = “not logged in” if request.method == “POST”: #Get the posted form MyLoginForm = LoginForm(request.POST) if MyLoginForm.is_valid(): username = MyLoginForm.cleaned_data[”username”] else: MyLoginForm = Loginform() return render(request, ”loggedin.html”, {“username” : username}) The view will display the result of the login form posted through the loggedin.html. To test it, we will first need the login form template. Let”s call it login.html. <html> <body> <form name = “form” action = “{% url “myapp.views.login” %}” method = “POST” >{% csrf_token %} <div style = “max-width:470px;”> <center> <input type = “text” style = “margin-left:20%;” placeholder = “Identifiant” name = “username” /> </center> </div> <br> <div style = “max-width:470px;”> <center> <input type = “password” style = “margin-left:20%;” placeholder = “password” name = “password” /> </center> </div> <br> <div style = “max-width:470px;”> <center> <button style = “border:0px; background-color:#4285F4; margin-top:8%; height:35px; width:80%;margin-left:19%;” type = “submit” value = “Login” > <strong>Login</strong> </button> </center> </div> </form> </body> </html> The template will display a login form and post the result to our login view above. You have probably noticed the tag in the template, which is just to prevent Cross-site Request Forgery (CSRF) attack on your site. {% csrf_token %} Once we have the login template, we need the loggedin.html template that will be rendered after form treatment. <html> <body> You are : <strong>{{username}}</strong> </body> </html> Now, we just need our pair of URLs to get started: myapp/urls.py from django.conf.urls import patterns, url from django.views.generic import TemplateView urlpatterns = patterns(”myapp.views”, url(r”^connection/”,TemplateView.as_view(template_name = ”login.html”)), url(r”^login/”, ”login”, name = ”login”)) When accessing “/myapp/connection”, we will get the following login.html template rendered − On the form post, the form is valid. In our case make sure to fill the two fields and you will get − In case your username is polo, and you forgot the password. You will get the following message − Using Our Own Form Validation In the above example, when validating the form − MyLoginForm.is_valid() We only used Django self-form validation engine, in our case just making sure the fields are required. Now let’s try to make sure the user trying to login is present in our DB as Dreamreal entry. For this, change the myapp/forms.py to − #-*- coding: utf-8 -*- from django import forms from myapp.models import Dreamreal class LoginForm(forms.Form): user = forms.CharField(max_length = 100) password = forms.CharField(widget = forms.PasswordInput()) def clean_message(self): username = self.cleaned_data.get(“username”) dbuser = Dreamreal.objects.filter(name = username) if not dbuser: raise forms.ValidationError(“User does not exist in our db!”) return username Now, after calling the “is_valid” method, we will get the correct output, only if the user is in our database. If you want to check a field of your form, just add a method starting by “clean_” then your field name to your form class. Raising a forms.ValidationError is important. Print Page Previous Next Advertisements ”;

Django – Overview

Django – Overview ”; Previous Next As you already know, Django is a Python web framework. And like most modern framework, Django supports the MVC pattern. First let”s see what is the Model-View-Controller (MVC) pattern, and then we will look at Django’s specificity for the Model-View-Template (MVT) pattern. MVC Pattern When talking about applications that provides UI (web or desktop), we usually talk about MVC architecture. And as the name suggests, MVC pattern is based on three components: Model, View, and Controller. Check our MVC tutorial here to know more. DJANGO MVC – MVT Pattern The Model-View-Template (MVT) is slightly different from MVC. In fact the main difference between the two patterns is that Django itself takes care of the Controller part (Software Code that controls the interactions between the Model and View), leaving us with the template. The template is a HTML file mixed with Django Template Language (DTL). The following diagram illustrates how each of the components of the MVT pattern interacts with each other to serve a user request − The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user. Print Page Previous Next Advertisements ”;

Django – Update Data

Django – Update Data ”; Previous Next Django ORM uses the Active Record pattern for the interaction between a model class and its mapped database table. An instance of the model class corresponds to a single row in the table. Any of the attributes of the object results in updating the corresponding row. In this chapter, we will focus on the different ways available in Django to update an already existing row in a relational database. We shall use the Dreamreal model as given below for the exercise − class Dreamreal(models.Model): website = models.CharField(max_length=50) mail = models.CharField(max_length=50) name = models.CharField(max_length=50) phonenumber = models.IntegerField() def __str__(self): return “Website: {} Email: {} Name: {} Ph.: {}”.format(self.website, self.mail, self.name, self.phonenumber) It is assumed that you have already performed the migrations and added a few objects in the model. Update Object From Shell Django has a useful feature with which you can invoke a Python shell inside the Django project’s environment. Use the shell command with the manage.py script − python manage.py shell In front of the Python prompt, import the Dreamreal model − >>> from myapp.models import Dreamreal The model.objects attribute returns the model Manager, and its all() method returns a QuerySet. We can limit the objects in the set by applying the filter. To return the object with its primary key as 2, use the following statement − obj = Dreamreal.objects.filter(pk = 2) The model class has the get() instance method with which we can change the value of one or more attributes. obj.update(f1=v1, f2=v2, . . .) Let us update the name of the object with “pk = 2” − obj.update(name=”example”) The model manager also has a get() method that fetches a single instance corresponding to the given keyword argument − obj = Dreamreal.objects.get(phonenumber = 2376970) We can use a simple assignment to update an attribute. Let us change the phone number − obj.phonenumber = 24642367570 To make the change persistent, you need to call the save() method − obj.save() Perform Update Operation by Calling a View Function Let us now perform the update operation by calling a view function. Define the update() function in views.py file. This function receives the primary key as the argument from its mapped URL. from django.shortcuts import render from django.http import HttpResponse from myapp.models import Dreamreal def update(request, pk): obj = Dreamreal.objects.get(pk=pk) obj.name=”admin” obj.save() return HttpResponse(“Update successful”) We also need to register this view in the urls.py file by adding a new path − from django.urls import path from . import views from .views import DRCreateView, update urlpatterns = [ path(“”, views.index, name=”index”), path(“addnew/”, views.addnew, name=”addnew”), path(“update/<int:pk>”, views.update, name=”update”), ] Run the Django server and visit the URL http://localhost:8000/myapp/update/2. The browser emits the update success message. Instead of using the hard-coded values as in the above example, we would like the data to be accepted from the user. We need to populate a HTML form with the object data corresponding to the primary key. Modify the update() View Function Modify the update() view function as shown − from django.shortcuts import render from django.http import HttpResponse from myapp.models import Dreamreal def update(request, pk): obj = Dreamreal.objects.get(pk=pk) if request.method == “POST”: ws = request.POST[”website”] mail = request.POST[”mail”] nm = request.POST[”name”] ph = request.POST[”phonenumber”] obj.name = nm obj.phonenumber = ph obj.save() return HttpResponse(“<h2>Record updated Successfully</h2>”) obj = Dreamreal.objects.get(pk=pk) context = {“obj”:obj} return render(request, “myform.html”, context) We need to populate the form elements with the values of object attributes with the template variables. Modify the myform.html script as follows − <html> <body> <form action=”../update/{{ obj.pk }}” method=”post”> {% csrf_token %} <p><label for=”website”>WebSite: </label> <input id=”website” type=”text” value = {{ obj.website }} name=”website” readonly></p> <p><label for=”mail”>Email: </label> <input id=”mail” type=”text” value = {{ obj.mail }} name=”mail” readonly></p> <p><label for=”name”>Name: </label> <input id=”name” type=”text” value = {{ obj.name }} name=”name”></p> <p><label for=”phonenumber”>Phone Number: </label> <input id=”phonenumber” type=”text” value = {{ obj.phonenumber }} name=”phonenumber”></p> <input type=”submit” value=”Update”> </form> </body> </html> Visiting the URL http://localhost:8000/myapp/update/2 renders a HTML form pre-populated with the data belonging to pk=2. User can update the name and phonenumber fields. Using ModelForm for Update Next, we shall use the ModelForm class to render a HTML form with its input elements corresponding to the model field types. Let use the DereamrealForm class that inherits the Modelform from django import forms from .models import Dreamreal class DreamrealForm(forms.ModelForm): class Meta: model = Dreamreal fields = “__all__” def __init__(self, *args, **kwargs): super(DreamrealForm, self).__init__(*args, **kwargs) self.fields[”website”].widget = forms.TextInput(attrs={”readonly”: ”readonly”}) self.fields[”mail”].widget = forms.TextInput(attrs={”readonly”: ”readonly”}) Note − Here, we have set the readonly property of the website and mail fields in the class constructor. The View function update() receives the primary key argument from the URL as before. When this function is called with POST method, the form data is used to update the existing object. When the GET method is used, Django fetches the object corresponding to the primary key, and uses its attributes to populate the HTML form − def update(request, pk): obj = Dreamreal.objects.get(pk=pk) if request.method == “POST”: form = DreamrealForm(request.POST) if form.is_valid(): form.save() return HttpResponse(“<h2>Record updated Successfully</h2>”) obj = Dreamreal.objects.get(pk=pk) context = {“obj”: DreamrealForm(instance=obj), “pk”: obj.pk} return render(request, “myform.html”, context) Visit the http://localhost:8000/myapp/update/1 URL to display the HTML form with its fields filled with the record with pk=1. You can change the values and submit for the corresponding object to be updated. The UpdateView Class Django defines a collection of generic view classes. The UpdateView class is specially designed for performing the INSERT query operation. We define a subclass of UpdateView class and set its template_name property to myform.html that we have already created.

Django – MVT

Django – MVT Architecture ”; Previous Next Most of the web frameworks implement the MVC (Model-View-Controller) architecture. Django uses a variation of MVC and calls it the MVT (stands for Model-View-Template) architecture. The Advantage of Using a Web Framework A software framework, in general, is a standard, reusable software platform that facilitates rapid development of software applications. In contrast, a web framework (also called web application framework) such as Django provides a generic functionality needed for building web applications, APIs and web services. The main advantage of employing a web framework is that it provides out-of-the-box support to perform common operations in the process of web development. For example, you can easily connect your application to the databases. Usually, the framework handles tasks such as session management much more efficiently. Likewise, it integrates with templating tools to render dynamic content on web page. The MVC Architecture This design pattern separates the entire process of web application development in three layers. The following diagram explains the interplay of these three layers. In the MVC approach, the user requests are intercepted by the controller. It coordinates with the view layer and the model layer to send the appropriate response back to the client. The Model Layer The Model is known as the lowest level which means it is responsible for maintaining the data. It handles data. The model layer is connected to the database. It responds to the controller requests because the controller never talks to the database by itself. The model talks to the database back and forth and then it gives the needed data to the controller. The model is responsible for data definitions, its processing logic and interaction with the backend database. The View Layer The View is the presentation layer of the application. It takes care of the placement and formatting of the result and sends it to the controller, which in turn, redirects it to the client as the application’s response. Data representation is done by the view component. It actually generates the UI or user interface for the user. So, at web applications, when you think of the View component, just think the HTML/CSS part. Views are created by the data which is collected by the model component but these data aren’t taken directly but through the controller, so the view only speaks to the controller. The Controller Layer It coordinates with the View layer and the model layer to send the appropriate response back to the client. The Controller layer receives the request from the client, and forwards it to the model layer. The Model layer updates the data and sends back to the controller. The Controller updates the view and sends back the response to the user. The MVT Architecture The Django framework adapts a MVT approach. It is a slight variation of the MVC approach. The acronym MVT stands for Model, View and Template. Here too, the Model is the data layer of the application. The View is in fact the layer that undertakes the processing logic. The Template is the presentation layer. Components of a Django Application A Django application consists of the following components − URL dispatcher View Model Template The URL Dispatcher Django’s URL dispatcher mechanism is equivalent to Controller in the MVC architecture. The urls.py module in the Django project’s package folder acts as the dispatcher. It defines the URL patterns. Each URL pattern is mapped with a view function to be invoked when the client’s request URL is found to be matching with it. The URL patterns defined in each app under the project are also included in it. When the server receives a request in the form of client URL, the dispatcher matches its pattern with the patterns available in the urls.py and routes the flow of the application towards its associated view. The View Function The View function reads the path parameters, query parameters and the body parameters included in the client’s request. It uses this data to interact with the models to perform CRUD operations, if required. The Model Class A Model is a Python class. Django uses the attributes of the Model class to construct a database table of a matching structure. Django’s Object Relational Mapper helps in performing CRUD operations in an object oriented way instead of invoking SQL queries. The View uses the data from the client as well as the model and renders its response in the form of a template. Template A Template is a web page in which HTML script is interspersed with the code blocks of Django Template Language. Django’s template processor uses any context data received from the View is inserted in these blocks so that a dynamic response is formulated. The View in turn returns the response to the user. This is how Django’s MVT architecture handles the request-response cycle in a web application. Print Page Previous Next Advertisements ”;

Django – Index Page

Django – Index Page ”; Previous Next When a new Django project is created with the startproject command, the URL http://localhost:8000/ shows a default index page. It shows that the Django installation is done successfully. Create a project with the following command − django-admin startproject myproject Now that your project is created and configured, make sure it”s working − python manage.py runserver On running the above command, you will get to see something like the following on your screen − Validating models… 0 errors found March 09, 2022 – 12:24:26 Django version 4.0, using settings ”myproject.settings” Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK.Quit the server with CONTROL-C. The development server is running at http://127.0.0.1:8000/. Open the link in the browser. In the main “myproject” folder, use the manage.py command − python manage.py startapp myapp You just created the myapp application. Django also creates a “myapp” folder with the application structure − myapp/ __init__.py admin.py models.py tests.py views.py __init__.py − Just to make sure python handles this folder as a package. admin.py − This file helps you make the app modifiable in the admin interface. models.py − This is where all the application models are stored. tests.py − This is where your unit tests are. views.py − This is where your application views are. Update the INSTALLED_APPS list in the settings.py file of your project (add your app name) − INSTALLED_APPS = [ ”django.contrib.admin”, ”django.contrib.auth”, ”django.contrib.contenttypes”, ”django.contrib.sessions”, ”django.contrib.messages”, ”django.contrib.staticfiles”, ”myapp”,] We will create a simple view in myapp to say “welcome to my app!“ Open “myappviews.py” and add the following view function − from django.shortcuts import render # Create your views here. def index(request): # other view code here return render(request, index.html”, {}) In this view, we use HttpResponse to render the HTML page. To see this view as a page, we just need to map it to a URL. Save the following Python script as myapp/urls.py − from django.urls import path from . import views urlpatterns = [ path(””, views.index, name=”index”), ] The next step is to point the root URLconf at the myapp.urls module. In myproject/urls.py, add an import for django.urls.include and insert an include() in the urlpatterns list, so you have − from django.contrib import admin from django.urls import include, path urlpatterns = [ path(””, include(”myapp.urls”)), path(”admin/”, admin.site.urls), ] Now run the Django development server − python manage.py runserver Visit the following URL to verify that the hello() view is rendered − http://localhost:8000/ You should be able to see the output of the index page. A Django Home Page with Multiple Apps However, a Django project may have more than one apps in it. Hence, the project home page should contain the links to the home pages of individual apps. Let us create two apps in the current Django project − python manage.py startapp customers And, python manage.py startapp products Rewrite the main index page of the project as − <!Doctype html> <html> <body> <!–header–> <div style=”height:10%;”> <h2 align=”center”>My Web Application</h2> <hr> </div> <div style=”width:100%;”> <!—side bar–> <div style=”width:20%; float:left; border-right-style:groove”> <ul> <b> <li><a href=”admin/”>Admin</a></li> <li><a href=”customers/”>Customers</a></li> <li><a href=”Products/”>Products</a></li> </b> </ul> </div> <!–contents–> <div style=”margin-left:21%;”> <p> <h2 align=”center”>Main Index Page</h2> </p> </div> </div> <br><br><br> <!–footer–> <hr> <div> <h4 align=”right”>All rights reserved</h4> </div> </body> </html> The index page for the customer app should be saved in the templates directory. It is rendered by the view in customers/views.py file − from django.shortcuts import render # Create your views here. def index(request): return render(request, “customerindex.html”, {}) Similarly, the index page for products app is created and its mapped view is defined in the “products/views.py” file − from django.shortcuts import render # Create your views here. def index(request): return render(request, “productindex.html”, {}) You also need to define the urlpattern list for each app as − from django.urls import path from . import views urlpatterns = [ path(“”, views.index, name=”customer-index”), ] Similarly, do the following for the products app − from django.urls import path from . import views urlpatterns = [ path(“”, views.index, name=”product-index”), ] Update the URLCONF of the myproject/urls.py file − from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path(”admin/”, admin.site.urls), path(”products/”, include(“products.urls”)), path(”customers/”, include(“customers.urls”)), path(””, views.index, name=”index”), ] Run the Django server and visit the root URL of the Django project (http://localhost:8000/) − Print Page Previous Next Advertisements ”;