使用many2many字段复制模型实例而不保存

时间:2016-12-22 03:41:44

标签: python django django-models django-forms django-orm

我有一个复制模型实例的视图。它设置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?

1 个答案:

答案 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,})