在模型级清洁期间无法访问相关对象,为什么?

时间:2016-10-23 21:48:11

标签: django

我的view.py

  def property_new(request,pk,uri):
        unit = get_object_or_404(Unit, pk=pk)
        title = 'property'
        uri = _get_redirect_url(request, uri)
        if request.method == "POST":
            form = PropertyForm(request.POST)
            form.unit = unit
            if form.is_valid():
                properties = form.save(commit=False)
                properties.unit = unit 
                try: 
                    properties.save()
                except ValidationError:
                    messages.add_message(request, messages.ERROR, str(unit.id) + "-Failed to add Property since it already exists")
                    return redirect(uri) 

                messages.add_message(request, messages.SUCCESS, str(properties.unit) + "-SUCCESS Object created sucssefully")


                return redirect(uri)



        else:
            form = PropertyForm()
        return render(request, 'object_edit.html', {'form': form, 'title':title, 'extend': EXTEND})

我的model.py

class Property(CommonInfo):
    properties = models.CharField(max_length=140)
    is_true = models.BooleanField(default=False)
    propertytype = models.ForeignKey(Propertytype)
    unit = models.ForeignKey(Unit)
    date = models.DateTimeField(null=True, blank=True)
    followup_date = models.DateTimeField(null=True, blank=True)
    quantity = models.PositiveSmallIntegerField()


    def __str__(self):
        return self.properties

    def clean(self):
        model = self.__class__
        if  (self.unit ):
            raise ValidationError('Same property cant be assigned more then ones')



    def save(self, *args, **kwargs):
        self.full_clean()
        return super(Property, self).save(*args, **kwargs)

我尝试保存时收到错误:

  

/ unit / property / new / 7 / Property中的RelatedObjectDoesNotExist没有   单元。

我从验证触发的模型中的clean方法中收到此错误。 为什么?我在验证之前为表单分配了单位值。对于运行良好的不同模型,我有完全相同的代码。

0 个答案:

没有答案