python - 我想向 Django DetailView 添加条件

标签 python django django-generic-views detailview

我正在使用 Django 通用 View DetailView。 但我想阻止用户访问尚未通过电子邮件确认的详细信息。 我在用户模型中有一个 email_confirmed 字段。

我的代码是:

@method_decorator(login_required(login_url='/login/'), name='dispatch')
class RecruitView(generic.DetailView):
    model = Recruit
    template_name = 'recruit.html'

我想补充:

    if not request.user.email_confirmed:
        error_message = "you did not confirmed yet. please check your email."
        return render(request, 'info.html', {'error_message': error_message})
    else: pass

如何将此条件添加到 DetailView?

(我试图覆盖“as_view”,但我不知道该怎么做)

最佳答案

我会使用 PermissionRequiredMixin .有了这个,您可以指定用户需要拥有的特定权限或覆盖 has_permission方法。

from django.contrib.auth.mixins import PermissionRequiredMixin

class RecruitView(PermissionRequiredMixin, generic.DetailView):
    ...

    login_url = '/login/'
    permission_denied_message = 'you did not confirmed yet. please check your email.'

    def has_permission(self):
         return self.request.user.email_confirmed

这会将没有 email_confirmed 的用户重定向到可以显示错误消息的 login_url。为了使用 index.html 模板,您可能需要覆盖 handle_no_permission方法。

关于python - 我想向 Django DetailView 添加条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47811179/

相关文章:

Django 自动完成灯 - "The results could not be loaded"

python - django.template.exceptions.TemplateDoesNotExist : registration/login. html

Django 表单前缀与基于类的通用 View

python - 无法将页面从主页转移到关于页面

python - 如何让 matplotlib (pyplot) 绘图循环更新?

python - 在 gmail 中使用预填充的 html 正文撰写电子邮件

python - 脚本在 IDLE 中返回输出,而不是在 CLI 上执行时

python - 为什么 TensorFlow 2 比 TensorFlow 1 慢得多?

python - 如何在 django-paypal IPN 函数中获取我的请求数据?

python - 当登录来自cookie时,如何识别用户登录?