我定义了一个模型,它对其他模型有一些外键。这样我在models.py中有以下内容:
class Appelation(models.Model):
appelation = models.CharField(max_length=100,
verbose_name=_('Appelation'),
validators=[non_numeric],
blank=True,
unique=True
)
class Wine(models.Model):
appelation = models.ForeignKey(ForeignKeyModel, null=True, blank=True, verbose_name=_('Appelation'))
表格.py
class WineForm(ModelForm):
class Meta:
model = Wine
appelation= CharField(widget=TextInput)
视图.py
class WineCreateView(WineActionMixin, LoginRequiredMixin, CreateView):
model = Wine
form_class = WineForm
action = 'created'
def post(self, *args, **kwargs):
self.request.POST = self.request.POST.copy() # makes the request mutable
appelationForm = modelform_factory(Appelation, fields=('appelation',))
form_dict = {
'appelation': appelationForm
}
for k, modelForm in form_dict.iteritems():
model_class = modelForm.Meta.model
log.debug('current model_class is: %s' % model_class)
log.debug('request is %s' % self.request.POST[k])
try:
obj = model_class.objects.get( **{k: self.request.POST[k]} )
log.debug("object exists. %s pk from post request %s " % (model_class,obj.pk))
self.request.POST[k] = obj.id
except ObjectDoesNotExist as e:
log.error('Exception %s' % e)
f = modelForm(self.request.POST)
log.debug('errors %s' % f.errors)
if f.is_valid():
model_instance = f.save()
self.request.POST[k] = model_instance.pk
return super(WineCreateView,self).post(self.request, *args, **kwargs)
基本上,视图代码所做的是,如果我们传递的那个不存在,它会尝试创建一个新的 Appelation 模型实例(它是 Wine 的一个 fk)。它返回字段中的 pk,因为我们期望一个 pk,而不是字符串作为输入。
我想创建 appelationForm,因为我需要应用一些自定义验证器来验证 foreignKey 输入。
我现在看到的限制是,我看不到如何将 appelationForm 中的验证错误附加到主表单的错误中,以便显示它们,而不是我们通常从 foreignKey 字段中显示的那些。
要查看完整的示例代码:
https://github.com/quantumlicht/django-wine/blob/master/project/corewine/models.py https://github.com/quantumlicht/django-wine/blob/master/project/corewine/forms.py https://github.com/quantumlicht/django-wine/blob/master/project/corewine/views.py