Form Processing in Django
Creation of forms in Django is done in a similar way to creating models. We just have to inherit from our Django class and the form fields will be our class attributes. First, add a file named “forms.py” in the folder named “myapplication”. This file will hold our forms. We will demonstrate this by creating a login form:
#-*- coding: utf-8 -*-
from django import forms
class MyForm(forms.Form):
user = forms.CharField(max_length = 80)
pwd = forms.CharField(widget = forms.PasswordInput())
In our case, our password will be hidden and that is why we have used the above widget. There are a number of widgets in Django that you can make use of whenever you are creating your forms.
- How to use a Form in a View :-
“GET” and “POST” are the two types of HTTP requests. The request object in Django that is passed as a parameter as a view has an attribute named “method”. This is where the type of request is set. ,The request can be used for accessing all the data that has been passed to the POST.
The login view can be created as follows:
#-*- coding: utf-8 -*-
from myapplication.forms import LoginForm
def login(request):
username = “not yet logged in”
if request.method == “POST”:
#Getting the posted form
LoginForm = MyForm(request.POST)
if LoginForm.is_valid():
username = LoginForm.cleaned_data[‘username’]
else:
LoginForm = Myform()
return render(request, ‘loggedin.html’, {“username” : username})
Our view will display the result of our login form, which has been posted via the “loggedin.html”. For the purpose of testing, the login form template is needed. This can be called “login.html”. It is shown below:
<html>
<body>
<form name = “form” action = “{% url “myapplication.views.login” %}”
method = “POST” >{% csrf_token %}
<div style = “max-width:460px;”>
<center>
<input type = “text” style = “margin-left:19%;”
placeholder = “Username” name = “username” />
</center>
</div>
<br>
<div style = “max-width:460px;”>
<center>
<input type = “password” style = “margin-left:19%;”
placeholder = “password” name = “password” />
</center>
</div>
<br>
<div style = “max-width:460px;”>
<center>
<button style = “border:0px; background-color:#4285F4; margin-top:9%;
height:36px; width:79%;margin-left:20%;” type = “submit”
value = “Login” >
<strong>Login</strong>
</button>
</center>
</div>
</form>
</body>
</html>
Our template will show a login form and then post the result to a login view as shown above. You might have noticed the tag used in the template, which will work to prevent a “Cross-site Request Forgery (CSRF)” attack on our site.
{% csrf_token %}
Now that we are having our “Lofin.html” template, we need to have the template “loggedin.html” and this will be rendered after the form has been treated. This is shown below:
<html>
<body>
Your username is : <strong>{{username}}</strong>
</body>
</html>
Only the pair of the URLs is remaining for us to get started. These should be defined in the file “myapplication/urls.py” as shown below:
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
upatterns = patterns(‘myapplication.views’,
url(r’^connection/’,TemplateView.as_view(template_name = ‘login.html’)),
url(r’^login/’, ‘login’, name = ‘login’))
- Form Validation :-
Our form can be validated by use of the method given below:
MyForm.is_valid()
That is self-validation engine for the Django. This will ensure that our fields are required. We now want to make sure that a user who logs into the system is present in the database. For this to be done, the file “myapplication/forms.py” has to be changed to the following:
#-*- coding: utf-8 -*-
from django import forms
from myapplication.models import Dreamreal
class MyForm(forms.Form):
user = forms.CharField(max_length = 90)
pwd = forms.CharField(widget = forms.PasswordInput())
def clean_message(self):
username = self.cleaned_data.get(“username”)
user = Dreamreal.objects.filter(name = username)
f not user:
raise forms.ValidationError(“User is not in our db!”)
return username
Once the method “is_valid” has been called and the user has been found to be in the database, we will get the best output.
👈Episode 11(D). Episode 13(D)👉
Share This Post
PRINT THIS POST
No comments:
Post a Comment
If you have any doubts. Please let me know.