2
votes

I have an account app in which I have created a Profile model by extending the custom user model. I have created a view which allows the user to edit his profile info and also I have corresponding UserEditForm and ProfileEditForm. As of now, no user has a profile so when I open the edit form I get an error: "RelatedObjectDoesNotExist at /account/edit/". " User has no profile " I tried to create the profile using admin , then the error goes away. How can I correct this in my views.py file.

views.py

@login_required
def edit(request):
    if request.method =='POST':
        user_form = UserEditForm(instance=request.user,data=request.POST)

        profile_form =     ProfileEditForm(instance=request.user.profile,data=request.POST,files=request.FILES)

        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request,'Profile updated successfully')

        else:
            messages.error(request,'Error updating your profile')

    else:
        user_form = UserEditForm(instance=request.user)

        profile_form = ProfileEditForm(instance=request.user.profile)


    context = {
        'user_form':user_form,
        'profile_form': profile_form
    }
    return render(request,'account/edit.html',context)

models.py

CATEGORY_CHOICES = (
    ('SA','School Admin'),
    ('T','Teacher'),
    ('S','Student'),
    ('P','Parent'),
)


class Profile(models.Model):
    eduser = models.OneToOneField(settings.AUTH_USER_MODEL)
    photo = models.ImageField(upload_to='users/%Y/%m/%d',blank=True)
    about_me = models.TextField(max_length=200,blank=True)
    category = models.CharField(max_length=1,choices=CATEGORY_CHOICES,blank=True)
    date_of_birth = models.DateField(blank=True,null=True)

    def __str__(self):
        return 'Profile for user {}'.format(self.eduser.username)

forms.py

class UserEditForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('first_name','last_name','email')

class ProfileEditForm(forms.ModelForm):

    class Meta:
        model = Profile
        fields = ('category','date_of_birth','about_me','photo')
1

1 Answers

3
votes

You need to catch the error. You can do it at the top of the function:

try:
    profile = request.user.profile
except ObjectDoesNotExist:
    profile = Profile(user=request.user)

and pass that profile into the ProfileEditForm in both if branches.