0

For GET form_page.html,
my view has a specific my_id to instantiate a form.
(ie, when a user first sees this form_page, an instance is already created for him,
and he's actually modifying it for the first time)

form = MyForm(instance=MyClass.objects.get(pk=my_id))

For POST form_page.html,
I'd like to update the same instance using the same my_id.

I guess I could have a separate hidden field for this my_id and get it when user POST the form.
But this seems not as easy as I expected.

How/where should I embed this my_id so that I can use it to update the same instance?

1 Answer 1

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, })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.