2013-04-17 47 views
0

我正在使用CRUD管理視圖來編輯一些文本。 我重寫了我的模型的save()方法以在之前運行一些驗證。也就是說,如果輸入字符串不是格式良好的xml,則不會保存它。我想通知用戶。 然而,我只能找到需要請求對象和信息框架,但解決方案,就我而言,我無法從save()Django CRUD管理視圖:返回錯誤消息

def save(self, *args, **kwargs): 
    try: 
     from xml.dom.minidom import parseString 
     doc = parseString(self.content) 
     super(Screen, self).save(*args, **kwargs) 
    except Exception, e: 
     from django.contrib import messages 
     # messages.error(request, "This is a bad bad message") 
     print("this is a bad bad string") 
     return 

訪問request我如何發送一個錯誤信息? 點擊「保存」後,用戶會再次被重定向到該模型的實例列表。有沒有辦法將它重定向到表單?這些問題有關嗎?

回答

0

感謝@FernandoFreitasAlves我可以寫一個解決方案。 我意識到我的模型也可以從一個文件加載,然後存儲在數據庫中,沒有CRUD管理頁面,所以我也覆蓋了save()方法。我想我不想重寫full_clean()方法。我看不出有什麼理由。該文檔(https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.full_clean)說

這個方法調用Model.clean_fields(),Model.clean(),和 Model.validate_unique(),按照這個順序,並提出一個ValidationError 有一個包含錯誤的message_dict屬性從全部三個 階段。

1

我想你可以使用乾淨的方法,你的模型裏面,這樣你將驗證在管理你的數據,就像其他管理領域

內,您的Model

def clean(self): 
    try: 
     from xml.dom.minidom import parseString 
     doc = parseString(self.content) 

    except Exception, e: 
     from django import forms 
     raise forms.ValidationError(u"It's not a XML") 

    super(YourModel,self).clean() 

def full_clean(self, exclude=None): 
    return self.clean() 

參考:https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.clean_fields

+0

我剛剛嘗試在ScreenAdmin類中重寫save_model。我得到了錯誤,但因爲它不是驗證錯誤,所以它也顯示了成功的消息。我也會嘗試你的解決方案。謝謝! –