根据条件在基于Django类的视图中获取不同的表单

时间:2019-01-11 17:30:50

标签: python django django-forms django-views django-class-based-views

假设我的表格如下:

SUBSCRIBE

现在我想在基于类的视图中获取表单:

Class FormCreateView(CreateView):         型号=用户

class FormA(models.ModelForm):
    ...
class FormB(models.ModelForm):
  ....
class FormC(models.ModelForm):
 .....

所以我已经这样做了。但是表单没有被提交,它给我输入错误:

    def post(self, request, *args, **kwargs):
        if self.request.user.user_level == 1:
             get FormA
        if self.request.user.user_level == 2:
             get FormB
        if self.request.user.user_level == 3:
             get Formc
        return reverse('xyz')

课程

Exception Value:    
is_valid() missing 1 required positional argument: 'self'
Exception Location:  
/home/bishwa/PycharmProjects/sharefile/sharefile/users/views.py in post, line 64

我的class UserCreateView(CreateView): model = User # form_class = UserCreationForm template_name = "users/create_user.html" success_url= "/users/create" def get_form_class(self): if self.request.user.user_level == 1 or self.request.user.user_level == 10: # form_class = UserCreationForm return UserCreationForm elif self.request.user.user_level == 20: # form_class = UserCreationFormCompanyManager return UserCreationFormCompanyManager else: # form_class = UserCreationFormHomeManager return UserCreationFormHomeManager def post(self, request, *args, **kwargs): form = self.get_form_class() user_level = User.objects.get(id=request.user.id) # form = UserCreationFormHomeManager(request.POST) # if request.method=='POST': # form = UserCreationFormCompanyManager(request.POST) if user_level == 20: if form.is_valid(): obj = form.save(commit=False) obj.company = self.request.user.company # obj.password = make_password(form.cleaned_data['password']) print(obj) obj.save() return obj elif user_level == 30: # if request.method=='POST': # form = UserCreationFormHomeManager(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.company = self.request.user.company obj.home = self.request.user.home # obj.password = make_password(form.cleaned_data['password']) print(obj) obj.save() return obj else: # if request.method=='POST': # form = UserCreationFormHomeManager(request.POST) if form.is_valid(): # obj.password = make_password(form.cleaned_data['password']) print(obj) obj = form.save() return obj return HttpResponseRedirect(reverse('users:create-user')) 中有这三种形式。当我尝试通过form.py调用表单(即已注释的一个)方法表单时,未保存该表单。

1 个答案:

答案 0 :(得分:0)

您可以在get_form_class方法中使用选择表单:

def get_form_class(self):
    if self.request.user.user_level == 1:
         return FormA
    elif self.request.user.user_level == 2:
         return FormB
    elif self.request.user.user_level == 3:
         return FormC
    else:
         return DefaultForm