Django Best实践覆盖外键表单小部件以接收用户输入

时间:2013-11-03 18:52:41

标签: django forms django-models django-forms django-views

我定义了一个对其他模型有一些外键的模型。这样我在 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'))

forms.py

class WineForm(ModelForm):

    class Meta: 
        model = Wine

    appelation= CharField(widget=TextInput)

views.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

1 个答案:

答案 0 :(得分:2)

您应该在clean_appelation上编写WineForm方法,根据您的条件全面验证输入,即现有的Appelation ID或新的Appelation名称,并提升适当的错误。然后在您的视图中,您可以假设表单数据有效并且可以正常工作。这应该给你一些开始:

class WineForm(ModelForm):
    ...
    appelation= CharField(widget=TextInput)
    def clean_appelation(self):
        data = self.cleaned_data['appelation']
        if data.isdigit():
             # assume it's an id, and validate as such
             if not Appelation.objects.filter(pk=data):
                 raise forms.ValidationError('Invalid Appelation id')
        else:
             # assume it's a name
             if ...:
                 raise forms.ValidationError('Invalid Appelation name')
        return data