Django 当表单不存在时执行validate#u unique';不包括所有字段

Django 当表单不存在时执行validate#u unique';不包括所有字段,django,django-forms,Django,Django Forms,我最近遇到一个情况,我的模型中的validate_unique方法没有运行。这是因为表单中没有包含唯一测试中涉及的一个字段。在使用此解决方案之前,我在表单和视图中尝试了很多方法:首先将字段注入UpdateView的对象,然后在_post_clean中以表单运行测试 models.py class Link(ModelBase): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

我最近遇到一个情况,我的模型中的validate_unique方法没有运行。这是因为表单中没有包含唯一测试中涉及的一个字段。在使用此解决方案之前,我在表单和视图中尝试了很多方法:首先将字段注入UpdateView的对象,然后在_post_clean中以表单运行测试

models.py 

class Link(ModelBase):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=200,blank=True,null=False)
    url = models.URLField(max_length=400,blank=False,null=False)
    profile = models.ForeignKey('Profile',null=False,blank=False,on_delete=models.CASCADE)

    class Meta:
        unique_together = ('url','profile')

    class Admin:
        pass

forms.py 

class LinkForm(ModelForm):

    def _post_clean(self):
        ''' Be sure that the instance validate_unique test 
            is run including the profile field '''
        super(LinkForm,self)._post_clean()
        try:
            self.instance.validate_unique(exclude=None)
        except ValidationError as e:
            self._update_errors(e)

    class Meta:
        model = Link
        fields = ['title','url']

views.py 

class LinkUpdateView(UpdateView):
    model = Link
    form_class = LinkForm

    def get_form_kwargs(self):
        ''' Add profile to self.object before kwargs are populated '''

        if hasattr(self, 'object') and self.object and self.profile:
                self.object.profile = profile

        kwargs = super(LinkUpdateView, self).get_form_kwargs()

        return kwargs   

有没有更好的方法不需要重写内部函数就可以做到这一点?

我有过类似的问题,我用这种方法解决了它:

  • 我在表格中包括了这个字段
  • 我在基于类的视图中重写了
    get\u form
    ,将字段隐藏给用户,并给它我想要的值
这样,由于包含该字段,它会触发验证,但用户无法填充它

看起来是这样的:

    def get_form(self, form_class=None):
        form = super(MyClass, self).get_form(form_class)
        form.fields['some_field'].initial = some_value
        form.fields['some_field'].widget = forms.HiddenInput()
        return form

我考虑过这样做,但不想为隐藏字段编写验证代码。现在我知道了如何将额外的Kwarg传递给表单,我可能会恢复这个想法。谢谢