gpt4 book ai didi

python - Django - 使用 full_clean() 验证管理错误

转载 作者:太空宇宙 更新时间:2023-11-03 18:43:17 25 4
gpt4 key购买 nike

我使用 modelformset_factory,并使用 full_clean() 来验证带有 unique_together=True 的表单。我想知道在 unique_together 未验证以返回模板中的错误消息的情况下处理错误的最佳方法是什么。

请看看我的观点,并告诉我我的做法是否正确,或者是否有更好的方法。

型号:

class Attribute(models.Model):
shapefile = models.ForeignKey(Shapefile)
name = models.CharField(max_length=255, db_index=True)
type = models.IntegerField()
width = models.IntegerField()
precision = models.IntegerField()

def __unicode__(self):
return self.name

def delete(self):
shapefile = self.shapefile
feature_selected = Feature.objectshstore.filter(shapefile=shapefile)
feature_selected.hremove('attribute_value', self.name)
super(Attribute, self).delete()

class Meta:
unique_together = (('name', 'shapefile'),)

表格:

class AttributeForm(ModelForm):
def __init__(self, *args, **kwargs):
super(AttributeForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance and instance.pk:
self.fields['type'].widget.attrs['disabled'] = True
self.fields['type'].required = False
self.fields['width'].widget.attrs['readonly'] = True
self.fields['precision'].widget.attrs['readonly'] = True


def clean_type(self):
if self.instance and self.instance.pk:
return self.instance.type
else:
return self.cleaned_data['type']

type = forms.ChoiceField(choices=FIELD_TYPE)

class Meta:
model = Attribute
exclude = 'shapefile'

查看:

def editFields(request, shapefile_id):
layer_selected = Shapefile.objects.get(pk=shapefile_id)
attributes_selected= Attribute.objects.filter(shapefile__pk=shapefile_id)
attributesFormset = modelformset_factory(Attribute, form=AttributeForm, extra=1, can_delete=True)
if request.POST:
formset = attributesFormset(request.POST, queryset=attributes_selected)
if formset.is_valid():
instances = formset.save(commit=False)
for instance in instances:
instance.shapefile = layer_selected
try:
instance.full_clean()
except ValidationError as e:
non_field_errors = e.message_dict[NON_FIELD_ERRORS]
print non_field_errors
formset = attributesFormset(queryset=attributes_selected)
return render_to_response("basqui/manage_layer_editFields.html", {'shapefile': layer_selected, 'formset':formset}, context_instance=RequestContext(request))
instance.save()

formset = attributesFormset(queryset=attributes_selected)
return render_to_response("basqui/manage_layer_editFields.html", {'shapefile': layer_selected, 'formset':formset}, context_instance=RequestContext(request))

最佳答案

您的方法的缺点是您已将验证从表单移至 View 。

我最近遇到了同样的问题,即验证唯一的共同约束,其中一个字段被排除在模型表单之外。我的解决方案是重写模型表单的 clean 方法,并查询数据库以检查唯一的共同约束。这会重复 full_clean 调用的代码,但我喜欢它,因为它是显式的。

我短暂地考虑过覆盖 _get_validation_exclusions这本来会更 DRY,但我决定不依赖私有(private) api。

关于python - Django - 使用 full_clean() 验证管理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20051211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com