python - 如何向类 View 添加逻辑

标签 python django

我有以下类 View :

class RegisterView(generic.CreateView):
    model = User
    form_class = forms.RegisterForm
    template_name = 'register.html'
    success_url = reverse_lazy('platforms')

    def form_valid(self, form):
        response = super(RegisterView, self).form_valid(form)
        user = authenticate(username=form.instance.username, password=form.cleaned_data['password'])
        login(self.request, user)
        return response

我如何将以下语句添加到上面的语句中,我会在普通函数中执行此操作?

def normal_register_function(request):
    if request.user is not None:
        return redirect('home')
    # register logic
    return render(request, 'register.html', data)

最佳答案

像这样:

class RegisterView(generic.CreateView):
    model = User
    form_class = forms.RegisterForm
    template_name = 'register.html'
    success_url = reverse_lazy('platforms')

    def get(self, request, *args, **kwargs):
        if request.user is not None:
            return redirect('home')
        # register logic
        return render(request, 'register.html', data)

    def form_valid(self, form):
        response = super(RegisterView, self).form_valid(form)
        user = authenticate(username=form.instance.username, password=form.cleaned_data['password'])
        login(self.request, user)
        return response

关于python - 如何向类 View 添加逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34231593/

相关文章:

python - os.rename 返回 winerror 2

python - 动态规划难题: Find longest consecutive pairs of 3 (different) pieces

python - 将使用 lambda 解包的元组从 Python 2 移植到 Python 3 的大多数 pythonic 方法

json - 结合 DjangoObjectType 和 ObjectType - Django, GraphQL

python - 在 Virtualbox>Vagrant>Ubuntu 上开始使用 Django。无法运行 django-admin

python - Tango with Django (v1.9/1.10) - 第 5 章,populate_rango 问题

python - Django Rest Framework 动态分组对象

python - 将多个绘图包装在一个图像中

python - 如何使服务器接受来自多个端口的连接?

python - pydev 无法识别 django 安装