【问题标题】:Copying a model instance with many2many fields without saving [duplicate]复制具有many2many字段的模型实例而不保存[重复]
【发布时间】:2017-05-07 14:59:37
【问题描述】:

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

正在复制的 Event 模型有两个 M2M 字段,并且这些字段在表单中都是空白的:

models.py

class Event(models.Model):

    title = models.CharField(max_length=120)
    ...
    blocks = models.ManyToManyField(Block)
    facilitators = models.ManyToManyField(User)

如何预填充这些 ManyToManyFields?

【问题讨论】:

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


    【解决方案1】:

    我解决了thanks to this question的问题。

    在设置pk = None之前,我需要从原始获取M2M字段:

    blocks = new_event.blocks.all() # M2M
    facilitators = new_event.facilitators.all() #M2M
    

    然后将这些在字典中传递给initial 参数:

    form = EventForm(request.POST or None, 
                     instance=new_event, 
                     initial={'blocks': blocks, 'facilitators': facilitators,})
    

    【讨论】:

      猜你喜欢
      • 2011-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 2014-01-11
      相关资源
      最近更新 更多