本文介绍了Django不调用model clean方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图,它从CSV文件创建模型。我已经在模型类定义中添加了干净的方法,但是在创建模型时不会调用。



这里是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):
时间戳= models.DateTimeField()
value = models.FloatField()
run = models.ForeignKey(运行)

def clean(self):
super CommonMeasurement,self).clean()
print'here we go'
if self.timestamp< self.run.timestamp_start或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 ()
除了django_exceptions.ValidationError为e:
custom_errors = e
返回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__,))
如果self.request.POST:
#get bound form
return self.form_class(uploaders,
self.request.POST,
self.request.FILES)
else:
返回form.ClientMeasurementsUploadForm(上传者)

进口商为每个模型执行实际的验证和调用create方法。 p>

解决方案

我找到了解决方法来覆盖方法:

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

对象= models.Manager()
analyze = managers.MeasureStatManager()

def save(self,** kwargs):
self.clean ()
返回超级(CommonMeasurement,self).save(** kwargs)

def clean(self):
super(CommonMeasurement,self).clean()
print'here we go'
if self.timestamp< self.run.timestamp_start或self.timestamp> self.run.timestamp_end:
raise django_excetions.ValidationError('测量超出运行')

但我不知道这可以是一个很好的决定。


I have a view, which creates models from CSV file. I've added clean method to the model class definition, but it isn't called when model is created.

Here is example of 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)

Here is my Form View code examples:

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)

importers perform actual validation and call create method for each model.

解决方案

I've found a solution to override method:

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

    objects = models.Manager()
    analyzes = managers.MeasureStatManager()

    def save(self, **kwargs):
        self.clean()
        return super(CommonMeasurement, self).save(**kwargs)

    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')

But I'm not sure that it can be a good decision.

这篇关于Django不调用model clean方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:39