我如何通过它的标题来查看单篇文章,如下所示: news/article_name ?
我设法使用数字( <int:pk>在urls中,然后使用{% url 'article' article.id %}在模板中访问它),所以news/1实际上起作用。 而不是使用数字,我想使用标题,并不知道如何。
models.py
class Article(models.Model): headline = models.CharField(max_length=200) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() def __str__(self): return self.headlineurls.py
path('<slug:headline>/', views.DetailView.as_view(), name='article'),views.py
class ArticleView(generic.DetailView): model = Article template_name = 'news/index.html' context_object_name = 'article' local_context = {**context, **{'show_comments':False}}在文章模板中的某处
<p><a href="{% url 'article' %}">Read more</a></p>How can I view a single article by it's headline like so: news/article_name?
I managed to make it work with numbers (<int:pk> in urls then access it in template using {% url 'article' article.id %}) so news/1 actually worked. Instead of using numbers I want to use headlines and can't figure out how.
models.py
class Article(models.Model): headline = models.CharField(max_length=200) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() def __str__(self): return self.headlineurls.py
path('<slug:headline>/', views.DetailView.as_view(), name='article'),views.py
class ArticleView(generic.DetailView): model = Article template_name = 'news/index.html' context_object_name = 'article' local_context = {**context, **{'show_comments':False}}somewhere in article template
<p><a href="{% url 'article' %}">Read more</a></p>最满意答案
当您使用主键时,必须将其包含在URL标记中。
{% url 'article' article.id %}同样,你必须在URL标签中加入标题。
{% url 'article' article.headline %}请注意,包含单独的slug字段而不是使用headline可能会更好,因此您可以使用/news/man-bites-dog而不是/news/Man%20Bites%20Dog
class Article(models.Model): headline = models.CharField(max_length=200) slug = models.SlugField()然后你会将url标签更改为:
{% url 'article' article.slug %}When you used the primary key you had to include that in the URL tag.
{% url 'article' article.id %}In the same way, you have to include the headline in the URL tag.
{% url 'article' article.headline %}Note that it might be better to include a separate slug field instead of using headline, so that you get URLs like /news/man-bites-dog instead of /news/Man%20Bites%20Dog
class Article(models.Model): headline = models.CharField(max_length=200) slug = models.SlugField()Then you would change the url tag to:
{% url 'article' article.slug %}更多推荐
发布评论