A
A
Aitym Ramazanov2016-03-12 07:23:50
Django
Aitym Ramazanov, 2016-03-12 07:23:50

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)

There is template registration/register.html with POST form
{% 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 %}

and a class for our custom form:
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.')

And here are the actual questions:
1) Why is request.method == 'POST' checked in the view code? After all, I have a POST form and there can be no ambiguity. And what happens if this condition is not met?
2) What is the difference between
form = RegistrationForm(request.POST)
and
form = RegistrationForm()
and what does each do? More precisely, I know that the constructor for forms.Form is being called. But I do not know its implementation and I do not know what the result will be.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
asd111, 2016-03-12
@iTeam1991

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 question

Ask a Question

731 491 924 answers to any question