【问题标题】:DoesNotExist: Getting "Group matching query does not exist." error while saving a UserCreationForm of DjangoDoesNotExist:获取“组匹配查询不存在”。保存 Django 的 UserCreationForm 时出错
【发布时间】:2021-06-04 01:03:35
【问题描述】:

我正在尝试保存 Django 内置的 auth 应用程序表单的 UserCreationForm,使用 forms.py 中的以下内容

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
from .models import *
class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

我未经身份验证的装饰器是:

def unauthenticated_user(view_func):
    def wrapper_func(request, *args, **kwargs):
        if request.user.is_authenticated:
            return redirect('home')
        else:
            return view_func(request, *args, **kwargs)
    return wrapper_func

视图功能如下:

@unauthenticated_user
def registerPage(request):
    form = CreateUserForm() 
    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            user = form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, 'Account was created for ' + username)
            return redirect('login')
    context = {'form':form}
    return render(request, 'accounts/register.html', context)

完整的追溯是:

Traceback (most recent call last):
  File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/jatinsinghbhati/Documents/workspaces/pollsite/accounts/decorators.py", line 9, in wrapper_func
    return view_func(request, *args, **kwargs)
  File "/Users/jatinsinghbhati/Documents/workspaces/pollsite/accounts/views.py", line 26, in registerPage
    user = form.save()
  File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/contrib/auth/forms.py", line 138, in save
    user.save()
  File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line 67, in save
    super().save(*args, **kwargs)
  File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/db/models/base.py", line 753, in save
    self.save_base(using=using, force_insert=force_insert,
  File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/db/models/base.py", line 801, in save_base
    post_save.send(
  File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 177, in send
    return [
  File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 178, in <listcomp>
    (receiver, receiver(signal=self, sender=sender, **named))
  File "/Users/jatinsinghbhati/Documents/workspaces/pollsite/accounts/signals.py", line 10, in customer_profile
    group = Group.objects.get(name='customer')
  File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/db/models/query.py", line 429, in get
    raise self.model.DoesNotExist(

Exception Type: DoesNotExist at /accounts/register/
Exception Value: Group matching query does not exist.

我的模型是:

class Customer(models.Model):
    user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200, null=True)
    profile_pic = models.ImageField(default="profile1.png", null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)

    def __str__(self):
        return self.name

我的signals.py 文件:

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.contrib.auth.models import Group
from .models import Customer
def customer_profile(sender, instance, created, **kwargs):
    if created:
        group = Group.objects.get(name='customer')
        instance.groups.add(group)
        Customer.objects.create(
            user=instance,
            name=instance.username,
            )
        print('Profile created!')
post_save.connect(customer_profile, sender=User)

请帮我解决这个问题。请注意,它正在成功地将值保存到 SQL DB,但返回此错误,并且没有向前移动任何位置 user = form.save() 行。

非常感谢任何帮助。谢谢!

【问题讨论】:

  • 你有一些关于用户创作的信号。请将它们添加到问题中。根据错误group = Group.objects.get(name='customer'),此查询失败,因为没有这样的组。
  • @AbdulAzizBarkat 添加了我的信号文件

标签: django django-views django-forms django-authentication django-auth-models


【解决方案1】:

似乎没有Groupname='customer'。您应该使用确保存在这样的组。一种方法是使用get_or_create 方法获取对象(如果存在)或创建并获取它:

def customer_profile(sender, instance, created, **kwargs):
    if created:
        group, created = Group.objects.get_or_create(name='customer')
        instance.groups.add(group)
        Customer.objects.create(
            user=instance,
            name=instance.username,
            )
        print('Profile created!')

【讨论】:

  • 感谢您的帮助!试过这个但得到同样的错误。我可以分享更多细节吗,让我知道。
  • @JatinSinghBhati 您是否进行了更改并重新启动了服务器?
  • @JatinSinghBhati 错误是否相同?如果您按照我的回答更改信号(如果它是正确的信号),那将是不可能的。
  • 刚刚注意到它仍然是关于组的,但在观察回溯时略有变化:异常类型:/accounts/register/ 处的 TypeError 异常值:字段 'id' 需要一个数字,但得到了(,错误)。你能帮我解决这个问题吗?
  • 你写的是group, created = Group.objects.get_or_create(name='customer')还是group = Group.objects.get_or_create(name='customer')?注意 created 它存在是因为 get_or_create 返回对象以及它是否已创建。
猜你喜欢
  • 2014-09-22
  • 2022-01-10
  • 1970-01-01
  • 2013-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-03
  • 2018-02-23
相关资源
最近更新 更多