2

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?

Danny
  • 470
  • 1
  • 4
  • 21

2 Answers2

3

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)

Lemayzeur
  • 8,297
  • 3
  • 23
  • 50
2

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.

Dap
  • 2,309
  • 5
  • 32
  • 44
  • Cool, I think this will put me on the right path. I'm just learning Django so this is all new to me. I updated with my model. Any syntax tips? – Danny May 08 '18 at 18:34
  • good luck. syntax fairly standard so far. and with your edit, author is an id and not a string. so use id when filtering, also you have to change the regex in your url function. have a look at this for integer regex in the url https://stackoverflow.com/questions/23420655/django-url-pattern-for-integer?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Dap May 08 '18 at 18:38