django CBV:以表单获取当前用户[副本]

时间:2023-01-26 18:20:27

This question already has an answer here:

这个问题已经有了答案:

I need to perform a form validation in wich current user is involved. I know how to do it but using FBV approach. Could be something like:

我需要在当前用户中执行表单验证。我知道怎么做,但是用FBV方法。可以是:

first declare the __ init __() method:

首先声明__ init()方法:

def __init__(self, user, *args, **kwargs):
    self.user = user
    super(MyFormClass, self).__init__(*args, **kwargs)

so now I can use the self.user in any validation method.

现在我可以用self了。用户在任何验证方法。

Later in a view method I could:

在以后的视图方法中,我可以:

if request.POST:
    form = MyFormClass(request.user, request.POST)

My question: How can I do the same but using CBV:

我的问题是:我如何用CBV做同样的事情呢?

Currently I'm using the CreateView generic, and the form_class attr:

目前我正在使用CreateView泛型和form_class attr:

class MyModelCreate(CreateView):
   model = MyModel
   form_class = MyFormClass

How can I instantiate MyFormClass with the current user using this way.

如何使用这种方式实例化MyFormClass和当前用户。

2 个解决方案

#1


1  

You need to override get_form() or get_form_kwargs(). If you are fuzzy about which methods to override in CBVs, a good reference is the excellent CCBV website. Here's a link to what you want from the CCBV docs:

您需要覆盖get_form()或get_form_kwargs()。如果您不清楚在cbv中应该覆盖哪些方法,一个很好的参考是优秀的CCBV网站。以下是你想从CCBV文档中得到的链接:

https://ccbv.co.uk/projects/Django/1.11/django.views.generic.edit/CreateView/#get_form_kwargs

https://ccbv.co.uk/projects/Django/1.11/django.views.generic.edit/CreateView/ get_form_kwargs

#2


0  

You can get the user in the form_valid method of CreateView.

您可以在CreateView的form_valid方法中获得用户。

def form_valid(self, form):
    user = self.request.user
    # add your validation

    return super(YourView, self).form_valid(form)

#1


1  

You need to override get_form() or get_form_kwargs(). If you are fuzzy about which methods to override in CBVs, a good reference is the excellent CCBV website. Here's a link to what you want from the CCBV docs:

您需要覆盖get_form()或get_form_kwargs()。如果您不清楚在cbv中应该覆盖哪些方法,一个很好的参考是优秀的CCBV网站。以下是你想从CCBV文档中得到的链接:

https://ccbv.co.uk/projects/Django/1.11/django.views.generic.edit/CreateView/#get_form_kwargs

https://ccbv.co.uk/projects/Django/1.11/django.views.generic.edit/CreateView/ get_form_kwargs

#2


0  

You can get the user in the form_valid method of CreateView.

您可以在CreateView的form_valid方法中获得用户。

def form_valid(self, form):
    user = self.request.user
    # add your validation

    return super(YourView, self).form_valid(form)