Django UserCreationForm错误:ModelForm没有指定模型类

时间:2017-02-15 05:20:01

标签: python django

我尝试为is_staff人创建页面可以创建用户。代码如下。

views.py

@login_required
def create_new_user(request):
    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('jobs:new-user'))
    else:
        form = CreateUserForm()
        return render(request, 'jobs/create_user.html', {'form': form})

forms.py

from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class CreateUserForm(UserCreationForm):
    class Meta:
        model: User
        fields = ['username', 'password1', 'password2']

错误输出

这是我尝试访问帐户创建页面时遇到的错误。

Traceback:

File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/jobs/views.py" in create_new_user
  124.         form = CreateUserForm()

File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/contrib/auth/forms.py" in __init__
  96.         super(UserCreationForm, self).__init__(*args, **kwargs)

File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/forms/models.py" in __init__
  275.             raise ValueError('ModelForm has no model class specified.')

Exception Type: ValueError at /create_user/
Exception Value: ModelForm has no model class specified.

有什么想法吗?一如既往,谢谢你

1 个答案:

答案 0 :(得分:2)

您需要将模型设置为与model = User

类似的用户
class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'password1', 'password2']