Django for loop to display all objects in database - python

def homepage(response):
data = Project_types.objects.all()
return render(response, 'main/homepage.html',{'projects':data})
def hacks(response):
return render(response, 'main/hacks.html', {})
def games(response):
return render(response, 'main/games.html', {})
All I need to know is how to iterate through each object in the variable "data" in html. I want it displayed in the most simple way possible !

Using the FOR template tags you can iterate through the objects in the data list ...
templatename.html:
{% for iteratorname in projects %}
<h1> {{ iteratorname.attributes }} </h1>
{% endfor %}
Please read the documentation for more details

You can use for template tag:
{% for project in projects %}
<p> {{project.attributes}} </p>
{% endfor %}

Related

Getting error 'context must be a dict rather than set.' when trying to retrieve single object where id=id in django Model

I can't make work my detail function to simply retrieve all fields of only one Model element.
my code is :
views.py
def band_detail(request, id):
band = Band.objects.get(id=id)
return render(request,
'bands/band_detail.html',
{'band', band })
in urls.py I wrote:
path('bands/<int:id>/', views.band_detail)
So, when I am going to /bands/{id} it should show me my band_details.html page :
{% extends 'listings/base.html' %}
{% block content %}
<h1> {{ band.name }} </h1>
{% if band.active %}
<h2> Active : <i class="fa-solid fa-check"></i> </h2>
{% else %}
<h2> Active : <i class="fa-solid fa-xmark"></i> </h2>
{% endif %}
{% endblock %}
but instead I get a typeError telling me : 'context must be a dict rather than set.'
error page
I guess this is due to the way I retrieve my Band object from id. But I can't wrap my mind around. That is why I am coming for a lil help.
Thanks in advance
You have a context error! because the context must be a dictionary.
def band_detail(request, id):
band = Band.objects.get(id=id)
return render(request,
'bands/band_detail.html',
context={'band': band })

Can't use Python dict in Django template tag

I checked multiple posts and solutions but can't make it happen.
I have a Python object returned within a view. I now want to use data from that dict to render it using Django template tags.
Somehow nothing shows up though...
View:
def render_Terminal(request, template="Terminal.html"):
account_information = AccountInformation.objects.all()
account_information_dict = {
'account_information': account_information
}
return render(request, template, (account_information_dict))
HTML
<div id="oneTwo" class="columnsOne">
{{ account_information.pk }}
</div>
Using just account_information within the tag, I get:
<QuerySet [<AccountInformation: AccountInformation object (30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f)>]>
Where is the issue?
AccountInformation.objects.all() is a QuerySet with a all() filter. A QuerySet is iterable, and it executes its database query the first time you iterate over it. You can show the id for all items in your list using:
{% for item in account_information %}
<div id="some-id-{{ forloop.counter }}" class="some-class">
{{ item.pk }}
</div>
{% endfor %}
Do like this
def render_Terminal(request, template="Terminal.html"):
account_information = AccountInformation.objects.all()
account_information_dict = {
'account_information': [a for a in account_information]
}
return render(request, template, (account_information_dict))
and
<div id="oneTwo" class="columnsOne">
{{ account_information.0.pk }}
</div>
however you can only recover the first item that comes
a better solution might be
account_information = AccountInformation.objects.get(pk=`you id`)
return render(request, template, (account_information_dict))
and then
<div id="oneTwo" class="columnsOne">
{{ account_information.pk }}
</div>
Using just account_information within the tag, I get:
inside the html code you have to put the item in "for" if you take the integer value
{% for a in account_information %}
<div>
{{ a.pk }}
</div>
{% endfor %}

how do i access the values in a session dynamically using django?

(Django , Python) I have created a list of book objects and it is being passed as context in my views.py along with the current session. On my template, i was to check if the books in that list are stored in the session, and if they are i want to access some info relating to that book within that session. how do i access the books in the session dynamically? is there a way?
i know i can access them by using "request.session.name" (where "name" is the same of the space in the session it is stored)
There are several book titles saved in the session, the way they are saved are as follows (in a function under views.py)
request.session["random book title"] = "random dollar price"
i want to access that "random dollar price" dynamically in a template.
this is the block of code in the template
{% for book in book_list %}
{% if book.title in request.session %}
{{ request.session.??? }}
{% endif %}
{% endfor %}
Thank you in advance!
You can make a custom template tag to look up by attribute like here
Performing a getattr() style lookup in a django template:
# app/templatetags/getattribute.py
import re
from django import template
from django.conf import settings
numeric_test = re.compile("^\d+$")
register = template.Library()
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
if hasattr(value, str(arg)):
return getattr(value, arg)
elif hasattr(value, 'has_key') and value.has_key(arg):
return value[arg]
elif numeric_test.match(str(arg)) and len(value) > int(arg):
return value[int(arg)]
else:
return settings.TEMPLATE_STRING_IF_INVALID
register.filter('getattribute', getattribute)
Now change your template to
{% load getattribute %}
{% for book in book_list %}
{% if book.title in request.session %}
{{ request.session|getattribute:book.title }}
{% endif %}
{% endfor %}
This is a basic custom template tag example:
Django - Simple custom template tag example
and docs:
https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/
From what I remember from my django days should work
You can put session data in a dictionary and send this data to target template when you want to render it in view function.
def some_function(request):
context={
'data':sessionData #put session data here
}
return render(request,"pass/to/template.html",context)
Now you can access 'data' in your template.html
I think you should just send a list of book names from your view instead of a queryset so when you are crosschecking with session you use the title directly instead.
{% for book in book_list %}
{% if book in request.session %}
{{ request.session.book }}
{% endif %}
{% endfor %}

Django - Template with 'if x in list' not working

I have a Django template that looks something like this:
{% if thing in ['foo', 'bar'] %}
Some HTML here
{% else %}
Some other HTML
{% endif %}
The problem is it comes back empty. If I switch to this:
{% if thing == 'foo' or thing == 'bar' %}
Some HTML here
{% else %}
Some other HTML
{% endif %}
it works fine. Is there some reason you can't use x in list in Django templates?
You can. But you can't use a list literal in templates. Either generate the list in the view, or avoid using if ... in ....
I got it working with the help of this answer. We could use split to generate a list inside the template itself. My final code is as follows (I want to exclude both "user" and "id")
{% with 'user id' as list %}
{% for n, f, v in contract|get_fields %}
{% if n not in list.split %}
<tr>
<td>{{f}}</td>
<td>{{v}}</td>
</tr>
{% endif %}
{% endfor %}
{% endwith %}
Send the list from the context data in the view.
Views.py:
class MyAwesomeView(View):
...
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['list'] = ('foo', 'bar')
...
return context
MyTemplate.html:
{% if thing in list %}
Some HTML here
{% else %}
Some other HTML
{% endif %}
Tested on Django version 3.2.3.
There is a possibility to achieve that also by creating a custom filter:
Python function in your_tags.py:
from django import template
register = template.Library()
#register.filter(name='is_in_list')
def is_in_list(value, given_list):
return True if value in given_list else False
and passing your list to html django template:
{% load your_tags %}
{% if thing|is_in_list:your_list %}
Some HTML here
{% else %}
Some other HTML
{% endif %}
or without passing any list - by creating a string containing your list's values (with a filter you still can't use list literal), e.g.:
{% load your_tags %}
{% if thing|is_in_list:'foo, bar' %}
Some HTML here
{% else %}
Some other HTML
{% endif %}
[TIP] Remember not to insert space after :.

search form with django+python

I have just started to do a website with django + python and I want to implement a search form to be able to search on all my database objects. What I want is; when I write for an example S I want the search field to display all my objects that starts with the letter S in a list, just like the Tags field below on this site.
Does anyone have a good ide to implement this with django?
For a decent django search implementation, I would recommend looking at djapian. However, for what you are doing, I would recommend a query using the ISTARTSWITH parameter. Consider the following:
views.py
def search(req):
if req.GET:
search_term = req.GET['term']
results = ModelToSearch.objects.filter(field__istartswith=search_term)
return render_to_response('search.html', {'results': results})
return render_to_response('search.html', {})
search.html
<html>
<body>
<form>
<input name='S'>
</form>
{% if results %}
Found the following items:
<ol>
{% for result in results %}
<li>{{result}}</li>
{% endfor %}
</ol>
{% endif %}
</body>
</html>

Categories

Resources