Object does not exist error: User has no profile

I am trying to create two forms to update the user profile, but I keep getting the error:

    django.contrib.auth.models.User.profile.RelatedObjectDoesNotExist: 
    User has no profile.

I do not know where I am going wrong! My code is as follows:

My profile.html

    {% extends "apotofgold/base.html" %}
    {% load crispy_forms_tags %}
    {% load avatar_tags %}
    {% block content %}
        <div class="content-section">
          <div class="media">
            <img class="rounded-circle account-img" src="{% avatar user         %}">
            <div class="media-body">
              <h2 class="account-heading">{{ user.username }}</h2>
              <p class="text-secondary">{{ user.email }}</p>
            </div>
          </div>
          <form method="POST" enctype="multipart/form-data">
            {% csrf_token %}
            <fieldset  class="form-group">
                <legend class="border-bottom mb-4">Profile                 Info</legend>
                {{ u_form|crispy }}
                {{ p_form|crispy }}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info"         type="submit">Update</button>
        </form>
        </div>
    {% endblock content %}

My forms.py

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

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

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

    class UserUpdateForm(forms.ModelForm):
        class Meta:
            model = User
            fields = ['username','email']

    class ProfileUpdateForm(forms.ModelForm):
        class Meta:
            model = Profile
            fields = ['image']

My models.py

    from django.db import models
    from django.contrib.auth.models import User

    class Profile(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        image = models.ImageField(default='default.jpg',         upload_to='profile_pics')

        def __sr__ (self):
                    return f'{self.user.uMy mpodsername} Profile'

My signals.py

    from djamgo.db.models.signals import post_save
    from django.contrib.auth.models import User
    from django.dispatch import receiver
    from .models import Profile

    @receiver(post_save, sender=User)
    def create_profile(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)


    @receiver(post_save, sender=User)
    def save_profile(sender, instance, **kwargs):
            instance.profile.save()

My views.py

    from django.shortcuts import render, redirect
    from django.contrib.auth.forms import UserCreationForm
    from django.contrib import messages
    from .forms import UserRegistrationForm, UserUpdateForm,         ProfileUpdateForm
    from django.contrib.auth.decorators import login_required

    def register(request):
        #form = UserCreationForm(request.POST)
        if request.method == 'POST':
            form = UserRegistrationForm(request.POST)
            if form.is_valid():
                form.save()
                username = form.cleaned_data.get('username')
                messages.success(request, f'Account created         for {username}!')
                return redirect('message-home')
        else:
            form = UserRegistrationForm()
        return render(request, 'users/register.html',{'form':form})

    @login_required
    def profile(request):
        if request.method == 'POST':
            if request.user.userprofile is None:
                user_profile = UserProfile(user=request.user)
                user_profile.save
        return render(request, 'users/profile.html')

    @login_required
    def profile(request):
        if request.method == 'POST':
            u_form =         UserUpdateForm(data=request.POST,instance=request.user)
            p_form =         ProfileUpdateForm(data=request.POST,files=request.FILES,instance=request.user.        profile)
            if u_form.is_valid() and p_form.is_valid():
                u_form.save()
                p_form.save()
                messages.success(request, f'Your Account has         been Updated!')
                return redirect('profile')
        else:
            u_form = UserUpdateForm(instance=request.user)
            p_form =         ProfileUpdateForm(instance=request.user.profile)

        context = {
            'u_form':u_form,
            'p_form':p_form
        }
        return render(request, 'users/profile.html', context)

The error message I get is as follows:

    System check identified 2 issues (0 silenced).
    July 21, 2019 - 16:41:07
    Django version 2.2.3, using settings 'apotofgold.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CTRL-BREAK.
    Internal Server Error: /profile/
    Traceback (most recent call last):
      File "C:\Projects\new\apotofgold\ENV\lib\site-                packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Projects\new\apotofgold\ENV\lib\site-        packages\django\core\handlers\base.py", line 115, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Projects\new\apotofgold\ENV\lib\site-        packages\django\core\handlers\base.py", line 113, in _get_response
        response = wrapped_callback(request, *callback_args,         **callback_kwargs)
      File "C:\Projects\new\apotofgold\ENV\lib\site-        packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
        return view_func(request, *args, **kwargs)
      File "C:\Projects\new\apotofgold\users\views.py", line 40, in         profile
        p_form = ProfileUpdateForm(instance=request.user.profile)
      File "C:\Projects\new\apotofgold\ENV\lib\site-        packages\django\utils\functional.py", line 257, in inner
        return func(self._wrapped, *args)
      File "C:\Projects\new\apotofgold\ENV\lib\site-        packages\django\db\models\fields\related_descriptors.py", line 415, in __get__
        self.related.get_accessor_name()
    django.contrib.auth.models.User.profile.RelatedObjectDoesNotExist:         User has no profile.
    [21/Jul/2019 16:41:17] "GET /profile/ HTTP/1.1" 500 83657
    [21/Jul/2019 16:41:21] "GET /message HTTP/1.1" 200 4236
    Internal Server Error: /profile/
    Traceback (most recent call last):
      File "C:\Projects\new\apotofgold\ENV\lib\site-                packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Projects\new\apotofgold\ENV\lib\site-        packages\django\core\handlers\base.py", line 115, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Projects\new\apotofgold\ENV\lib\site-        packages\django\core\handlers\base.py", line 113, in _get_response
        response = wrapped_callback(request, *callback_args,         **callback_kwargs)
      File "C:\Projects\new\apotofgold\ENV\lib\site-        packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
        return view_func(request, *args, **kwargs)
      File "C:\Projects\new\apotofgold\users\views.py", line 40, in         profile
        p_form = ProfileUpdateForm(instance=request.user.profile)
      File "C:\Projects\new\apotofgold\ENV\lib\site-        packages\django\utils\functional.py", line 257, in inner
        return func(self._wrapped, *args)
      File "C:\Projects\new\apotofgold\ENV\lib\site-        packages\django\db\models\fields\related_descriptors.py", line 415, in __get__
        self.related.get_accessor_name()
    django.contrib.auth.models.User.profile.RelatedObjectDoesNotExist:         User has no profile.
    [21/Jul/2019 16:41:27] "GET /profile/ HTTP/1.1" 500 83657

Any help is much appreciated and I hope we can solve this problem together.

1 answer

  • answered 2019-07-21 20:08 Farhani Walid

    Did you declared the signal in your apps.py file like that ?

    from django.apps import AppConfig
    
    
    class UsersConfig(AppConfig):
        name = 'users'
    
        def ready(self):
            import users.signals
    
    

    In yout views.py youn have 2 functions with the name profile :

        @login_required
        def profile(request):
            if request.method == 'POST':
                if request.user.userprofile is None:
                    user_profile = UserProfile(user=request.user)
                    user_profile.save
            return render(request, 'users/profile.html')
    
        @login_required
        def profile(request):
            if request.method == 'POST':
                u_form =         UserUpdateForm(data=request.POST,instance=request.user)
                p_form =         ProfileUpdateForm(data=request.POST,files=request.FILES,instance=request.user)
                if u_form.is_valid() and p_form.is_valid():
                    u_form.save()
                    p_form.save()
                    messages.success(request, f'Your Account has         been Updated!')
                    return redirect('profile')
            else:
                u_form = UserUpdateForm(instance=request.user)
                p_form =         ProfileUpdateForm(instance=request.user.profile)
    
            context = {
                'u_form':u_form,
                'p_form':p_form
            }
            return render(request, 'users/profile.html', context)