Django ModelForm错误

时间:2016-12-17 20:39:50

标签: django django-forms

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})

那就是django错误

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

错误在

def get(self, request):

        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

1 个答案:

答案 0 :(得分:1)

要检索表单,请使用get_form代替初始化:

form = self.get_form()

如果您没有将form_class传递给get_form(),那么它将默认为get_form_class()次返回。