我有一个复制模型实例的视图。它设置new_event.pk = None,然后呈现一个表单供用户取消,更改内容并保存。
然而,M2M字段在表单中是空白的,我希望它们预先填充与原始模型实例相同的值。
views.py
def event_copy(request, id=None):
new_event = get_object_or_404(Event, id=id)
new_event.pk = None # autogen a new primary key
form = EventForm(request.POST or None, instance=new_event)
if form.is_valid():
event = form.save()
messages.success(request, "New event created")
return HttpResponseRedirect(event.get_absolute_url())
context = {
"form": form,
}
return render(request, "events/event_form.html", context)
正在复制的事件模型有两个M2M字段,这些字段在表单中都是空白的:
models.py
class Event(models.Model):
title = models.CharField(max_length=120)
...
blocks = models.ManyToManyField(Block)
facilitators = models.ManyToManyField(User)
如何预填充这些ManyToManyFields?
答案 0 :(得分:0)
我解决了问题thanks to this question。
在设置pk = None
之前,我需要从原始版本获取M2M字段:
blocks = new_event.blocks.all() # M2M
facilitators = new_event.facilitators.all() #M2M
然后将这些在dict中传递给initial
参数:
form = EventForm(request.POST or None,
instance=new_event,
initial={'blocks': blocks, 'facilitators': facilitators,})