Answer the question
In order to leave comments, you need to log in
How to understand this piece of code in Django?
I started learning the Django framework from the book "Learning Website Development with Django". There was such a question.
Here is such a view:
def register_page(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
return HttpResponseRedirect('/register/success/')
else:
form = RegistrationForm()
variables = RequestContext(request, {
'form': form
})
return render_to_response('registration/register.html', variables)
{% extends "base.html" %}
{% block title %}User Registration{% endblock %}
{% block head %}User Registration{% endblock %}
{% block content %}
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="register" />
</form>
{% endblock %}
from django import forms
import re
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
class RegistrationForm(forms.Form):
username = forms.CharField(label='Username', max_length=30)
email = forms.EmailField(label='Email')
password1 = forms.CharField(
label='Password',
widget=forms.PasswordInput()
)
password2 = forms.CharField(
label='Password (Again)',
widget=forms.PasswordInput()
)
def clean_password2(self):
if 'password1' in self.cleaned_data:
password1 = self.cleaned_data['password1']
password2 = self.cleaned_data['password2']
if password1 == password2:
return password2
raise forms.ValidationError('Passwords do not match.')
def clean_username(self):
username = self.cleaned_data['username']
if not re.search(r'^\w+$', username):
raise forms.ValidationError('Username can only contain alphanumeric characters and the underscore.')
try:
User.objects.get(username=username)
except ObjectDoesNotExist:
return username
raise forms.ValidationError('Username is already taken.')
form = RegistrationForm(request.POST)
form = RegistrationForm()
Answer the question
In order to leave comments, you need to log in
1) You can not check, but use decorators or Class based view. Validation is used in the simplest views as in your example. Checking is needed to know what request came. If a POST request came, then the form was sent, if a GET request came, then the form needs to be displayed so that it can be sent later.
2) form = RegistrationForm(request.POST)
creates an object of the RegistrationForm class with data from request.POST, i.e. with data from a POST request; form = RegistrationForm()
creates an empty object of the RegistrationForm class
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question