Sonali Gupta
Sonali Gupta

Reputation: 514

RelatedObjectDoesNotExist User and no profile

I am extending User model of Django by following model

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    favorites = models.ManyToManyField(Post, related_name='favorited_by')

When I click on a button that calls the following view,

def add_fav(request,pk):
    post = get_object_or_404(Post, pk=pk)
    form = PostForm(instance=post)
    post = form.save(commit=False)
    userprofile=request.user.profile
    with userprofile.favorites.all as favorite_posts:
        for post in post_list:
            if post not in favorite_posts:
                userprofile.favorites.add(post)
    userprofile.save() 
    return redirect('post_list')

I get the error RelatedObjectDoesNotExist User has no profile

I applied migrations and everything.

Upvotes: 0

Views: 1262

Answers (2)

Moaaz
Moaaz

Reputation: 790

That happened to me once and I lost a day debugging. In my case, the app was called "users". Long story short, in my settings.py and under INSTALLED_APPS, I had:

MY_APPS = [
    .....
    'blog',
    'users',
    .....
]
INSTALLED_APPS.extend(MY_APPS)

Changing it to:

MY_APPS = [
    .....
    'blog',
    'users.apps.UsersConfig',
    .....
]
INSTALLED_APPS.extend(MY_APPS)

did the trick.

I am still not sure why but it was working just fine (with 'users' in INSTALLED_APPS). Users were created, Profile for Users was created. Signals were firing. Out of a sudden, it just stopped working. Glad I fixed it. It drove me crazy!

Upvotes: 0

Mr. Nun.
Mr. Nun.

Reputation: 850

You probably don't have a Profile object. you need to create a profile for the already existing users (the right way to do it would be in the migration) and also create a user profile whenever a new user is created.

another easier approach would be to check if a profile exists and if not - create it. (in this case, you'll have to make this field not mandatory. you could make it like this:

def add_fav(request,pk):
    post = get_object_or_404(Post, pk=pk)
    form = PostForm(instance=post)
    post = form.save(commit=False)
    if not request.user.profile:
        request.user.profile = Profile.objects.create()
    userprofile=request.user.profile
    with userprofile.favorites.all as favorite_posts:
        for post in post_list:
            if post not in favorite_posts:
                userprofile.favorites.add(post)
    userprofile.save() 
    return redirect('post_list')

Upvotes: 2

Related Questions