我對(duì) Django 很陌生,對(duì)文檔有點(diǎn)不知所措。我認(rèn)為我的問(wèn)題很簡(jiǎn)單,但我發(fā)現(xiàn)的一切都讓我更加困惑。我正在使用模型 NewsItem 構(gòu)建一個(gè)小新聞應(yīng)用程序:from django.db import modelsfrom django.utils import timezone# Create your models here.class NewsItem(models.Model): title = models.CharField(max_length=50) newsText = models.TextField() dateEntered = models.DateTimeField('date entered') datePublished = models.DateTimeField('date published', blank=True, null=True) user = models.CharField(max_length=30) #temporary field. will be changed to user foreign key def __str__(self): return self.title def publish(self): if (self.datePublished == None): self.datePublished = timezone.now() def published(self): return self.datePublished != None兩個(gè)視圖(技術(shù)上 3)索引和詳細(xì)信息from django.http import HttpResponseRedirectfrom django.shortcuts import render, get_object_or_404from django.urls import reversefrom django.views import genericfrom .models import NewsItem# Create your views here.class IndexView(generic.ListView): template_name = 'news/index.html' context_object_name = 'latestNewsList' def get_queryset(self): return NewsItem.objects.order_by('-datePublished')[:5]#todoclass DetailView(generic.DetailView): model = NewsItem template_name = 'news/detail.html'def publish(request, itemId): newsItem = get_object_or_404(NewsItem, pk=itemId) newsItem.publish() newsItem.save() return HttpResponseRedirect(reverse('news:detail', args=(newsItem.id,)))和這樣的 urlconffrom django.urls import pathfrom . import viewsurlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:itemId>/publish', views.publish, name='publish'),]在詳細(xì)視圖中,我有一個(gè)鏈接發(fā)布,它只觸發(fā)函數(shù)views.publish。該視圖應(yīng)該重定向回詳細(xì)視圖。我現(xiàn)在要做的是在發(fā)布視圖重定向時(shí)在詳細(xì)視圖中顯示一條小消息(如成功發(fā)布的文章)。但我不知道什么是好的方法我可以在發(fā)布視圖中呈現(xiàn)詳細(xì)信息模板,但它仍然會(huì)在 URL 中顯示新聞/發(fā)布而不是新聞/詳細(xì)信息在此先感謝您的幫助
1 回答

守著星空守著你
TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超8個(gè)贊
看看消息框架。您可以在重定向之前添加一條成功消息,該消息將顯示在下一頁(yè)上。
from django.shortcuts import redirect
from django.contrib import messages
def publish(request, itemId):
newsItem = get_object_or_404(NewsItem, pk=itemId)
newsItem.publish()
newsItem.save()
messages.success(request, "The post has been published")
return redirect('news:detail', newsItem.id)
請(qǐng)注意,我已經(jīng)簡(jiǎn)化了return要使用的語(yǔ)句,redirect(...)而不是HttpResponseRedirect(reverse(...)).
添加回答
舉報(bào)
0/150
提交
取消