如何修复“ CreateView缺少查询集”

时间:2019-09-07 16:56:47

标签: python django

我正在尝试使用django应用来管理帐户和用户。 管理员用户可以访问django管理站点,并可以执行任何需要管理的用户。 具有用户权限的简单用户可以通过表单添加/修改用户,但不能访问django管理站点。

我正在尝试为简单用户添加CreateView以添加用户,但是我一直收到此错误:“ CreateView缺少QuerySet”

是否导致我扩展AbstractBase User? 有人可以解释一下这些查询集是什么以及如何修复我的代码吗?

谢谢

代码: `

#admin.py
class UserCreationForm(forms.ModelForm):
    password = forms.CharField(label='Mot de passe', widget=forms.PasswordInput)
    password_confirm = forms.CharField(label='Confirmation du mot de passe', widget=forms.PasswordInput)

    class Meta:
        model = UserProfile
        fields = ('first_name', 'last_name', 'email', 'perm_on_user', 'perm_on_news', 'is_admin',)

    def clean_password_confirm(self):
        # Check that the two password entries match
        password = self.cleaned_data.get("password")
        password_confirm = self.cleaned_data.get("password_confirm")
        if password and password_confirm and password != password_confirm:
            raise forms.ValidationError("Les mots de passes ne correcpondent pas")
        return password

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password"])
        if commit:
            user.save()
        return user

class UserModificationForm(forms.ModelForm):

    password = forms.CharField(label='Mot de passe', widget=forms.PasswordInput)
    password_confirm = forms.CharField(label='Confirmation du mot de passe', widget=forms.PasswordInput)

    class Meta:
        model = UserProfile
        fields = ('first_name', 'last_name', 'email', 'perm_on_user', 'perm_on_news', 'is_admin',)

    def clean_password_confirm(self):
        # Check that the two password entries match
        password = self.cleaned_data.get("password")
        password_confirm = self.cleaned_data.get("password_confirm")
        if password and password_confirm and password != password_confirm:
            raise forms.ValidationError("Les mots de passes ne correcpondent pas")
        return password

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password"])
        if commit:
            user.save()
        return user


class UserAdmin(BaseUserAdmin):
    form = UserModificationForm
    add_form = UserCreationForm

    list_display = ('username', 'first_name', 'last_name', 'email', 'perm_on_user', 'perm_on_news', 'is_admin',)
    list_filter = ('perm_on_user', 'perm_on_news', 'is_admin')
    fieldsets = (
        (None, {'fields': (
        'username', 'password', 'password_confirm', 'first_name', 'last_name', 'email', 'perm_on_user', 'perm_on_news',
        'is_admin',)}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'first_name', 'last_name', 'email', 'password', 'password_confirm', 'perm_on_user',
                       'perm_on_news', 'is_admin'),
        }),
    )
    search_fields = ('username',)
    ordering = ()
    filter_horizontal = ()


admin.site.register(UserProfile, UserAdmin)
admin.site.unregister(Group)

#model.py
class UserProfileManager(BaseUserManager):

    def create_user(self, password=None, **kwargs):
        user = self.model(**kwargs)
        user.set_password(password)
        user.save(using=self.db)
        return user

    def create_superuser(self, password=None, **kwargs):
        user = self.create_user(password=password)
        user.is_admin = True
        user.save(using=self.db)
        return user

class UserProfile(AbstractBaseUser):
    __MAX_LENGTH = 100
    username = models.CharField(max_length=__MAX_LENGTH, verbose_name="Nom d'utilisateur", unique=True)
    first_name = models.CharField(max_length=__MAX_LENGTH, verbose_name="Prénom", default="")
    last_name = models.CharField(max_length=__MAX_LENGTH, verbose_name="Nom", default="")
    email = models.EmailField(max_length=__MAX_LENGTH, verbose_name="Adresse e-mail", default="")
    perm_on_user = models.BooleanField(verbose_name="Gestion des utilisateurs", default=False)
    perm_on_news = models.BooleanField(verbose_name="Gestion de la newsletter", default=False)
    is_admin = models.BooleanField(verbose_name="Administrateur", default=False)

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['first_name', 'last_name', 'email', 'perm_on_user', 'perm_on_news', 'is_admin', ]

    object = UserProfileManager()

    class Meta:
        verbose_name = "Utilisateur"

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    @property
    def is_staff(self):
        return self.is_admin

#view.py
class CreateUserView(CreateView):
    model = UserProfile
    fields = ['first_name', 'last_name', 'email', 'perm_on_user', 'perm_on_news', 'is_admin', ]

` 编辑:

这里有更多信息 `

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/accounts/new/

Django Version: 2.2.5
Python Version: 3.7.4
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'accounts']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/usr/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/usr/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "/usr/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/lib/python3.7/site-packages/django/views/generic/base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)

File "/usr/lib/python3.7/site-packages/django/views/generic/base.py" in dispatch
  97.         return handler(request, *args, **kwargs)

File "/usr/lib/python3.7/site-packages/django/views/generic/edit.py" in get
  168.         return super().get(request, *args, **kwargs)

File "/usr/lib/python3.7/site-packages/django/views/generic/edit.py" in get
  133.         return self.render_to_response(self.get_context_data())

File "/usr/lib/python3.7/site-packages/django/views/generic/edit.py" in get_context_data
  66.             kwargs['form'] = self.get_form()

File "/usr/lib/python3.7/site-packages/django/views/generic/edit.py" in get_form
  32.             form_class = self.get_form_class()

File "/usr/lib/python3.7/site-packages/django/views/generic/edit.py" in get_form_class
  93.                 model = self.get_queryset().model

File "/usr/lib/python3.7/site-packages/django/views/generic/detail.py" in get_queryset
  73.                         'cls': self.__class__.__name__

Exception Type: ImproperlyConfigured at /accounts/new/
Exception Value: CreateView is missing a QuerySet. Define CreateView.model, CreateView.queryset, or override CreateView.get_queryset().

`

`     在/ accounts / new /

上配置不正确
CreateView is missing a QuerySet. Define CreateView.model, CreateView.queryset, or override CreateView.get_queryset().

Request Method:     GET
Request URL:    http://127.0.0.1:8000/accounts/new/
Django Version:     2.2.5
Exception Type:     ImproperlyConfigured
Exception Value:    

CreateView is missing a QuerySet. Define CreateView.model, CreateView.queryset, or override CreateView.get_queryset().

Exception Location:     /usr/lib/python3.7/site-packages/django/views/generic/detail.py in get_queryset, line 73
Python Executable:  /usr/bin/python3.7
Python Version:     3.7.4
Python Path:    

['/home/antoine/PycharmProjects/AsepWebApp',
 '/home/antoine/PycharmProjects/AsepWebApp',
 '/home/antoine/PyCharm/helpers/pycharm_display',
 '/usr/lib/python37.zip',
 '/usr/lib/python3.7',
 '/usr/lib/python3.7/lib-dynload',
 '/usr/lib/python3.7/site-packages',
 '/home/antoine/PyCharm/helpers/pycharm_matplotlib_backend']

Server time:    sam, 7 Sep 2019 16:59:20 +0000

`

编辑2:

在这里urls.py

`

#accounts/urls.py
urlpatterns = [
    path('new/', views.CreateView.as_view(), name="accounts/new/"),
]

#base urls.py file
urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('accounts.urls'))
]

`

2 个答案:

答案 0 :(得分:0)

您没有显示您的网址,但您似乎在这里使用了基本的CreateView而不是CreateUserView。

答案 1 :(得分:0)

您必须在CreateUserView中使用扩展的urls.py,而不是像这样导入的CreateView

urlpatterns = [
    path('new/', views.CreateUserView.as_view(), name="accounts/new/"),
]