Copying a model instance with many2many fields without saving

450 Views Asked by At

I have a view that copies a model instance. It sets new_event.pk=None and then renders a form for the user to cancel, change stuff, and save.

However the M2M fields are blank in the form, and I'd like them to be prepopulated with the same values as the original model instance.

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)

The Event model that is being copied has two M2M fields, and these are both blank in the form:

models.py

class Event(models.Model):

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

How do I prepopulate these ManyToManyFields?

1

There are 1 best solutions below

0
On

I solved the problem thanks to this question.

BEFORE setting pk = None, I needed to get M2M fields from the original:

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

Then pass these in a dict to initial parameter:

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