[Answer]-Django using specific instance for ModelForm object

1👍

Usually I keep the id in the url

url(r'^(?P<id>[\d]+)/edit/$', "edit"),


def edit(request, id=None, **kwargs):
    if id:
        instance = get_object_or_404(Model, pk=id)
    else:
        instance = Model()
    form = ModelForm(request.POST or None, request.FILES or None, instance=instance)

    if request.method == 'POST' and form.is_valid():
        instance = form.save()
        return redirect(instance)

    return TemplateResponse(request, 'edit.html', {'form': form, })

Leave a comment