python – Django不调用model clean方法

前端之家收集整理的这篇文章主要介绍了python – Django不调用model clean方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个视图,它从CSV文件创建模型.我已经将clean方法添加到模型类定义中,但是在创建模型时不会调用它.

以下是models.py的示例:

class Run(models.Model):
    name = models.CharField(max_length=120)
    tested_build = models.ForeignKey('apps.Build')
    timestamp_start = models.DateTimeField()
    timestamp_end = models.DateTimeField()

class CommonMeasurement(models.Model):
    timestamp = models.DateTimeField()
    value = models.FloatField()
    run = models.ForeignKey(Run)

    def clean(self):
        super(CommonMeasurement,self).clean()
        print 'here we go'
        if self.timestamp < self.run.timestamp_start or self.timestamp > self.run.timestamp_end:
            raise django_excetions.ValidationError('Measurement is outside the run')


class ClientMeasurement(CommonMeasurement):
    metric = models.ForeignKey(ClientMetric)
    account = models.CharField(max_length=120,blank=True)

这是我的表单视图代码示例:

class BaseMeasurementsUpload(generic_views.FormView):
    template_name = 'upload.html'
    models_to_upload = None   

    def get_success_url(self):
        return self.request.get_full_path()

    def form_valid(self,form):
        uploader = getattr(importers,form.cleaned_data['uploader'])
        try:
            the_uploader = uploader(form.cleaned_data,self.models_to_upload)
            upload_results = the_uploader.get_result_info()
        except django_exceptions.ValidationError as e:
            custom_errors = e
        return render_to_response(self.template_name,{'upload_results': upload_results,'custom_errors': custom_errors},context_instance=RequestContext(self.request))


class ClientMeasurementsUploadView(BaseMeasurementsUpload):
    form_class = forms.ClientMeasurementsUploadForm
    models_to_upload = models.ClientMeasurement

    def get_form(self,form_class):
        uploaders = (('MeasurementsSimpleCsv',importers.MeasurementsSimpleCsv.__doc__),('ClientMeasurementsBulkCsv',importers.ClientMeasurementsBulkCsv.__doc__,))
        if self.request.POST:
            # get bound form
            return self.form_class(uploaders,self.request.POST,self.request.FILES)
        else:
            return forms.ClientMeasurementsUploadForm(uploaders)

进口商为每个型号执行实际验证和调用create方法.

解决方法

调用模型clean方法,我们将重写save方法.检查链接https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.clean
class CommonMeasurement(models.Model):
    timestamp = models.DateTimeField()
    value = models.FloatField()
    run = models.ForeignKey(Run)

    def clean(self):
        if self.timestamp < self.run.timestamp_start or self.timestamp > self.run.timestamp_end:
            raise django_excetions.ValidationError('Measurement is outside the run')

    def save(self,*args,**kwargs):
        self.full_clean()
        return super(CommonMeasurement,self).save(*args,**kwargs)
原文链接:https://www.f2er.com/python/185970.html

猜你在找的Python相关文章