I need to loop through all field objects of a model in Django. Once I look through I need to detect if in any of the entries of data this specific field(type) is equal to "Date1". If it is I need it to send a variable(val) that is a string equal to "True" to the Django templates. I have everything set and it seems simple and it seems like it should work. On its own, the val can send a value to the template when it is not in an if statement and the for loop also properly works. Even when "Date1" exists as a value in the type field of an entry in the model "Field_Repo1" the val isn't sent and the if statement is never iterated through(I know this by using prints). No matter what the if statement is never run through. Code Below. Thanks in advance.
context = {}
context['Field_Repo1'] = Field_Repo1.objects.filter(user=response.user)
for type1 in Field_Repo1.objects.values_list('type'):
if type1 == "Date1":
val = "True"
context['val'] = val
print(val)
print(AHHHHHHHHHHHH)
if response.method == 'POST':
form = Field_Repo1_Form(response.POST, response.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.user = response.user
instance.save()
response.user.Field_Repo1.add(instance)
return redirect('repo1')
else:
form = Field_Repo1_Form()
context['form'] = form
return render(response, 'sheets/add_fields/repo1_add_field.html', context)
CodePudding user response:
The values_list()
function returns a queryset of tuples. The statement in your for
loop if type1 == "Date1":
is trying to compare equality between "Date1"
and a tuple, which will never be true. The tuples in the query set all are of length 1 since you only passed a single field to the values_list()
function, so you should be able to do if type1[0] == "Date1":
for your comparison.