amonowy amonowy - 1 year ago 123
Python Question

How to pass variable from save method to view in Django?

I need to display message with information if form was successfuly saved in database. Since there are many different forms in my website I want to write custom save method and pass variable to view every time save method was called.

I tried to use global for creating global variable when saving and then catch it in view and pass to template.

def save(self, *args, **kwargs):
global some_var
some_var = True
super(ModelName, self).save()

But this does not allow me to get some_var in view after I save model. I understand that making variables global is not best practice but could not figure out anything better.


from .forms import modForm

def func(request, passed_id):
mod_obj = ModelName.objects.get(pk=passed_id)
if request.method == 'POST':
mod_form = modForm(request.POST, instance = mod_obj)
return render(request, 'template.html')

I need to pass variable to template when form was saved. But since I have many forms writing this in views isn't DRY. Thats Why I wanted to do it in custom save()

Answer Source

The best way to do this is in the view; it is the view that is saving the object, after all, so it should know that it has done so.

However if you really want to do this in the save method, you could try just attaching an extra attribute to the model object:

def save(self, *args, **kwargs):
    self.is_saved = True
    return super(ModelName, self).save(*args, **kwargs)

Now assuming that object is the one you are passing to your template, you can simply check {% if obj.is_saved %} there.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download