所以我有这两种形式。当我为其他表单检查add_uRG时,我希望能够以env_form格式访问数据。是否有可能做到这一点?我的环境形式在我的应用程序中是一种非常常见的形式,因此我希望将其保持分开,而不是将其包含在每个表单中。
class env_form(forms.Form):
env = forms.ChoiceField(choices=ENV, required=True)
class add_uRG(forms.Form):
user = forms.CharField(max_length=50)
group = forms.CharField(required=True)
role = forms.CharField(required=True)
def clean_user(self):
post_user = self.cleaned_data['user']
post_env = self.cleaned_data['env']
c = User.objects.filter(user__contains=post_user, env__contains=post_env ).count()
if (c == 0):
raise forms.ValidationError(u"User Not Found.")
else:
user_info = User.objects.filter(user__contains=post_user).values('password').distinct().count()
user_env = User.objects.filter(user__contains=post_user).values('env').distinct().count()
if not (user_env == user_info):
raise forms.ValidationError(u'User is using same password')
return(post_user)
答案 0 :(得分:0)
您可以在验证env_form后在add_uRG表单上指定属性,或者可以将值作为参数传递给add_uRG表单。
#forms.py
class AdduRGForm(forms.Form):
def __init__(self, *args, **kwargs):
super(AdduRGForm, self).__init__(*args, **kwargs)
self.env = None
#my_view.py
def my_view(request):
env_form = env_form(request.POST or None)
if request.POST:
if env_form.is_valid():
add_uRG_form = AdduRGForm(request.POST or None)
add_uRG_form.env = env_form.cleaned_data.get('env')
if add_uRG_form.is_valid():
#do something else
return render_to_response('template.html',
{'env_form' : env_form, 'add_uRG_form' : add_uRG_form})
我不完全确定您的工作流程,因此如果这些表单不存在于同一视图中,就像您首先处理env_form,然后转到另一个视图并需要之前选择的某个值,您可以将请求传递给env_form,并在会话中设置选择,您可以使用我概述的方法在第二个表单中再次选择。
答案 1 :(得分:0)
如果我正确地阅读了您的问题,我认为可以在此处使用表单继承。
class env_form(forms.Form):
env = forms.ChoiceField(choices=ENV, required=True)
class add_uRG(env_form):
user = forms.CharField(max_length=50)
group = forms.CharField(required=True)
role = forms.CharField(required=True)
def clean_user(self):
post_user = self.cleaned_data['user']
post_env = self.cleaned_data['env']
c = User.objects.filter(user__contains=post_user, env__contains=post_env ).count()
if (c == 0):
raise forms.ValidationError(u"User Not Found.")
else:
user_info = User.objects.filter(user__contains=post_user).values('password').distinct().count()
user_env = User.objects.filter(user__contains=post_user).values('env').distinct().count()
if not (user_env == user_info):
raise forms.ValidationError(u'User is using same password')
return(post_user)
def __init__(self, *args, **kwargs):
super(env_form, self).__init__(*args, **kwargs)
class SomeOtherForm(env_form):
some_field = forms.CharField()
def __init__(self,*args,**kwargs):
super(env_form, self).__init__(*args,**kwargs)