Reputation:
So I just created a form and keep getting this error, why? I correctly use the Cleaned_data after I checked if the form is valid, right?
This is my forms.py:
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
username = forms.CharField(max_length=10)
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password']
This is my views.py:
class UserFormView(View):
form_class = UserForm
template_name = 'Home/index.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
username = form.Cleaned_data['username']
password = form.Cleaned_data['password']
user.set_password(password)
user.save()
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('Home:Dashboard')
return render(request, self.template_name, {'form': form})
My urls.py:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^register$', views.UserFormView.as_view(), name='register'),]
and the form location:
<form action="/register" method="post">
{% csrf_token %}
<ul class="contactList">
<li id="username1" class="contact">{{ form.username }}</li>
<li id="email1" class="contact">{{ form.email }}</li>
<li id="password1" class="contact">{{ form.password }}</li>
</ul>
<input type="submit" value="Submit">
</form>
There are other topics about this issue but I could not get any help out of them, as most people didn't include the if form.is_valid(), but in my case I do.
Upvotes: 1
Views: 4946
Reputation: 645
Use form.cleaned_data.get('username')
instead of form.Cleaned_data
Edit
Use FormView
from django.views.generic.edit import FormView
class UserFormView(FormView):
form_class = UserForm
template_name = 'Home/index.html'
def form_valid(self, form):
user = form.save(commit=False)
username = form.cleaned_data.get('username')
...
get_form_class
returns the class of the form i.e UserForm
. You need is a object of that class. The class does not have any attribute cleaned_data
.
Upvotes: 2