我嘗試了很多使用過濾器的方法,因為嘗試獲取單個物件但它仍然有效。當我從我的管理部分發帖時,一切正常,但是當使用表單從我的前端發帖時,它會創建帖子然后向我顯示物件不可迭代“注意:帖子創建得非常好”但我得到了可迭代的error 和 slug 不會像在后端管理部分那樣自動填充到前端。任何幫助都會非常有用,并使我的作業更快。讓我展示一些我的代碼
視圖.py
#this is for allowing user to create a new post from the frontend
def blogpost(request):
if request.method == "POST":
form = BlogPostForm(request.POST, request.FILES)
if form.is_valid():
form = form.save(commit=False)
form.creator = request.user
form.save()
messages.success(request, f'Hi, Your Post have been sent for review and would be live soon!')
else:
form = BlogPostForm()
context = {
"form": form
}
return render(request, 'blog/AddPost.html', context)
#this is for listing all the blog posts
def BlogList(request):
posts = Blog.objects.filter(status='published').order_by('-created').values()
categoriess = Category.objects.all()
context = {
'posts': posts,
'categories': categoriess,
}
return render(request, 'blog/bloghome.html', context)
# This is view for blog details
def BlogDetail(request, blog_slug):
post = get_object_or_404(Blog, slug=blog_slug)
# post = Blog.objects.filter(slug=blog_slug)
categories = Category.objects.all()
comments = post.comments.filter(active=True)
new_comment = None
if request.method == "POST":
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.name = request.user
new_comment.save()
else:
comment_form = CommentForm()
表格.py
class BlogPostForm(forms.ModelForm):
class Meta:
model = Blog
fields = ['title', 'slug', 'content', 'image', 'category', 'tags']
模型.py
class Blog(models.Model):
title = models.CharField(max_length=10000, null=True, blank=True, verbose_name="Title")
content = models.TextField(verbose_name="Post Content")
slug = models.SlugField(unique=True)
image = models.ImageField(upload_to="blog-images/%Y/%m/%d/", verbose_name="Post Thumbnail")
category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, verbose_name="Category", null=True)
tags = models.ManyToManyField(Tag, related_name='tags', verbose_name="Tag", null=True)
status = models.CharField(choices=STATUS_CHOICE, default="published", max_length=150, verbose_name='Status')
creator = models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name="Creator", null=True)
created = models.DateTimeField(auto_now_add=True ,verbose_name="Created", null=True)
def get_absolute_url(self):
return reverse('blog:blog-details', args=[self.slug])
class Meta:
verbose_name = "Blog Post"
verbose_name_plural = "Blog Posts"
def __str__(self):
return self.title
網址.py
urlpatterns = [
path('', views.BlogList, name="home"),
path('post/<slug:blog_slug>', views.BlogDetail, name="blog-details"),
path('post/categories/<slug:category_slug>', views.category, name="category"),
path('post/tags/<slug:tag_slug>', views.tag, name="tags"),
path('post/create/', views.blogpost, name="add-post"),
博客主頁.html
<!-- this would list out all the blog post -->
{% for post in posts %}
<div class="col-lg-4 col-md-6 col-sm-12">
<div class="articles_grid_style style-2">
<div class="articles_grid_thumb">
<a href="{{post.get_absolute_url}}"><img src="{{post.image.url}}" class="img-fluid" alt="" style="width: 450px; height: 250px;"></a>
</div>
<div class="articles_grid_caption">
<div class="mpd-date-wraps">
<!-- <span >10</span> -->
<span class="mpd-meta-month">{{post.created|date:"d, M Y"}}</span>
</div>
<div class="blog-grid-cat" style="background: rgb(161, 161, 161); color: white;">{{post.category}}</div>
<a href="{{post.get_absolute_url}}"><h4>{{post.title|truncatechars:70}}</h4></a>
<div class="articles_grid_desc">
<p style="color: black;">{{post.content|truncatechars:80}}</p>
</div>
</div>
<div class="articles_grid_caption-footer">
<div class="articles_grid_author">
<div class="articles_grid_author_img"><img src="{{post.creator.profile.image.url}}" class="img-fluid" alt=""></div>
<a href="">
<h4>{{post.creator.profile.first_name}} {{post.creator.profile.last_name}}</h4>
</a>
</div>
<div class="footer-flex-last">
<a href="{{post.get_absolute_url}}" class="bl-detail-view" style="background:linear-gradient(230deg, rgb(255, 0, 157) 0%, rgb(111, 0, 255) 100%), url(assets/img/tag-light.png) no-repeat; color: white;"><b>READ MORE</b></a>
</div>
</div>
</div>
</div>
{% endfor %}
添加post.html
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form|crispy}}
<div class="form-group">
<button class="btn theme-bg rounded" type="submit">Send Message</button>
</div>
</form>
博客詳細資訊.html
<div class="post-featured-img">
<img class="img-fluid" src="{{ post.image.url }}" alt="">
</div>
<div class="post-top-meta">
<ul class="meta-comment-tag">
<li><a href="#"><span class="icons"><i class="ti-user"></i></span>by {{ post.creator.profile.first_name }} {{ post.creator.profile.last_name }}</a></li>
<li><a href="#"><span class="icons"><i class="ti-comment-alt"></i></span>{{comments.count}} Comments</a></li>
</ul>
</div>
<h2 class="post-title">{{ post.title }}</h2>
<p style="color: black;">{{ post.content }}<p>
uj5u.com熱心網友回復:
查看您的模板代碼會很有幫助,但這里有一些我看到的問題。
第一,你的blogpost看法。當您執行 POST 請求時,在保存表單并設定成功訊息后,重定向到BlogDetail視圖。按照您的編碼方式,在保存表單后,它將再次呈現blogpost視圖,這次使用包含請求 POST 資料的表單。抬頭看redirect 這里。
其次,在您BlogList看來,您正在呼叫.values()您的查詢集posts。沒有看到您的模板代碼,我無法判斷這是否是故意的,但請確保您知道values()從查詢集中回傳的內容。您可能不想使用它。
第三,您的BlogDetail視圖不回傳任何內容,您需要render像其他視圖一樣使用例如回傳 HttpResponse 。
最后一點,它的通用約定是用小寫命名基于函式的視圖,用 _ 作為空格。CamelCase 保留用于基于類的視圖。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/360200.html
