[Fixed]-Exception Value: global name 'total_max_counter' is not defined

1👍

Firstly, in get_or_create(), you need to specify the argument in the form of kwargs. Then only, it will look up an object with the given kwargs, creating one if necessary. kwargs may be empty if your model has defaults for all fields.

The function definition for get_or_create() is:

get_or_create(defaults=None, **kwargs)

Secondly, you are trying to update the survey_wizard_total field of TotalCounter object whereas your model has no such field defined in it. It has only the field total_max_counter in it. You will also need to correct that in your code.

This should work for you:

from django.db.models import F
from survey.models import TotalCounter

def done(self, form_list, **kwargs):

    total_counter = TotalCounter.objects.get_or_create(total_max_counter__gte=0)[0] 
    total_counter.total_max_counter = F('total_max_counter') + 1 # increment value of `total_max_counter` by 1
    total_counter.save() # save the object

    for form in form_list:
        form.save()

    return render(self.request, 'Return_to_AMT.html', {
        'form_data': [form.cleaned_data for form in form_list],            
    })

0👍

You are using get_or_create method in a wrong way:

total_counter = TotalCounter.objects.get_or_create(total_max_counter)

You are trying to get object from database but you are not making any comparison.
It should be something like:

total_counter = TotalCounter.objects.get_or_create(total_max_counter=<some value to match against>)

Even after this correction if your query runs, then an object for TotalCounter will be returned which have no attribute ‘survey_wizard_total

total_counter.survey_wizard_total += 1

Leave a comment