I have created a random blog post link on my site and the code it uses works. When I was creating it there was a problem making it work correctly since it kept saying ‘QuerySet’ object has no attribute ‘slug’, so I came up with a work around. The work around makes more requests to the db than necessary (i think):
from django.http import HttpResponseRedirect
def randompost(request):
blog_posts = BlogPost.objects.filter(post_status = 'published').order_by('?')[:1]
blog_title = blog_posts[0]
blog_post = get_object_or_404(BlogPost, title=blog_title)
path = '/theblog/post/' + blog_post.slug + '/'
return HttpResponseRedirect(path)
Ideally I would like a solution like Django redirect URL to latest created blog post
Will it also need the correct http code since it’s a redirect?
The old code with the Queryset error:
blog_post = BlogPost.objects.filter(post_status = 'published').order_by('?')[:1]
path = '/theblog/post/' + blog_post.slug + '/'
return HttpResponseRedirect(path)
redirectand reverse URLs;[]syntax to get first object of QuerySet.Updated code:
Updated:
URL sample, reverse is done by url name
blog_post: