gpt4 book ai didi

python - 如何在 django 中创建唯一的 URL?

转载 作者:行者123 更新时间:2023-12-01 01:27:51 25 4
gpt4 key购买 nike

我的项目是博客类型。在这个博客中我需要发布新闻。我可以使用 Django 管理页面添加新闻并在一个 url 中显示所有新闻。现在我希望每个新闻都有一个唯一的 URL。

我的models.py :

from django.db import models

class Newsform(models.Model):
headline = models.CharField(max_length=50)
description = models.CharField(max_length=100, default='')
content = models.CharField(max_length=100, default='')
image = models.ImageField(upload_to='news_image', blank=True)

views.py :

from django.shortcuts import render
from blog.models import Newsform

def show_content_from_database(request):
headline_news=Newsform.objects.all()
context = {
'headline_news': headline_news
}
return render(request, 'blog/index.html', context)

这里是urls.py :

from django.urls import path
from . import views

urlpatterns = [
path('', views.show_content_from_database,
name='show_content_from_database'),
]

最后,index.html 的部分,我在其中显示每条新闻的标题:

{% for headline in headline_news %}
<h1>{{ headline.headline }}</h1>
{% endfor %}

最多,我想在此处发布新闻的唯一链接:<h1>{{ headline.headline }}</h1> ,并且该独特的页面必须扩展一些 base.html .

我在网上搜索了我的问题的解决方案,但没有找到。这个任务可能足够大,所以我想查看互联网上一些示例的链接(youtube、stackoverflow 或 github 等)。

最佳答案

在您的 views.py 中定义一个函数,该函数将从它收到的主键中获取一个对象。

def show_one_item(request, pk):
headline_news = Newsform.objects.get(pk=pk) # returns only one object
context = {
'headline_news': headline_news
}
return render(request, 'blog/new_template.html', context) # Write a new template to view your news.

将其添加到您的urls.py

urlpatterns = [
path('', views.show_content_from_database, name='show_content_from_database'),
path('news/<pk:pk>', show_one_item, name="show_one_item")
]

一旦您编写了 new_template 来适应该函数。您的每个新闻项目都有唯一的网址。

您的 new_template.html 的示例可能如下所示。

{% extends 'base.html' %}
<div class="container">

<p>{{ headline_news.headline }}</p>
<p>{{ headline_news.description }}</p>
<p>{{ headline_news.content }}</p>

</div>

现在,您可以转到 ../news/1(假设您没有搞乱 django 的默认行为)来查看您的第一个新闻项。 ../news/2 第二个,依此类推...稍后学习如何使用 slugs 来使您的网址看起来更真实。

关于python - 如何在 django 中创建唯一的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53194989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com