-1

as the title reads I'm NOT getting the RelatedObjectDoesNotExist error in Django 3.1(Latest Release) I'm not using signals. I create a superuser using the (python manage.py createsuperuser) command, which, as expected, does not create a profile.

models.py '''

class User(AbstractUser):
    pass


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    birth_date = models.DateField(null=True, blank=True)

'''

views.py

'''

class RegisterView(View):

    def get(self, request):
        form = UserSignUpForm()
        # print(form)
        return render(request, 'users/register.html', {'form': form})

    def post(self, request):
        form = UserSignUpForm(request.POST)

        if form.is_valid():
            form.save()

            username = request.POST.get('username')
            Profile.objects.create(user=User.objects.get(username=username))

            return redirect('users:login-page')
        return render(request, 'users/register.html', {'form': form})

'''

when I use the createsuperuser command no profile is created, so I expect to get RelatedObjectDoesNotExist if I try to sign in. But I do NOT! why is that? also if I edit the database manually and remove a profile and keep the user, the user still works with no RelatedObjectDoesNotExist error! is this something that has changed with Django 3.1 !

thank you

Jamal
  • 11
  • 1
  • 2

2 Answers2

0

I actually found the issue. in the absence of signals connecting User and Profile models, Django couldn't tell a profile was missing for the signed-in user and no error was raised.

Jamal
  • 11
  • 1
  • 2
0

Try to create a new signals.py in the same folder and make the create_profile and save_profile functions in the below, that should work.

from django.db.models.signals import post_save  
from django.contrib.auth.models import User  
from django.dispatch import receiver  
from .models import Profile  

@receiver(post_save, sender=User)  
def create_profile(sender, instance, created, **kwargs):  
    if created:  
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    instance.profile.save()