来自 URL 的模板 class 视图,其中的变量未显示

Template class view from URL with variables in it not displaying

我目前正在尝试使用 URL 中的变量渲染此 class 模板视图。

例如我有 http://localhost:8000/confirm/?email=hello@example.com&conf_num=641484032777 作为 URL

我的 class 视图如下所示

class Confirm(TemplateView):
    template_name = 'confirm.html'
    def get_context(self, request, *args, **kwargs):
        context = super(Confirm, self).get_context()
        sub = Newsletter.objects.get(email=request.GET['email'])
        if sub.conf_num == request.GET['conf_num']:
            sub.confirmed = True
            sub.save()
            context['email'] = request.GET['email']
            context['action'] = 'added'
        else:
            context['email'] = request.GET['email']
            context['action'] = 'denied'
        return context

我的urls.py看起来像这样

    path('confirm/', views.Confirm.as_view(), name='confirm'),

我的 confirm.html 看起来像这样

<!doctype html>
<html>
    <head>
        <title> Email Newsletter </title>
        <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    </head>
    <body>
        <div class="container">
            <div class="col-12">
                <h1>Email Newsletter</h1>
            </div>
            <div class="col-12">

                <p>{{ email }} has been {{ action }}.</p>

            </div>
        </div>
    </body>
</html>

但出于某种原因,它从不显示电子邮件或操作的更新。任何帮助将不胜感激

您可能需要使用 get_context_data 而不是 get_context。所以:

class Confirm(TemplateView):
    template_name = 'confirm.html'
    def get_context_data(self, *args, **kwargs):
        context = super(Confirm, self).get_context_data()
        sub = Newsletter.objects.get(email=self.request.GET['email'])
        if sub.conf_num == self.request.GET['conf_num']:
            sub.confirmed = True
            sub.save()
            context['email'] = self.request.GET['email']
            context['action'] = 'added'
        else:
            context['email'] = self.request.GET['email']
            context['action'] = 'denied'
        return context

*注意:- self 将具有其 request 属性以获取 GET 方法。所以,不需要传递 request 作为参数。