NakedPython
NakedPython

Reputation: 930

Django: Updating Context Value every time form is updated

I've got an UpdateView I'm using to update some data from my model, but I want to give my user only a max amount of times they can do it, after they used all their "updates" it should not be possible anymore. My view looks like this:

class TeamUpdate(UpdateView):
    model = Team
    template_name = 'team/team_update_form.html'
    context_object_name = 'team'
    form_class = TeamUpdateForm

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'max_updates': 2
        })
        return context

    def form_valid(self, form, **kwargs):
        team = form.save()
        // update context somehow so that it has the new value for max_updates?
        messages.success(self.request, f'{team} was updated')
        return redirect(team.get_absolute_url())

My Problem right now is that I don't know how I can dynamically update my context every time my form is updated. How would I do that? I assume the hardcoded "2" must be removed and I probably have to do something like 2 if not value_from_form else value_from_form but how do I get this value_from_form? And could I use this value in my a dispatch to check if its zero and then redirect my user back with a warning message like "Sorry you've used up all you're updates for this team!". Thanks to anyone who answers!

Upvotes: 0

Views: 536

Answers (1)

ruddra
ruddra

Reputation: 51998

I think there should be a field which stores number of max updates in Team model. Like this:

class Team(models.Model):
   updated = models.IntegerField(default=0)

   def save(self, *args, **kwargs):
        if self.updated:
            self.updated += 1
        else:
            self.updated = 0
        super().save(*args, **kwargs)

Finally in settings.py, have a variable MAX_UPDATES_FOR_TEAM=2. Then in context you can simply put:

def get_context_data(self):
    context = super().get_context_data()
    updated = self.object.updated
    context.update({
            'max_updates': settings.MAX_UPDATES_FOR_TEAM - updated
    })
    return context

Finally, prevent Form from updating if value of updated exceeds the MAX_UPDATES_FOR_TEAM

 class TeamForm(forms.ModelForm):
     ...
     def clean(self):
         if self.instance.updated >= settings.MAX_UPDATES_FOR_TEAM:
              raise ValidationError("Exceeded max update limit")

Upvotes: 1

Related Questions