Django: How to update a model after displaying a view?

I have a view that displays a list of models. Some properties of some models need to be updated after the presentation has been visualized, that is, it is expected that the user will see the original unchanged values ​​on the first visit and updated values ​​on subsequent visits (or when the page reloads).

I thought I could achieve this with general class representations. The official documentation points to “doing extra work before or after invoking the general view” (my emphasis), but all the above examples affect the models before they are displayed.

I searched for signals, but to no avail.

The appearance of an asynchronous task is an option, but since all I need to do is update the field in several models (probably one or nothing) and save them, it seems to be too difficult for this task.

You can use the ajax request to start the update, or you can use your own template tag to display the corresponding fields and update them after that. I don't like this because they move the application logic to the presentation layer. The ajax method also adds the overhead of the second request.

But I seem to have no other choice, or am I? Is there a more practical method for connecting to a generic view or query and executing additional logic after rendering the template?

+3
source share
5 answers

. - , . .

:

def my_view(request, params):
    ... do something ...
    response = render_to_response('my_template.html', {'foo': bar'})
    ... do something after rendering ...
    return response

, , :

def my_decorator(view):
    def my_func(request, params):
        response = view(request, params)
        ... do something after rendering ...
        return response
    return my_func

@my_decorator, .

... , , ( process-response).

TemplateResponse. , - .

+7

, , .

def foo(*args):
  ret = bar(*args)
  do_something()
  return ret
0

, , ( ) ?

, .

0

Django request_finished, AFTER django, .

0

,

your_task.delay() 

You can use the countdown argument to indicate the elapsed time before starting the task.

If you do not use celery, the chances are that you will be in the future :)

0
source

All Articles