Reputation: 35
I created a form which has login option. I want to show the username which was given in the username label in the python console. Here is my views.py file:
from django.views.generic import TemplateView
from django.shortcuts import render
from app.forms import *
class login(TemplateView):
template_name = 'app/login.html'
def clean(self):
form = RegistrationForm()
print form.cleaned_data['username']
The following is my forms.py file:
from django import forms
class RegistrationForm(forms.Form):
username = forms.CharField(label='Username', max_length=30)
password = forms.CharField(label='Password',
widget=forms.PasswordInput())
def clean_password(self):
username = self.cleaned_data['username']
This doesn't print what I wanted. Pls help me solve this.
Upvotes: 1
Views: 3989
Reputation: 599698
If you want to process a form in your class-based view, you need to use a base class that understands forms. In your case, a FormView would be the right one.
As well as that, you need to override a method that is actually called during the rendering process. You can't just define a random method and expect it to be invoked. The method of FormView that is called after the form is validated is called form_valid
. So:
class login(FormView):
template_name = 'app/login.html'
form_class = RegistrationForm
def form_valid(self, form):
print form.cleaned_data['username']
return super(FormView, self).form_valid(form)
Upvotes: 2
Reputation: 4603
You are creating a new Form object without supplying the POST data:
form = RegistrationForm(data=self.request.POST)
And as Daniel says in his comment the clean
method is likely never called for a TemplateView
. You might want to use FormView
or simply View
instead.
Your clean_password
function most likely isn't correct as well. It creates the local variable username
which is simply discarded after the function:
def clean_password(self):
username = self.cleaned_data['username']
Upvotes: 1