[英]Django CreateView validate field not in fields
因此,我有一个Django通用视图:
class Foobaz(models.Model):
name = models.CharField(max_length=140)
organisation = models.ForeignKey(Organisation)
class FoobazForm(forms.ModelForm):
class Meta:
model = Foobaz
fields = ('name')
class FoobazCreate(CreateView):
form_class = FoobazForm
@login_required
def dispatch(self, *args, **kwargs):
return super(FoobazCreate, self).dispatch(*args, **kwargs)
我想做的是从URL中获取组织ID:
/organisation/1/foobaz/create/
并将其添加回创建的对象。 我意识到我可以在CreateView.form_valid()
做到这一点,但是据我了解,这是完全无效的。
我尝试将其添加到get_form_kwargs()
但这并不期望组织kwarg,因为它不在所包含的字段中。
理想情况下,我想做的是将其添加到表单实例中,以与其他表单进行验证-确保它是有效的组织,并且所涉及的用户具有向其添加新的foobaz的正确权限。
如果这样做是最好的方法,我很乐意发表自己的看法,但我可能只是想念一个窍门。
谢谢!
我认为最好包括organisation
字段并将其定义为隐藏和只读,这样django会为您验证它。
然后,您可以像这样重写get_queryset
方法:
def get_queryset(self):
return Foobaz.objects.filter(
organisation__id=self.kwargs['organisation_id'])
其中organisation_id
是URL模式中的关键字。
您可以重写View的get_kwargs()
方法和Form的save()
方法。 在get_kwargs()
将organization_id
“注入”到表单的初始数据中,在save()
,使用提供的初始数据检索缺少的信息:
在urls.py中:
urlpatterns('',
#... Capture the organization_id
url(r'^/organisation/(?P<organization_id>\d+)/foobaz/create/',
FoobazCreate.as_view()),
#...
)
在views.py中:
class FoobazCreate(CreateView):
# Override get_kwargs() so you can pass
# extra info to the form (via 'initial')
# ...(all your other code remains the same)
def get_form_kwargs(self):
# get CreateView kwargs
kw = super(CreateComment, self).get_form_kwargs()
# Add any kwargs you need:
kw['initial']['organiztion_id'] = self.kwargs['organization_id']
# Or, altenatively, pass any View kwarg to the Form:
# kw['initial'].update(self.kwargs)
return kw
在forms.py中:
class FoobazForm(forms.ModelForm):
# Override save() so that you can add any
# missing field in the form to the model
# ...(Idem)
def save(self, commit=True):
org_id = self.initial['organization_id']
self.instance.organization = Organization.objects.get(pk=org_id)
return super(FoobazForm, self).save(commit=commit)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.