Django Template _set.all - django

I have this model:
class CustomerAddresses(models.Model):
ID = models.AutoField(primary_key=True)
...
CustomerID = models.ForeignKey('Customers', on_delete=models.CASCADE)
I render the Address Data in my Template:
% for address in customer_default_shipping_address %}
{% if address.Address_Company %}
<h5>{{ address.Address_Company }}<br/>
{{ address.Address_Firstname }} {{ address.Address_Lastname }}</h5>
{% else %}
<h5>{{ address.Address_Firstname }} {{ address.Address_Lastname }}</h5>
{% endif %}
<address class="mb-0 font-14 address-lg">
{{ address.Street}}<br>
{{ address.Zip}} {{ address.City}}<br>
{% for customer in address.customers_set.all %}
<abbr title="Telefon">P:</abbr> {{ customer.PhoneNumber }} <br/>
<abbr title="E-Mail">M:</abbr> {{ customer.Email }}
{% endfor %}
</address>
{% endfor %}
but the E-Mail and Phone Field will not be rendered, are I'm doing something wrong?

It looks like your relational model is wrong. A CustomerAddress only has one CustomerID linked to it because of the ForeignKey usage, thus you cannot look through address.customes_set.all.
Give it a go without the second nested loop and have just: address.customerID.PhoneNumber for example.

Related

many to one field self relationship

i used a self relationship inside model with foreignkey , purpose was to make a replyable comment , but idk how to use it in templates,
i mean whats different between 3 ManyToOne relationships i used in template , how can i know form send reply or comment?
model:
class Comment(models.Model):
#comments model
post = models.ForeignKey(Post,related_name='comments',on_delete=models.CASCADE)
text = models.CharField(max_length=300)
user = models.ForeignKey(get_user_model(),related_name='users',on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
parent = models.ForeignKey('self', null=True,related_name='reply',on_delete=models.SET_NULL)
class Meta():
verbose_name_plural = 'Comments'
ordering = ['date']
def __str__(self):
return self.test[:50]
template:
<div>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button value="submit">Send</button>
</form>
</div>
<div>
{% for comment in object.comments.all %}
<p>{{ comment.text }}</p>
{% for reply in object.reply.all %}
<p>{{ reply.text }}</p>
{% endfor %}
<form method='post'>
{% csrf_token %}
{{ form.as_p }}
<button value="submit">reply</button>
</form>
{% endfor %}
</div>
{% endblock %}
can you a little explain how it works?
You can consider using a recursive solution in your code using with template tag, like this:
First define a template which will render the comment:
<!-- comments.html -->
{% for comment in comments %}
<p>{{ comment.text }}</p>
<form method='post'>
{% csrf_token %}
{{ form.as_p }}
<button value="submit">reply</button>
</form>
{% if comment.reply.exists %}
<ul>
{% include "comments.html" with comments=comment.reply.all %}
</ul>
{% endif %}
{% endfor %}
Then include it in the original template:
<div>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button value="submit">Send</button>
</form>
</div>
<div>
{% include "comments.html" with comments=object.comments_only %}
</div>
Finally, only send the Comments which does not have parents,like this:
class Post(...):
...
def comments_only(self):
return self.comments.filter(parent__isnull=True)

How can I show help_text attribute through for loop in my template?

forms.py
class UserRegistratiion(forms.Form):
email = forms.EmailField()
name = forms.CharField(help_text="80 Char Maximum")
views.py
def showFormData(request):
fm = UserRegistratiion(auto_id="my_%s")
return render(request, "blog/login.html", {"form":fm})
When i use this in my template it works fine and my help_text shows in span tag..
<form action="">
<div>
{{form.as_p}}
</div>
But, whwn i use for loop
{% for field in form.visible_fields %}
<div>
{{field.label_tag}}
{{field}}
</div>
{% endfor %}
help_text doesn't show how can i get this?
try this
{% for field in form.visible_fields %}
<div>
{{ field.label_tag }}
{{ field }}
{{ field.help_text }} <!-- new -->
</div>
{% endfor %}
or
{% for field in form.visible_fields %}
<div>
{{ field.label_tag }}
{{ field }}
{% if field.name =='name' %}
{{ field.help_text }} <!-- new -->
{% endif %}
</div>
{% endfor %}

Issue assigning form fields in the HTML template django

I have a model form and I wanted to know if it is possible to take a model form and assign the name of the specific field when it is running through a for loop within the template html file.
Here is what i have in the current html template:
{% extends "base.html" %}
{% block content %}
<h1>Add members to {{record.name}}</h1>
{% if message %}
<p>{{message}}</p>
{% endif %}
<form action="." method="POST">
{% csrf_token %}
{% for trans in transactions %}
{% if trans.record.id == record.id %}
{{ trans.user.username }}
{{ form.as_p }}
{% endif %}
{% endfor %}
<p>Tax: <input type="text" name="tax" value=""></p>
<p>Tip: <input type="text" name="tip" value=""></p>
<input type="submit" name="submit" value="submit">
</form>
{% endblock %}
here is the current form model:
class IndividualSplitTransactionForm(forms.ModelForm):
class Meta:
model = Transaction
fields = ['amount', 'description']
currently the format is looking like this:
omar
amount
description
hani
amount
description
assad
amount
description
tax
tip
so when i process it and i want to grab the amount assigned to each of the specific users and update a record. I want it to look something like this for easier processing in the view.
omar
omaramount
omardescription
hani
haniamount
hanidescription
assad
assadamount
assaddescription
tax
tip
so that when i am processing I can properly assign the corrent amount and description for each user when i am updating existing records with the amount.
is it possible to do that within the template itself or would i have to do it somewhere else.
UPDATED
So i tried to change my code and update it to get what i am trying to get but this is what i am getting...
Here is the html
{% extends "base.html" %}
{% block content %}
<h1>Add members to {{record.name}}</h1>
{% if message %}
<p>{{message}}</p>
{% endif %}
<form action="." method="POST">
{% csrf_token %}
{% for trans in transactions %}
{% if trans.record.id == record.id %}
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ trans.user.username }}{{ field.label }}{{ field|safe }}
</div>
{% endfor %}
{% endif %}
{% endfor %}
<p>Tax: <input type="text" name="tax" value=""></p>
<p>Tip: <input type="text" name="tip" value=""></p>
<input type="submit" name="submit" value="submit">
</form>
{% endblock %}
and here is what I am getting.
request returs
So if you look at the image, it is still just returning the last amount and description of the three that i entered... should i just create the whole form manually in the html file....
If you wanted the username + amount or username + description, then you to change away from form.as_p, because you will get the html <p><p/> tag for each field with label preceding it.
You want to dynamically add username then do by designing your own html content of the form manually.
There is a label_suffix, but prefix is not available. Even with suffix you should be doing it at the time of creating the form object.
Update:
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ trans.user.username }} {{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}

How to insert extra content in form?

I have form:
class ItemForm(forms.ModelForm):
id = forms.ModelChoiceField(queryset=Item.objects.all(), widget=forms.HiddenInput())
temp = forms.BooleanField(widget=forms.HiddenInput(), required=False)
date = forms.SplitDateTimeField(widget=forms.SplitDateTimeWidget())
... etc
and in template i have:
{% for field in itemForm %}
{% if field.is_hidden %}
{{ field }}
{% else %}
<div class="fieldWrapper">
{% if field.errors %}<div class="errorbox">{% endif %}
<p>{{ field.label_tag }}</p>
<p>{{ field }}</p>
<p></p>
{% if field.errors %}<p>{{ field.errors }}</p></div>{% endif %}
</div>
{% endif %}
{% endfor %}
it is a universal template for different forms. And now in one form:
class DifferentForm(forms.ModelForm):
id = forms.ModelChoiceField(queryset=DifferentItem.objects.all(), widget=forms.HiddenInput())
option = forms.ModelChoiceField(queryset=Option.objects.all(), widget=forms.HiddenInput())
(????)
temp = forms.BooleanField(widget=forms.HiddenInput(), required=False)
date = forms.SplitDateTimeField(widget=forms.SplitDateTimeWidget())
... etc
i want put an additional link in such a way as to show in this way:
<select ...>
<option>...</option>
</select>
(my additional link, button, text, whatever)
<input ...
How to do it?
The way I usually do this is in the template:
{% for field in itemForm %}
{% if field.name == "option" %}
Custom stuff I want to go before this field
{% endif %}
<!-- Regular field stuff goes here -->
{% if field.is_hidden %}
{{ field }}
{% else %}
<div class="fieldWrapper">
...
</div>
{% endif %}
<!-- End Regular Field Stuff -->
{% if field.name == "option" %}
Custom stuff I want to go after the field
{% endif %}
{% if field.name == "another_field_name"%}
Custom stuff I want to go after the field
{% endif %}
{% endfor %}

Why doesn't django like my dictionary?

I'm new to django, and desperately trying to figure out why I can't get a set of dictionary objects to render. Here is a snippet of the template--with some pprints for debugging:
<ul>
{% with req.requirement_id as reqid %}
req.requirement_id: {{ req.requirement_id|pprint }}<br />
reqid: {{ reqid|pprint }}<br />
e_quals: {{ e_quals|pprint }}<br />
e_quals.reqid: {{ e_quals.reqid|pprint }}<br />
{% for qual in e_quals.reqid %}
qual.qual_type: {{ qual.qual_type }}
{% if qual.qual_type == "self" %}
<li>Only self-endorsements.</li>
{% endif %}
{% if qual.qual_type == "other" %}
<li>No self-endoresements.</li>
{% endif %}
{% if qual.qual_type == "hasa" %}
<li>Endorser must hold an active {{ qual.qual_data }} badge.</li>
{% endif %}
{% endfor %}
{% endwith %}
</ul>
And here is what I get as an output:
req.requirement_id: u'man_keephead'
reqid: u'man_keephead'
e_quals: {u'man_keephead': [<EndorsementQual: man_keephead_others>, <EndorsementQual: man_keephead_man>], u'man_trustself': [<EndorsementQual: man_trustself_self>], u'man_waiting': [<EndorsementQual: man_waiting_other>]}
e_quals.reqid: ''
I really seems like--given that reqid and that e_quals dictionary, e_quals.reqid should produce that list of objects. I'm not sure what I'm missing.
You can't do this sort of indirect variable resolution in Django's template language. It will always interpret e_quals.req_id as e_quals["req_id"] - ie as a literal key.
You'll need to create a simple template filter:
#register.filter
def dict_get(my_dict, key):
return my_dict.get(key)
{{ e_quals|dict_get:req_id }}