【问题标题】:can't use id and str:username together不能同时使用 id 和 str:username
【发布时间】:2021-07-19 07:03:42
【问题描述】:

我创建了一个博客,您可以在其中访问用户的个人资料并查看他们的帖子。您还可以单独查看每个帖子。

但是,我不能使用这样的 url 路径路径(' / /', post_view, name = 'tak')。这导致“tak”与参数“(44,)”的反向未找到错误。 这是我的代码 视图.py

def user_posts(request, username):
  posts = Post.objects.filter(author__username=username)
  return render(request, 'profile.html', {'posts':posts})

    
def post_view(request,post_id):
    post = Post.objects.get(id=post_id)
    context={'post':post}
    return render(request, 'post.html',context)

urls.py

path('<str:username>/', user_posts, name='profile'),
path('<str:username>/<post_id>/', post_view, name='tak'),

models.py

class Post(models.Model):
    text=models.CharField(max_length=25)
    pub_date=models.DateTimeField('date published',auto_now_add=True)
    author=models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
# Create your models here.
    def __str__(self):
        return self.text

profile.html

{% extends 'base.html' %}

{% block content %}

{% for post in posts %}
<ul><li>
{{post}}
<hr>
<p>
<a href="{% url 'tak' post.id %}">{{post}}</a></p>
</li>
</ul>
{% endfor %}

{% endblock content %}

【问题讨论】:

    标签: django


    【解决方案1】:

    路径tak 需要两个参数,而您只发送一个:在您的profile.html 中替换:

    <a href="{% url 'tak' post.id %}">{{post}}</a></p>
    

    与:

    <a href="{% url 'tak' request.user.id post.id %}">{{post}}</a></p>
    

    【讨论】:

      猜你喜欢
      • 2020-09-22
      • 2018-07-13
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-30
      • 2016-09-21
      • 1970-01-01
      相关资源
      最近更新 更多