【问题标题】:Featured post is not adding精选帖子未添加
【发布时间】:2021-02-24 10:06:32
【问题描述】:

我正在构建一个 BlogApp,但遇到了一个问题。

我要做什么

我正在尝试像Featuring Post system 一样构建。如果用户单击此帖子的功能,则应将帖子添加到特色帖子中。

问题

当我点击精选此帖子时,它不会在精选帖子页面中添加帖子。

我尝试了什么

我还为特色帖子制作了另一个模型,但它不起作用,所以我再次在 Post Model 中实施

views.py

def featured(request,user_id):
    post = get_object_or_404(Post,post_owner=user_id)

    if request.user.is_authenticated:
        if request.method == 'POST':
            post.featured.add(post)

    context = {'post':post}
    return render(request, 'featured_posts.html', context)

models.py

class Post(models.Model):
    post_owner = models.ForeignKey(User,default='',null=True,on_delete=models.CASCADE)
    post_title = models.CharField(max_length=500,default='')
    featured = models.ManyToManyField(User,related_name='featured',blank=True,default='')

urls.py

path('featured/<int:user_id>/',views.featured,name='featured'),

detail_view.html

{{ data.post_title }}


<a href="{% url 'mains:featured' data.id %}">Feature this Post</a>

featured_posts.html

{% for s in post.featured %}

{{ s.post_title }}

{% endfor %}

我不知道我做错了什么。

任何帮助将不胜感激。

提前致谢。

【问题讨论】:

  • 请分享 404 的完整堆栈跟踪。
  • 没有显示404 now

标签: python html django django-models django-views


【解决方案1】:

您写的post.featured.add(post) 是不正确的,因为featured 是用户和帖子之间的多对多关系。你可能想写:

post.featured.add(request.user)

request.user.featured.add(post)

您还写了if request.method == 'POST':,但视图是通过正常的获取请求(您使用锚标记)到达的。删除该条件,它将起作用。 (最好将锚点更改为带有提交按钮的表单)

还可以显示用户的精选帖子:

{% for s in request.user.featured.all %}
    {{ s.post_title }}
{% endfor %}

【讨论】:

  • 感谢您的回答。但它仍然没有在精选页面中显示帖子。
  • 我认为,问题出在模型中,因为我添加了 ManyToManyFieldUser 并且当我在管理员中检查它时,它显示 Feature PostUSERS NAMES 但它应该是帖子名称。而且我认为我应该ManyToManyFieldPost
猜你喜欢
  • 1970-01-01
  • 2015-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多