Home > Blockchain >  FieldError at /favourites/ Cannot resolve keyword 'favpost' into field. Choices are: autho
FieldError at /favourites/ Cannot resolve keyword 'favpost' into field. Choices are: autho

Time:10-10

I have error FieldError at /en/account/profile/favourites/ Cannot resolve keyword 'favpost' into field. Choices are: author, author_id

This spanning can be as deep as you’d like.

It works backwards, too. While it can be customized, by default you refer to a “reverse” relationship in a lookup using the lowercase name of the model.

This example retrieves all Post objects which have at least one favPost whose user=request.user

class Post(models.Model):
    title = models.CharField(max_length=250)
    excerpt = models.TextField()

class favPost(models.Model):        post = models.ForeignKey(Post, related_name='postfv', on_delete=models.CASCADE, default=None, blank=True)
    user = models.ForeignKey(User, related_name='userfv', on_delete=models.CASCADE, default=None, blank=True)
    vote = models.BooleanField(default=True)
    publish = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.post


def favourite_list(request):
    new2 = Post.objects.filter( favpost__user=request.user )        
    return render(request, 'accounts/favourites.html', {'new':  new2  } )

CodePudding user response:

Since the related_name=… parameter [Django-doc] for the ForeignKey to post is related_name='postfv', you thus query with:

from django.contrib.auth.decorators import login_required

@login_required
def favourite_list(request):
    new2 = Post.objects.filter(postfv__user=request.user)
    return render(request, 'accounts/favourites.html', {'new': new2})

You should furthermore put the post ForeignKey as field under the favPost, so:

class FavPost(models.Model):
    post = models.ForeignKey(Post, related_name='postfv', on_delete=models.CASCADE, default=None, blank=True)
    user = models.ForeignKey(User, related_name='userfv', on_delete=models.CASCADE, default=None, blank=True)
    vote = models.BooleanField(default=True)
    publish = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return str(self.post)

Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].

  • Related