RelatedObjectDoesNotExist at /register/ User has no schoolprofile

Viewed 73

hello am trying to create a school profile when a user( schooluser) registers,the profile is created but giving the error RelatedObjectDoesNotExist at /register/User has no schoolprofile.and the strange thing is that in the admin the model fields when you try to edit any field of the created school profile they are empty. help.

models.py

class SchoolProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='schoolprofile')
    schoolname = models.CharField(max_length=200)
    region = models.CharField(max_length=200)
    district = models.CharField(max_length=200)
    code = models.CharField(max_length=20)
    logo = models.ImageField(default='default.jpg', upload_to='logos')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import SchoolProfile



class SchoolRegisterForm(UserCreationForm):
    email = forms.EmailField()
   

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

  
class SchoolProfileForm(forms.ModelForm):
    class Meta:
        model = SchoolProfile
        fields = ['schoolname', 'code', 'region']

views.py

from .forms import SchoolRegisterForm,SchoolProfileForm



def register(request):
    if request.method == 'POST':
        form = SchoolRegisterForm(request.POST)
        s_profile_form = SchoolProfileForm(request.POST)
        if form.is_valid() and s_profile_form.is_valid():
            form.save()
            request.user.refresh_from_db()  
            s_profile_form = SchoolProfileForm(request.POST, instance=request.user.schoolprofile)
            s_profile_form.full_clean()
            s_profile_form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Your account has been created! You are now able to log in!')
            return redirect('dashboard')
    else:
        form = SchoolRegisterForm()
        s_profile_form = SchoolProfileForm()
    return render(request, 'accounts/register.html', {'form': form,'s_profile_form':s_profile_form})
1 Answers

You use request.user.schoolprofile, but your user (right now) has not per se a related SchoolProfile object, hence the error. Furthermore creating a user will not (automatically) log in that user. You can alter the .user field in the instance wrapped in the s_profile_form:

def register(request):
    if request.method == 'POST':
        form = SchoolRegisterForm(request.POST)
        s_profile_form = SchoolProfileForm(request.POST)
        if form.is_valid() and s_profile_form.is_valid():
            user = form.save()
            s_profile_form.instance.user = user
            s_profile_form.save()
            messages.success(request, f'Your account has been created! You are now able to log in!')
            return redirect('dashboard')
    else:
        form = SchoolRegisterForm()
        s_profile_form = SchoolProfileForm()
    return render(request, 'accounts/register.html', {'form': form,'s_profile_form':s_profile_form})

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Related