【发布时间】:2021-11-19 10:42:39
【问题描述】:
我已经尝试了很多方法来解决这个问题,但它们都不起作用,这就是为什么我想在这里问比我更好的人。我试过使用 slug 字段它没有显示,但我想在它开始显示错误时使用 id。注意:帖子创建得非常好,然后显示此错误,但帖子已发布。我尝试使用前端的表单发布帖子
让我展示一些代码 视图.py
def blogpost(request):
if request.method == "POST":
form = BlogPostForm(request.POST, request.FILES)
if form.is_valid():
form.instance.creator = request.user
form.save() # ← no commit=False
messages.success(request, f'Hi, Your Post have been sent for review and would be live soon!')
return redirect('blog:home')
else:
form = BlogPostForm()
context = {
'form': form
}
return render(request, 'blog/AddPost.html', context)
# this is the blog list view
def blog_list(request):
posts = Blog.objects.filter(status='published').order_by('-created')
categoriess = Category.objects.all()
context = {
'posts': posts,
'categories': categoriess,
}
return render(request, 'blog/bloghome.html', context)
#this is the blog detail view
def blog_detail(request, post_id):
post = get_object_or_404(Blog, id=post_id)
# 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()
context = {
'post': post,
'comments': comments,
'comment_form': comment_form,
'new_comment': new_comment,
'categories': categories,
}
return render(request, 'blog/blog-details.html', context)
forms.py
class BlogPostForm(forms.ModelForm):
image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=True)
# content = forms.CharField(widget=forms.Textarea(attrs={'class': 'input is-medium'}), required=True)
tags = forms.CharField(widget=forms.TextInput(attrs={'class': 'input is-medium'}), required=True)
class Meta:
model = Blog
fields = ('title', 'content', 'image', 'category', 'tags')
addpost.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>
urls.py
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.blog_list, name="home"),
# path('post/<uuid:posts_id>', views.blog_detail, name="blog-details"),
path('<uuid:post_id>', views.blog_detail, 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"),
]
任何帮助将不胜感激
【问题讨论】: