在Django中创建单个帖子和URL的详细信息视图可以通过以下步骤实现:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
from django.urls import path
from . import views
urlpatterns = [
path('post/<int:pk>/', views.post_detail, name='post_detail'),
]
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'post_detail.html', {'post': post})
post_detail.html
的模板文件:<h1>{{ post.title }}</h1>
<p>{{ post.content }}</p>
<p>Author: {{ post.author }}</p>
<p>Created at: {{ post.created_at }}</p>
以上步骤完成后,当访问类似/post/1/
的URL时,Django将会调用post_detail
视图函数,并将对应帖子的详细信息传递给模板进行渲染。
领取专属 10元无门槛券
手把手带您无忧上云