RelatedObjectDoesNotExist at /users/edit/ User has no profile

I ran into a situation where I had developed a method called edit and passed both the profile and user forms into it when I wanted to modify a profile.

@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()
      else:
            user_form = UserEditForm(instance=request.user)
            profile_form = ProfileEditForm(instance=request.user.profile)          
      return render(request,'users/edit.html',{'user_form':user_form,'profile_form':profile_form})

this is my views.py where i have written the logic

and coming to urls.py

path('edit/',views.edit,name='edit'),

and the edit.html code follows like this

{% extends 'users/base.html' %}
{% block body %}
<h2>Edit profile form</h2>
      <form method="post" enctype="multipart/form-data">
            {% csrf_token %}
            {{ user_form.as_p }} 
            {{ profile_form.as_p }}
            <input type="submit"/>
      </form>
{% endblock %}

the output shows me like this

The result output

I am expecting a better solution to resolve this issue

Show us your models, most likely, in your Profile model, add a "related_name=profile" argument to your user field.

Back to Top