0

I'm trying to save UserCreationForm of Django's built in auth application's form, using following in 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']

My unauthenticated decorator is:

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

And views function looks like:

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

Complete Traceback is:

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.

My model is:

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

My signals.py file:

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)

Please help me with this. Kindly note that it is saving the values to the SQL DB successfully but returning this error and not moving anywhere ahead user = form.save() line.

Any help is much appreciated. Thanks!

Jatin Singh Bhati
  • 133
  • 1
  • 3
  • 14

1 Answers1

2

It appears that there is no Group with name='customer'. You should use ensure that a group like that exists. One method would be to use the get_or_create method to get the object if it exists or create and get it:

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!')
Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33
  • Thanks for the help! Tried this but getting the same error. Shall I share some more details, let me know. – Jatin Singh Bhati Mar 05 '21 at 11:02
  • @JatinSinghBhati did you make the changes and restart your server? – Abdul Aziz Barkat Mar 05 '21 at 11:09
  • @JatinSinghBhati is the error the same? That would not be possible if you changed the signal as per my answer (if it is the correct signal). – Abdul Aziz Barkat Mar 05 '21 at 11:16
  • Just noticed that it still is about groups but slightly changed when observed traceback: Exception Type: TypeError at /accounts/register/ Exception Value: Field 'id' expected a number but got (, False). Can you help me to address this? – Jatin Singh Bhati Mar 05 '21 at 11:18
  • 1
    Did you write `group, created = Group.objects.get_or_create(name='customer')` or did you write `group = Group.objects.get_or_create(name='customer')`? notice the `created` It is there because `get_or_create` returns the object and whether it was created or not. – Abdul Aziz Barkat Mar 05 '21 at 11:20