我一直在嘗試向我正在創建的博客頁面添加評論。我有一個評論模型,它有一個帖子 ID 作為外鍵,還有用戶,因為我只想允許用戶發表評論。
class Comment(models.Model):
post = models.ForeignKey(
Article, on_delete=models.CASCADE, related_name='comments')
name = models.ForeignKey(
User, blank=True, null=True, on_delete=models.SET_NULL)
email = models.EmailField()
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
class Meta:
ordering = ['created_on']
但是在保存時,它會回傳 404 錯誤。
Not Found: /articles/this-is-first-article/
[05/Nov/2021 16:51:05] "POST /articles/this-is-first-article/ HTTP/1.1" 404 2912
這是我的網址:
app_name = 'articles'
urlpatterns = [
path('', article_search_view, name='search'),
path('create/', article_create_view, name='create'),
path('<slug:slug>/', article_detail_view, name='detail'),
]
這是我的觀點:
def article_detail_view(request, slug=None):
article_obj = None
new_comment = None
comments = None
comment_form = None
if slug is not None:
try:
article_obj = Article.objects.get(slug=slug)
comments = article_obj.comments.filter(active=True)
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.article = article_obj
new_comment.save()
return redirect(article_obj.get_absolute_url())
else:
comment_form = CommentForm()
except Article.DoesNotExist:
raise Http404
except Article.MultipleObjectsReturned:
article_obj = Article.objects.filter(slug=slug).first()
except:
raise Http404
context = {
"object": article_obj,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form
}
return render(request, "articles/detail.html", context=context)
我知道這是一個微不足道的問題,但如果您能幫助我理解出了什么問題,我將不勝感激。我也想讓用戶可以評論評論,但這可能是一個不同的時間,因為我還沒有嘗試過自己。但是,如果您有快速解決方案,請告訴我。
uj5u.com熱心網友回復:
現在,您可以首先傳遞 primary_key 和 slug,就像 stackoverflow 對這些 url 所做的一樣。這將幫助您確保該.get()方法會給您一個專案。我使用 get_object_or_404 來避免try and except.
from django.shortcuts import get_object_or_404
def article_detail_view(request,slug=None):
article_obj = None
new_comment = None
comments = None
comment_form = None
if slug is not None:
article_obj = get_object_or_404(Article,slug=slug)
comments = article_obj.comments.filter(active=True)
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = article_obj
new_comment.save()
return redirect(article_obj.get_absolute_url())
else:
comment_form = CommentForm()
context = {
'object': article_obj,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form
}
return render(request, "articles/detail.html", context=context)
更改您的網址:
app_name = 'articles'
urlpatterns = [
path('', article_search_view, name='search'),
path('create/', article_create_view, name='create'),
path('<slug:slug>/', article_detail_view, name='detail'),
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/349987.html
標籤:姜戈
