如何在Django 2.1中实施新帖子的审核 [英] How to implement the moderation of new posts at Django 2.1
问题描述
我是Django的初学者.我写的是Django 2.1,Python 3.6.面临以下问题.我想审核新创建的帖子.也就是说,可以在管理面板中打勾,并且只有在发布之后才可以.但是,当然,理想情况下,当然是这样,以便管理员可以在网站上直接看到新条目,并允许它们在该位置发布.
I'm beginner in Django. I'm write on Django 2.1, Python 3.6. Faced the following problem. I want to moderate new posts created. That is, that it was possible to put a tick in the admin panel, and only after that the post would be published. But ideally, of course, so that the administrator could see the new entries right on the site and allow them to publish right there.
models.py
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=50)
body = models.TextField()
moderation = models.BooleanField(default=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
forms.py
from .models import Post
class PostForm(forms.ModelForm):
title = forms.CharField(required=True)
body = forms.CharField(widget=forms.Textarea)
class Meta:
model = Post
fields = ['title', 'body']
views.py
from .forms import PostForm
class PostCreateView(FormView):
form_class = PostForm
template_name = 'blog/post_form.html'
success_url = reverse_lazy('posts')
def form_valid(self, form):
response = super(PostCreateView, self).form_valid(form)
form.instance.user = self.request.user
form.save()
return response
admin.py
from .models import Post
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'user', 'moderation')
admin.site.register(Post, PostAdmin)
urls.py
urlpatterns = [
url(r'^posts/$', views.PostListView.as_view(), name='posts'),
url(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(), name='post-detail'),
]
我希望它像图片一样.或者,您可以立即在网站上观看和审核帖子.
I want it to be like in the picture. Or you can watch and moderate the post right away on the site.
推荐答案
好,在您的PostListView中,定义如下的get_queryset方法:
Well, in your PostListView, define the get_queryset method like this:
class PostListView(ListView):
...
def get_queryset(self):
queryset = super(PostListView, self).get_queryset()
return queryset.filter(moderation=True)
这里发生的是,除非帖子由管理员主持,否则它将在PostListView中可用.
What happens here is that, unless the posts are moderated by admin, it will be available in PostListView. More details on filter is available in this documentation.
这篇关于如何在Django 2.1中实施新帖子的审核的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!