我的博客文章模型的保存方法model.save()稱爲具有標籤多對一對多領域:Django的admin.py:save_model()不通過的ModelForm
tags = models.ManyToManyField(PostTag)
但它是不舒服的編輯和我修改我的模型是這樣的:
def _get_tagging(self): # Returns comma separated list of tags
tagging = []
for tag in self.tags.all():
tagging.append(tag.name)
return ", ".join(tagging)
def _set_tagging (self, tagging): # Saves tags from comma separated list
tagging = tagging.split(", ")
self.tags.clear()
for tag in tagging:
if len(tag) < 1:
continue
try:
self.tags.add(PostTag.objects.get(name=tag))
except ObjectDoesNotExist:
self.tags.create(name=tag)
tagging = property(_get_tagging, _set_tagging)
然後我修改了admin.py
:
class BlogAdminForm (forms.ModelForm):
tagging = forms.CharField(required=False, label="Tags", max_length=200,
widget=forms.TextInput(attrs={'class':'vTextField'}))
class Meta:
model = BlogPost
def __init__(self, *args, **kwargs):
super(BlogAdminForm, self).__init__(*args, **kwargs)
if kwargs.has_key('instance'):
instance = kwargs['instance']
self.initial['tagging'] = instance.tagging
def save(self, commit=True):
model = super(BlogAdminForm, self).save(commit=False)
model.tagging = self.cleaned_data["tagging"]
if commit:
model.save()
return model
而且這工作得很好,但只適用於編輯對象。我嘗試創建新對象時出錯。爲什麼?因爲多對多關係可以用於尚未存在於數據庫中且沒有主鍵的對象(在多對多關係之前,'BlogPost'實例需要具有主鍵值使用)。我試圖通過編輯這種保存方法來解決它:
def save(self, commit=True):
model = super(BlogAdminForm, self).save(commit=False)
try:
model.tagging = self.cleaned_data["tagging"]
except ValueError:
model.save()
model.tagging = self.cleaned_data["tagging"]
if commit:
model.save()
這解決了原來的問題。但現在model.save()
不調用save_model
方法我的管理模式:
class BlogAdmin (admin.ModelAdmin):
# ...
form = BlogAdminForm
def save_model(self, request, obj, form, change):
obj.author = request.user
obj.save()
在這個結果我得到一個新的錯誤:null value in column "author_id" violates not-null constraint.
我在做什麼錯?我可以手動調用此方法嗎?
非常感謝你這麼好的回答!也感謝風格的改進。我會在工作中考慮到他們。 – 2012-03-11 03:11:53