我可以在基于类的视图中实现UserPassesTestMixin
class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Post
success_url = '/'
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
但是我不知道如何在基于函数的视图中实现它?谢谢
编辑:
def permission_of_user_for_posts(request,**kwargs):
post = get_object_or_404(Blog, slug= request.GET.get('blog_slug'))
if request.user.username == post.author:
return True
return False
@user_passes_test(permission_of_user_for_posts)
def blog_create(request):
if request.method == 'POST':
form = BlogForm(request.POST, request.FILES)
if form.is_valid():
form.instance.author = request.user
slug = form.instance.slug
form.save()
return redirect('/')
form = BlogForm()
context = {
'form':form,
}
return render(request, 'blogs/form.html', context)
答案 0 :(得分:2)
from django.contrib.auth.decorators import user_passes_test
def email_check(user):
return user.email.endswith('@example.com')
@user_passes_test(email_check)
def my_view(request):
...