Danny
Danny

Reputation: 510

View articles by author in Django blog

I'm trying to create a view that allows one to see all blog posts written by a particular author. Here's the URL pattern I'm using:

url(r'^user/(?P<username>[\w-]+)/$', views.user_articles, name="user_articles"),

And here's my view:

def user_articles(request, username):
    articles = Article.objects.filter(author=username).order_by('-date')
    return render(request, "articles/article_list.html", {'articles': articles})

This is returning the error:

ValueError at /articles/user/danny/
invalid literal for int() with base 10: 'danny'

Editing to add model as well:

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True)
    body = HTMLField('Body')
    date = models.DateTimeField(auto_now_add=True)
    thumb = models.ImageField(default="keys.jpg", blank=True)
    author = models.ForeignKey(User, default=None)

danny is a valid username, and it should be a string, not an integer, so I'm not sure what's going wrong here. Any ideas?

Upvotes: 2

Views: 1299

Answers (2)

Lemayzeur
Lemayzeur

Reputation: 8525

Considering author, which is a ForeignKey to auth.User .

Your query should be

Article.objects.filter(author__username=username)

instead of ...Article.objects.filter(author=username)

Upvotes: 3

Dap
Dap

Reputation: 2359

Post your model but I assume the association between models, is a Foreign Key. So 'author' on your model Article is likely an ID and not a string. So instead of the username 'danny' try retrieving 'danny's ID.

Upvotes: 2

Related Questions