Reputation: 3
forms.py
from django.contrib.auth.models import User
from django import forms
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class meta:
model = User
fields = ['username','email','password']
view.py
class UserFormView(View):
form_class = UserForm
template_name = "music/registration_form.html"
# display blank form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
# process form data
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
# cleaned normalized data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
# returns user object if credentials are correct
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('music:index')
return render(request, self.template_name, {'form': form})
and thats django error
ValueError at /music/register/
ModelForm has no model class specified.
Request Method: GET
Request URL: http://127.0.0.1:8000/music/register/
Django Version: 1.10.3
Exception Type: ValueError
Exception Value:
ModelForm has no model class specified.
Exception Location: C:\Python34\lib\site-packages\django-1.10.3-py3.4.egg\django\forms\models.py in __init__, line 275
Python Executable: C:\Python34\python.exe
Python Version: 3.4.0
Python Path:
['C:\\Users\\HP\\desktop\\projweb',
'C:\\Python34\\lib\\site-packages\\django-1.10.3-py3.4.egg',
'C:\\Windows\\SYSTEM32\\python34.zip',
'C:\\Python34\\DLLs',
'C:\\Python34\\lib',
'C:\\Python34',
'C:\\Python34\\lib\\site-packages']
Server time: Sat, 17 Dec 2016 23:35:40 +0300
the error is in the
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
Upvotes: 0
Views: 601
Reputation: 91525
To retrieve the form use get_form
instead as it does some initialization:
form = self.get_form()
If you don't pass a form_class
to get_form()
then it will default to the whatever get_form_class()
returns.
Upvotes: 1