2016-11-02 39 views
0

我有一個讓我抓狂的問題RelatedObjectDoesNotExist

我有模型

class Property1(CommonInfo): 
    unit = models.ForeignKey(Unit) 
    is_true = models.BooleanField(default=False) 
    propertytype = models.ForeignKey(Propertytype, related_name='propertytype') 
    date = models.DateTimeField(null=True, blank=True) 
    followup_date = models.DateTimeField(null=True, blank=True) 
    quantity = models.PositiveSmallIntegerField() 


    def __str__(self): 
     return self.propertytype 

    def clean(self): 
     model = self.__class__ 
     if (self.unit) and model.objects.filter(unit=self.unit, propertytype=self.propertytype).exclude(id=self.id).count() == 1: 
      raise ValidationError('Same property cant be assigned more then ones') 

這個模型我有形式

class Property1Form(forms.ModelForm): 

    class Meta: 
     model = Property1 
     fields = ['unit','propertytype','is_true','date','followup_date','quantity','description'] 

    def __init__(self, *args, **kwargs): 
     super(Property1Form, self).__init__(*args, **kwargs) 
     instance = getattr(self, 'instance', None) 
     if instance: 
      self.fields['unit'].required = False 
      self.fields['unit'].widget.attrs['disabled'] = 'disabled' 

而且我有一個觀點

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 = Property1Form(request.POST) 
     form.unit = unit 


     if form.is_valid(): 
      properties = form.save(commit=False) 
      properties.unit = unit 

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

      return redirect(uri) 
    else: 
     form = Property1Form(initial={'unit': unit}) 


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

How在創建新房產後,我總是得到

RelatedObjectDoesNotExist at *** Property1 has no unit。的

if form.is_valid(): 

有什麼問題在執行過程中引發

錯誤?

UPDATE:

回溯:

File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django\core\handlers\base.py" in get_response 
    132.      response = wrapped_callback(request, *callback_args, **callback_kwargs) 
File "C:\Users\Boris\dev\rentout\rentout\unit\views.py" in property_new 
    390.   if form.is_valid(): 
File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django\forms\forms.py" in is_valid 
    184.   return self.is_bound and not self.errors 
File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django\forms\forms.py" in errors 
    176.    self.full_clean() 
File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django\forms\forms.py" in full_clean 
    394.   self._post_clean() 
File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django\forms\models.py" in _post_clean 
    430.    self.instance.full_clean(exclude=exclude, validate_unique=False) 
File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django\db\models\base.py" in full_clean 
    1132.    self.clean() 
File "C:\Users\Boris\dev\rentout\rentout\unit\models.py" in clean 
    117.   if (self.unit) and model.objects.filter(unit=self.unit, propertytype=self.propertytype).exclude(id=self.id).count() == 1: 
File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django\db\models\fields\related.py" in __get__ 
    608.     "%s has no %s." % (self.field.model.__name__, self.field.name) 

Exception Type: RelatedObjectDoesNotExist at /unit/property/new/6/http://127.0.0.1:8000/unit/property_details/6/ 
Exception Value: Property1 has no unit. 
+1

form.unit =單元沒有做你想做的事。 嘗試將此值分配給對象。而不是形式。 – Zartch

+0

請顯示完整的回溯。 – Alasdair

+1

嘗試將'if(self.unit)'改爲'if self.unit_id'。 – Alasdair

回答

1

設置required=False和禁用插件並不理想。禁用小部件意味着您的瀏覽器不會爲該字段提交任何值。由於您有required=False,這意味着表單將設置外鍵爲None。但是,這與模型的外鍵不兼容,默認情況下外鍵爲null=False

我對內部不夠熟悉,無法精確解釋異常,但基本問題是Django試圖從數據庫中取回相關的unit,表單將外鍵設置爲None

一個解決辦法是檢查self.unit_id而不是self.unit。這可以防止數據庫查找,所以你不會得到異常。

但是,這對我來說似乎有點骯髒。如果您不希望用戶編輯unit字段,我會將其從表單中完全刪除。檢查self.instance.pk以確定實例是否已在數據庫中。

def __init__(self, *args, **kwargs): 
    super(Property1Form, self).__init__(*args, **kwargs) 
    if self.instance.pk: 
     del self.fields['unit'] 

然後在您看來,您不應該再設置properties.unit = unit。我也會刪除form.unit = unit,我不認爲它有用。