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