Django开发:如何根据主键在独立HTML页面展示通知详情?
Got it, let's walk through this step by step to get your notice detail page working perfectly. You've already got a start with your Notice model, so we'll fill in the missing pieces to make the detail view functional.
1. First, Update Your Notice Model (Add Missing Date Fields)
You mentioned you want to display publish and expiry dates, but those aren't in your current model. Let's add them first:
# models.py from django.db import models from django.utils import timezone class Notice(models.Model): Notice_No = models.AutoField(primary_key=True) Content = models.TextField(max_length=5000, help_text="Enter notice content") # Add publish and expiry date fields publish_date = models.DateTimeField(default=timezone.now) expiry_date = models.DateTimeField() def __str__(self): # Optional: Makes admin display more readable return f"Notice {self.Notice_No}"
Don't forget to run migrations after updating the model:
python manage.py makemigrations python manage.py migrate
2. Create a Detail View Function
Next, we need a view that fetches a single notice using its primary key (Notice_No) and passes it to the detail template. Add this to your views.py:
# views.py from django.shortcuts import get_object_or_404, render from .models import Notice def notice_detail(request, notice_id): # Fetch the notice by primary key; return 404 if it doesn't exist notice = get_object_or_404(Notice, pk=notice_id) # Pass the notice object to the detail template return render(request, 'notice_detail.html', {'notice': notice})
The get_object_or_404 helper is great here—it handles the case where a user tries to access a notice that doesn't exist, so you don't have to write extra error-handling code.
3. Configure URL Routing
Map the detail page URL to your new view. Update your app's urls.py:
# urls.py (inside your Django app) from django.urls import path from . import views urlpatterns = [ # Your existing notice list view (adjust the path/name if needed) path('notices/', views.notice_list, name='notice_list'), # Detail route: <int:notice_id> captures the primary key as an integer path('notices/<int:notice_id>/', views.notice_detail, name='notice_detail'), ]
The <int:notice_id> part is a path converter—it takes the number from the URL and passes it as the notice_id parameter to your notice_detail view.
4. Update Your List Template's Hyperlinks
Now, modify your existing list template (where you loop through notices) to link each notice's content to the detail page. Use Django's URL reverse parsing to avoid hardcoding URLs:
<!-- notice_list.html (your existing list template) --> {% for notice in notices %} <div class="notice-item"> <p>通知编号: {{ notice.Notice_No }}</p> <!-- Link the content to the detail page --> <p>内容: <a href="{% url 'notice_detail' notice.Notice_No %}">{{ notice.Content|truncatechars:100 }}</a></p> <p>发布日期: {{ notice.publish_date|date:"Y-m-d H:i" }}</p> <p>到期日期: {{ notice.expiry_date|date:"Y-m-d H:i" }}</p> </div> {% endfor %}
{% url 'notice_detail' notice.Notice_No %}generates the correct URL for each notice using thenamewe set inurls.py.|truncatechars:100shortens long content in the list view—users can click through to see the full text.
5. Build the Detail Page Template
Create notice_detail.html (the independent page you mentioned) to display the full notice content in your CHS-compliant format:
<!-- notice_detail.html --> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>通知详情 - {{ notice.Notice_No }}</title> <!-- Add your CHS-compliant styles here (fonts, layout, etc.) --> <style> .notice-container { max-width: 800px; margin: 2rem auto; padding: 1.5rem; font-family: "Microsoft YaHei", sans-serif; line-height: 1.6; } .notice-header { border-bottom: 1px solid #eee; padding-bottom: 1rem; margin-bottom: 1rem; } .notice-content { white-space: pre-line; /* Preserves line breaks in the content */ } </style> </head> <body> <div class="notice-container"> <div class="notice-header"> <h1>通知编号: {{ notice.Notice_No }}</h1> <p><strong>发布日期:</strong> {{ notice.publish_date|date:"Y年m月d日 H:i" }}</p> <p><strong>到期日期:</strong> {{ notice.expiry_date|date:"Y年m月d日 H:i" }}</p> </div> <div class="notice-content"> {{ notice.Content }} </div> </div> </body> </html>
- The
white-space: pre-lineCSS rule keeps line breaks from yourContentfield intact, making the text easier to read. - Adjust the styles to match your CHS规范 requirements—this is just a starting point.
That's all! Now when users click the content link in your notice list, they'll be taken to the detail page showing the full, correct notice based on its primary key.
内容的提问来源于stack exchange,提问作者Tanmay

