Hello,
I want to check if a value exists in an ArrayField in an if statement in my template.
This is my template:
{% for customer in list %}
<tr>
<!-- Checking if postalcode of the vet is in his range -->
{% if customer.postalcode in postalrepresentative.postalCodes or customer.postalcode >= postalrepresentative.beginPostalRange and customer.postalcode <= postalrepresentative.endPostalRange %}
<td><a href="#" data-url="{% url 'customer_note' customer.id %}" class="customernote" data-bs-toggle="modal" data-bs-target="#dynamic-modal"><i class="las la-comment text-secondary font-16"></i></a></td>
<td>{{ customer.companyName }}</td>
{% comment %} <td>{{ customer.postalcode }}</td>
<td>{{ postalrepresentative.postalCodes }}</td> {% endcomment %}
<td>{{ customer.vetoId }}</td>
<td>{{ customer.active }}</td>
<td>{{ customer.reasonInactive }}</td>
<td>{{ customer.email }}</td>
<td>{{ customer.telephoneNumber }}</td>
<td>{{ customer.website }}</td>
<td>
<a href="#" data-url="{% url 'customer_update' customer.id %}" class="customerupdate" data-bs-toggle="modal" data-bs-target="#dynamic-modal"><i class="las la-pen text-secondary font-16"></i></a>
<a href="#" data-url="{% url 'customer_delete' customer.id %}" class="customerdelete" data-bs-toggle="modal" data-bs-target="#dynamic-modal"><i class="las la-trash-alt text-secondary font-16"></i></a>
</td>
{% endif %}
</tr>
{% endfor %}
My model:
### CONNECT REPRESENTATIVE WITH ZIP CODES/RANGES ###
class PostalRepresentative(models.Model):
postalCodes = ArrayField(models.CharField(max_length=250, default= False, blank = True, null = True), blank=True, null=True)
beginPostalRange = models.IntegerField(blank=True, null=True, default= False)
endPostalRange = models.IntegerField(blank=True, null=True, default= False)
representative = models.ForeignKey(User, on_delete=models.CASCADE, related_name="referentie_representative", blank=True, null=True)
And my view:
### CUSTOMERS ###
class CustomersView(FormMixin, ListView):
template_name = 'customers/customers_overview.html'
model = Customers
form_class = InsertCustomerForm
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'] = self.get_form()
context['postalrepresentative'] = PostalRepresentative.objects.get(representative = self.request.user)
context['list'] = Customers.objects.all()
return context
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self,form):
form = form.save(commit=False)
form.save()
# messages.success(self.request, 'User has been added correctly.')
return redirect('customers_overview')
def form_invalid(self, form):
print(form.errors)
print("Form is invalid")
return redirect('customers_overview')
How could you check if this value exists in this ArrayField of integers?
Thanks!