[Answer]-Reusing an object from a context after submitting a form

0👍

This is not related to django. It’s how the web works. HTTP is stateless.
When you generate the page, you’ve finished with that task.
The model instance is destroyed.

When the user submits the form or sends the modifications in any other way, a new connection starts with a new request and a new context.
At this point you need to re-instance the object to modify.
Depends on the application and the model itself.
You can pass the unique_id of the object, if it has one, and get it back in your actual context querying for it.

1👍

You cannot pass a model (or any Python object) directly to another page. There are workarounds (sessions, serializers) but in most cases these are not necessary.

In your case it’s not necessary or even recommended to pass the actual Python object. Django supplies many features and options for form handling. You may want to take a particular look at ModelForms, a nice feature to easily create forms that allow you to directly edit your models.

👤knbk

0👍

The context you’re referring to is just what django uses to render the template. The objects in the context are not passed across in the HTML response/request, they are just used to generate the content for the HTML template you specify, which is then passed to the http response as static data.

To do what I believe you are trying to do, you generally pass across the ID of the model instance you are trying to access to the url of the page you are loading, so on the template of the page you passed the model instance context to, you would have:

<a href="{% url 'name_of_next_url' model_instance.id %}">Link to model-specific page</a>

and the url for the instance page you are trying to reach would be

url(r'^next_url/(?P<model_instance_id>\d+)/$', 'views.next_url_view', name='name_of_next_url')

the view:

def next_url_view(model_instance_id):
    model = Model.objects.get(pk=model_instance_id)
    ...

so now you have access to the model instance in the subsequent view.

As others have mentioned, there are already generic/class-based views that can handle most things like this, but it’s good to know the background first.

Leave a comment