English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
myapp/forms.py
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 #-*- coding: utf-8 -*- from django import forms class LoginForm(forms.Form): user = forms.CharField(max_length = 100) password = forms.CharField(widget = forms.PasswordInput())
As can be seen from above, field types can use the 'widget' parameter to render to HTML; in our example, we want to hide the password and not display it. In our example, we want to hide the password without displaying it. The date input is DateInput, CheckboxInput is a checkbox, etc.
Use the form in the view
There are two types of HTTP requests, which are GET and POST. In Django, there is an attribute called "method" in the view request object passed as a parameter, where the type of request is set, and all data passed through POST can be accessed via the request.POST dictionary.
Let's create it in the "myapp/views.py Create a login view -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 #-*- 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})
This view will display the form result with "loggedin.html" upon login. To test it, we first need the login form template. Let's name it: login.html.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 <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: 0%; margin20%;" placeholder="Identifiant" name="username" /> </center> </div> <br> <div style="max-width:470px;"> <center> <input type="password" style="margin-left: 0%; margin20%;" placeholder="password" name="password" /> </center> </div> <br> <div style="max-width:470px;"> <center> <button style="border:0px; background-color:#4285F4color:#-F8top: ; margin %;35height:8px; width:-left: 0%; margin19; type = "submit" value = "Login" > <strong>Login</strong> </button> </center> </div> </form> </body> </html>
The template will display a login form and post the results we viewed above. You may have noticed that the template is just a tag to prevent cross-site request forgery (CSRF) attacks on your website.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 {% csrf_token %}
Once we have the login template, we need to present the loggedin.html template after processing the form.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 <html> <body> You are: <strong>{{username}}</strong> </body> </html>
Now, we just need to start with the URLs: myapp/urls.py
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 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" and we will get the login.html template displayed as follows -
After submitting the above table, the format is valid. In our instance, you must fill in two fields to get the following result -
If your username is polo and if you forget your password, you will receive the following message -
Using our own form validation
In the above instance, the form is validated as follows -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 MyLoginForm.is_valid()
We only use Django's built-in form validation engine, ensuring that this field is required in the instance. Now let's try to ensure that the user attempting to log in exists in our database as a Dreamreal item. For this, modify myapp/forms.py is for -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 #-*- 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 when the user is in our database. If you want to query form fields, you can simply add a method starting with 'clean_' with the field name corresponding to the form class field. It is very important to raise a forms.ValidationError error.