Django Querying: How do i query an account page through a blog post that the account owner has created? aka link from one to another. So I have an account model and a blog post model, with the author as the foreign key. I am unsure of how i can do the querying of the account. Can anyone advise how this is normally done? Because I tried to do user_id=request.user.id
but this would take me to my own account view. Thanks!
html
<a class="dropdown-item" href="{% url 'account:view' %}">{{blog_post.author}}</a>
views.py
def detail_blog_view(request, slug):
context = {}
blog_post = get_object_or_404(BlogPost, slug=slug)
context['blog_post'] = blog_post
return render(request, 'HomeFeed/detail_blog.html', context)
urls.py for Blogs
path('<slug>/detail/', detail_blog_view, name= "detail"),
urls.py for accounts:
path('<user_id>/', account_view, name="view"),
models.py
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
class BlogPost(models.Model):
title = models.CharField(max_length=50, null=False, blank=False)
body = models.TextField(max_length=5000, null=False, blank=False)
slug = models.SlugField(blank=True, unique=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
You don't really need to query the author
, what you do is just get the foreign key
value from the BlogPost
object like this:
views.py
def post(request, pk):
post = BlogPost.objects.get(pk=pk)
author = post.author
return render(request, 'post.html', {'post': post,
'author': author})
Then display it in a template:
post.html
<a href="{% url 'view' author.pk %}">{{ author }}</a>
(or you can use {{ post.author }} here aswell) says:
{{ post.title }} | {{ post.body }}
EDIT
in your urls where you have a path to your user profile you actually need to specify the argument type like:
path('<int:user_id>/', account_view, name="view"), # btw dont call your views 'view', name should describe what the view actually does or shows