使用 django 通用表单编辑多对多关系的对立面
我有两个模型:
class Actor(models.Model):
name = models.CharField(max_length=30, unique = True)
event = models.ManyToManyField(Event, blank=True, null=True)
class Event(models.Model):
name = models.CharField(max_length=30, unique = True)
long_description = models.TextField(blank=True, null=True)
在上一个问题中: Django 表单通过多对多字段链接 2 个模型,我创建了一个具有保存功能的 EventForm:
class EventForm(forms.ModelForm):
class Meta:
model = Event
def save(self, commit=True):
instance = forms.ModelForm.save(self)
instance.actors_set.clear()
for actor in self.cleaned_data['actors']:
instance.actors_set.add(actors)
return instance
这允许我从定义的 m2m 连接的另一端添加 m2m 链接。
现在我想编辑该条目。我一直在使用通用函数:
def generic_edit(request, modelname, object_id):
modelname = modelname.lower()
form_class = form_dict[modelname]
return update_object(request,
form_class = form_class,
object_id = object_id,
template_name = 'createdit.html'
)
但这会提取除保存到该对象的多对多选择之外的所有信息。
我想我需要做类似的事情: 编辑 M2M 的两侧在管理页面,但我还没弄清楚。
如何使用通用 update_object 编辑多对多链接的另一端?
I have two models:
class Actor(models.Model):
name = models.CharField(max_length=30, unique = True)
event = models.ManyToManyField(Event, blank=True, null=True)
class Event(models.Model):
name = models.CharField(max_length=30, unique = True)
long_description = models.TextField(blank=True, null=True)
In a previous question: Django form linking 2 models by many to many field, I created an EventForm with a save function:
class EventForm(forms.ModelForm):
class Meta:
model = Event
def save(self, commit=True):
instance = forms.ModelForm.save(self)
instance.actors_set.clear()
for actor in self.cleaned_data['actors']:
instance.actors_set.add(actors)
return instance
This allowed me to add m2m links from the other side of the defined m2m connection.
Now I want to edit the entry. I've been using a generic function:
def generic_edit(request, modelname, object_id):
modelname = modelname.lower()
form_class = form_dict[modelname]
return update_object(request,
form_class = form_class,
object_id = object_id,
template_name = 'createdit.html'
)
but this pulls in all the info except the many-to-many selections saved to this object.
I think I need to do something similar to this: Editing both sides of M2M in Admin Page, but I haven't figured it out.
How do I use the generic update_object to edit the other side of many-to-many link?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在这里找到了答案:
http://www.djangosnippets.org/snippets/1295/
I found the answer here:
http://www.djangosnippets.org/snippets/1295/