DoesNotExist:保存 Django 的 UserCreationForm 时出现 "Group matching query does not exist." 错误

DoesNotExist: Getting "Group matching query does not exist." error while saving a UserCreationForm of Django

我正在尝试保存 UserCreationForm 的 Django 内置 auth 应用程序表单,使用 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 数据库,但返回此错误并且没有移动到 user = form.save() 行之前的任何地方。

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

似乎没有 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!')