Django SuperUser Not having the one to one relationship with profile form
I wanted to create a edit profile page and along with the usercreationform fields wanted to add extra fields like phone no and data and use a one to one relation with the model having extra infos
models.py
class Profile(models.Model):
user = models.OneToOneField(User,
on_delete=models.CASCADE,
related_name='profile')
bio = models.TextField(blank=True, max_length=500)
phone_no = models.TextField(blank=True, max_length=10)
forms.py
class EditUser(ModelForm):
class Meta:
model = User
fields = ["first_name", "last_name", "email"]
class EditUserProfile(ModelForm):
class Meta:
model = Profile
fields = ["phone_no", "bio"]
the profile model is working in a onetoone relation with users but not with supersuser it says profile model doesnt exist
views.py
class EditProfile(View):
def get(self, request, pk, *args, **kwargs):
user_form = EditUser(instance=request.user)
profile_form = EditUserProfile(instance=request.user.profile)
context = {'user_form': user_form, 'profile_form': profile_form}
return render(request, 'base/edit_profile.html', context)
def post(self, request, pk, *args, **kwargs):
user_form = EditUser(request.POST, instance=request.user)
profile_form = EditUserProfile(request.POST, instance=request.user.profile)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
context = {'user_form': user_form, 'profile_form': profile_form}
return render(request, 'base/edit_profile.html', context)
You are creating the relationship table but not relating a profile to an user per se. The best way would be to send a post_save signal to create a Profile everytime an User is created.
class Profile(models.Model):
...
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)