【问题标题】:Load different HTML page based on URL in Django class based view在基于 Django 类的视图中基于 URL 加载不同的 HTML 页面
【发布时间】:2018-07-18 20:55:10
【问题描述】:

目前我的 urls.py 有这个代码:

login_view = LoginView.as_view()
url(r'^login$', login_view, name='login'),

我在views.py中写了一个对应的LoginView:

class LoginView(FormView):
    template_name = 'auth/login.html'
    form_class = forms.LoginForm

现在我的要求是我想为来自不同 url 的不同用户集创建一个登录页面。例如myproject.com/customers。 我可以用一个新的 View 类来做到这一点。但我想让它通用并在同一个 LoginView() 类中处理它。

是否可以捕获 url 参数并在 LoginView() 中检查它并为它们加载不同的 login.html 页面?或者有没有其他方法可以处理这种情况?

【问题讨论】:

    标签: python python-3.x django django-class-based-views django-1.8


    【解决方案1】:

    由于您使用的是FormView,因此您可以覆盖以下方法,如下例所示。模板以render_to_response 方法呈现。

    def render_to_response(self, context, **response_kwargs):
        """
        Returns a response, using the `response_class` for this
        view, with a template rendered with the given context.
        If any keyword arguments are provided, they will be
        passed to the constructor of the response class.
        """
    
        # Write you logic here
        if self.request.something == "customer":
            template = "customer_login.html"
        else:
            template = "user_login.html"
        #######
        response_kwargs.setdefault('content_type', self.content_type)
        return self.response_class(
            request=self.request,
            template=template,
            context=context,
            using=self.template_engine,
            **response_kwargs
        )
    

    更多信息可以https://ccbv.co.uk/projects/Django/1.11/django.views.generic.edit/FormView/

    【讨论】:

      猜你喜欢
      • 2012-12-28
      • 2017-05-08
      • 1970-01-01
      • 2012-01-25
      • 2014-10-12
      • 1970-01-01
      • 2014-02-16
      • 1970-01-01
      • 2012-04-16
      相关资源
      最近更新 更多