How to acess form based on index django - django

I am trying to access the form based on the index value how can i do that exactly?
Ex:
{% for line in data_lines %}
{{line}}
{% with x=forloop.counter %}
{{form.x}}
{% endwith %}
{% endfor %}

As Django discourages adding too much logic hence I don't think it's possible using built-in Django Template features. You can achieve this by sending a dict instead of data_lines and accessing via key, value as:
{% for key, value in data_lines.items %}
{{value}}
{{ form.key }}
{% endfor %}
If you really want it then you could write a custom template filter.

Related

{% with %} tag to store 'in' expression value in django template

I'm trying to store a boolean value in a variable within the {% with %} tag of Django. But its not working. is there any other way around to do this ? Can I create a custom filter for it or is there any pre-built filter for this?
{% with isEnrolled=course in all_courses %}
.....
{% endwith %}

Django check form error code in template

I am using Django 1.10 and trying to find a way to check the error code of a form inside of the template. So I tried a few things, like errors.as_data or errors.as_json, but I was unable to parse the different values (except by using javascript). Could it be something like this ?
<p>{% for key, value in form.errors.items %}
{{ value }}
{% if code == 'inactive_account'%}
// do some stuff
{% endif %}
{% endfor %}
</p>
But I don't know how to get this error code. Any suggestion ?
PS : I know that a solution would be to do it inside of the view, but since I am using a django already-made one, I would prefer not to do it.
The dictionary form.errors does not contain the ValidationError instances. You need to use the as_data method.
Note that you need to loop through the list of errors for each key, and then you can check the code.
{% for key, key_errors in form.errors.as_data.items %}
{{ key }}
{% for error in key_errors %}
{% if error.code == 'inactive_account'%}
// do some stuff
{% endif %}
{% endfor %}
{% endfor %}
There's also other way to check for the error code.
You can use has_error to check for the error code.
{% form.has_error 'field_name' 'code' %}
To check for non-field errors use NON_FIELD_ERRORS as the field parameter.

django ModelChoiceField: how to iter through the instances in the template?

I am trying to get access to the instances of a ModelChoiceField to render them the way I want in a template by displaying several fields of the instances.
class MyForm(forms.Form):
mychoices = forms.ModelChoiceField(
queryset=ObjectA.objects.all(), widget=forms.RadioSelect(), empty_label=None
)
This does not work:
{% for choice in form.mychoices %}
{{ choice.pk}}
{% endfor %}
I also tried to use the queryset but it does not render anything
{% for choice in form.mychoices.queryset %}
{{ choice.pk}}
{% endfor %}
Any idea?
Thanks
{% for choice in form.mychoices.field.queryset %}
{{ choice.pk }}
{% endfor %}
Notice the extra .field. It's a bit strange the first time you come across it, but it gives you what you want. You can also access the choices attribute of that object, instead of accessing queryset directly, but you'll need to access the first element of the choice to get the PK of the instance, like this:
{% for choice in form.mychoices.field.choices %}
{{ choice.0 }}
{% endfor %}

Django template for loop. Member before

I want to create such loop:
{% for object in objects %}
{% if object.before != object %}
{{ object }} this is different
{% else %}
{{ object }} this is the same
{% endfor %}
Based on https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#for I can't. Is there really no simple way to do this? Or I just need to use counter and check for objects[counter-1]?
P.S. .before is theoretical and objects is simple query list. I want to take and do something with the loop member that encountered before current loop member.
Check ifchanged template tag
There is a "simple way" to do this: write a custom template tag. They're really not hard. This would probably do the trick (untested):
#register.simple_tag
def compare_objects(object_list):
comparisons = []
for i in range(1, len(object_list)):
if object_list[i] > object_list[i-1]:
comparisons.append('bigger')
else:
comparisons.append('smaller')
return comparisons
The built-in template tags and filters don't make it easy (as of Django 1.4), but it is possible by using the with tag to cache variables and the add, slugify, and slice filters to generate a new list with only one member.
The following example creates a new list whose sole member is the previous member of the forloop:
{% for item in list %}
{% if not forloop.first %}
{% with forloop.counter0|add:"-1" as previous %}
{% with previous|slugify|add:":"|add:previous as subset %}
{% with list|slice:subset as sublist %}
<p>Current item: {{ item }}</p>
<p>Previous item: {{ sublist.0 }}</p>
{% endwith %}
{% endwith %}
{% endwith %}
{% endif %}
{% endfor %}
This isn't an elegant solution, but the django template system has two faults that make this hack unavoidable for those who don't what to write custom tags:
Django template syntax does not allow nested curly parenthesis. Otherwise, we could do this:
{{ list.{{ forloop.counter|add:-1 }} }}
The lookup operator does not accept values stored using with (and perhaps for good reason)
{% with forloop.counter|add:-1 as index %}
{{ list.index }}
{% endwith %}
This code should work just fine as a django template, as long as object has a property or no-argument method called before, and objects is iterable (and '<' is defined).
{% for object in objects %}
{% if object.before < object %}
this is bigger
{% else %}
this is smaller
{% endfor %}

Django Newbie ManyToManyField Template Question

I have a Django model with a ManyToManyField and I'm trying to iterate the contents of that field in a comma-delimited list in my template. I'm getting some unexpected results.
{% for painting in paintings_list %}
<p>{% for item in painting.style.all %}
{{ item.style|join:', ' }}
{% endfor %}</p>
{% endfor %}
The contents are being displayed as they exist in the database, but they're displayed in an unanticipated way...ie. instead of:
Renaissance, Baroque, Expressionist
I'm getting:
R,e,n,a,i,s,s,a,n,c,e,,B,a,r,o,q,u,e,,E,x,p,r,e,s,s,i,o,n,i,s,t
Any idea what I'm doing wrong? Would have thought the join template filter was for exactly this type of scenario, but perhaps the proper way to do this would be to create a custom method of the model...
Ignacio Vasquez-Abrams is correct (as usual). A solution to your problem might lie in the forloop variables.
<p>{% for item in painting.style.all %}
{{item.style}} {% if not forloop.last %}, {% endif %}
{% endfor %}</p>
item.style is returning a string, so you're joining each character with , instead of each item.