Filtering in Django html template - django

I'm passing two models into the html template
listings - has all the properties of the listed items (like on an auction site)
bids - has a listing field as a foreign key to link to listings (and the user who made a bit, plus the amount)
I'm looping through the listings items to display all their attributes of the individual listings on cards (that works nicely)
I want to display the bid that belongs to the individual listing if there is any (only the highest bid is passed on for each listing in the 'bid' queryset)
I suspect the problem is with the syntax here, but can't find a solution.
<p>{{bids.filter(listingID=listing.listingID)}}</p>
The error message:
Could not parse the remainder: '(listingID=listing.listingID)' from 'bids.filter(listingID=listing.listingID)'
This is my HTML template
{% extends "auctions/layout.html" %}
{% block body %}
<h2>Active Listings</h2>
<div></div>
{%for listing in listings%}
<div class="listingItem">
<div class="listingLeft">
</div>
<div class="listingRight">
<a href={{listing.id}}><h4>{{listing.listingName}}</h4></a>
<p>{{listing.listingDesc}}</p>
<p>Current bid: ${{listing.listingFirstBid}}</p>
<p>{{bids.filter(listingID=listing.listingID)}}</p>
<p class="created">Created: {{listing.listingCreated}}</p>
</div>
</div>
{%endfor%}
{% endblock %}

Related

How to store nav menu urls in database?

I'm working on my first django app, and i have side nav menu like in twitter. To prevent the dozens of lines in my template like this
<ul class="nav d-flex flex-column">
<li class="nav-item align-self-start rounded-pill mb-3"><li>
<li class="nav-item align-self-start rounded-pill mb-3"><li>
...
<li class="nav-item align-self-start rounded-pill mb-3"><li>
</ul>
and for app extensibility i want to store nav menu in database to be able to loop over the menu items
<ul class="nav d-flex flex-column">
{% for item in menu %}
<li class="nav-item align-self-start rounded-pill mb-3"><li>
{% endfor %}
</ul>
But the problem is that i can't store direct urls for menu items in database, because several of them have dynamic urls e.g. profile page, which has 'slug:username/' pattern.
I've tried to store template tags in database like
{% url 'app_name:view_name' %}
but of course it doesn't work.
My current idea is to store in database namespaced url e.g. 'app_name:view_name' for static urls and 'request.user.get_absolute_url()' for pages which have username in urls.
The next step is to get QuerySet with menu items from database, loop over them and transform namespaces url with reverse (it works), but 'request.user.get_absolute_url()' is just a string and it doesn't work. Then make list of ditcs and pass it to context
menu = [{item1 attrs}, {item2 attrs},...,]
Is exists a better approach to solve my problem? And finally what i should do with dynamic urls?
UPD:
If we're dealing with menu items whose urls depend only on usernames i.e. only on User model, we can do smth like this (NavigationMenu - table model, url_link - column with following values: 'app_name:view_name' or 'get_absolute_url'):
menu = NavigationMenu.object.all()
for item in menu:
url_link = item.url_link
if ':' in item.url_link:
url = reverse(url_link)
else:
method = getattr(request.user, url_link)
url = method()
# then store all instance attrs in dict
But it seems that is not a good way to solve this.
The ideal approach to achieve this is to create a base.html in which you build this sidebar nav item, and then include that base.html on every page where you want that sidebar.
This is an example of base.html
<!DOCTYPE html>
<html>
<head>
<title>My Project</title>
</head>
<body>
<header>
<ul>
<li>Home</li>
<li>News</li>
</ul>
</header>
{% block content %}{% endblock content %}
</body>
</html>
Include base.html in other Html files
{% extends "base.html" %}
{% block content %}
<h2>Content for My App</h2>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry..</p>
{% endblock content %}

How to get the information of a specific object that is retrived from a django model using for loop

I have a boostrap slider which is populating using for loop and django model objects now I want that if I click on any of the slider object then it show me the information related to that specific object which I clicked the Information must be retrived from the django model.
Thanks In Advance please help me to get out of this situation ..
Here is my code which is populating the slider. I want when I clicked on any object in the loop it should only show me the information related to that object or How can I access and display the name and description of individual product diplayed using for loop in django
{% for product in products %}
<div class="services-block-two">
<div class="inner-box">
<div class="image">
<img src="/{{ product.prd_logo }}" alt="" />
</div>
<div class="lower-content">
<h3>{{ product.prd_name }}</h3>
<div class="text">{{ product.prd_des }}</div>
Read More <span class="arrow flaticon-next"></span>
</div>
</div>
</div>
{% endfor %}
here is a image of product i want to display the name,logo and description of the product on different web page when user would click on that product

Data base saving & Redirection issue using django

I have an issue, I do not know why it is happening and how to solve it;
My app ask a user to create a project and is redirect directly to the project detail page. On that detail page if a team_id is empty I ask the user to create a team and when the team is created the user is redirected again to the project detail page to now be able to populate his team.
I used the code {% if Project.team_id == None %} when the user is redirected after creating his team but it is not working .. could you please help ? It is like before the redirection the new team is not saved in the Db ..
my html:
{% extends 'base.html' %}
{% block body %}
<div class="container">
<div class="jumbotron">
<h2>Welcome to your Project {{ project.name }} Detail page</h2>
</div>
{% if Project.team_id == None %}
<div class="invite-team">
<div class="jumbotron">
<div class="jumbo-text">
<h3>It is time to link a team to your project now create a new team and add team members</h3>
</div>
<div class="jumbo-button">
<span class="glyphicon glyphicon-plus"></span> Create a new team
</div>
</div>
{% else %}
<div class="invite-teammembers">
<div class="jumbotron">
<div class="jumbo-text">
<h3>The team {{ project.team_id }} has beed created, we now need to add TeamMembers</h3>
</div>
<div class="jumbo-button">
<span class="glyphicon glyphicon-plus"></span> Create a new team
</div>
</div>
</div>
{% endif %}
</div>
</div>
{% endblock%}
Looking at your surrounding code, you are using project as the container of your project. However, in your statement you are using Project (first character uppercase). Changing Project to project might help.
Your comment question:
what do you mean "Looking at your surrounding code, you are using project as the container of your project". my model Project is with a capital letter why now it is without ?
With looking at the surrounding code I mean that I literally looked at your code how you are using the variables in the other parts of your code. I am not sure if you are using CBV (class based views) or FBV (function based views).
With CBV the object is added to the context with the name defined in:
DetailView:81
or ListView:104
You can override the context object name by using the context_object_name in the View class
If you are using FBV, you have added it to the context manually as something like:
return render(request, 'myapp/template.html', {
'project': <project_query_or_variable>,
})

Template NoReverseMatch exceptions, outside of Models

I am generating some Django template code on the fly, in order to display rows in tables that are not stored in
a Django database and do not have models. I know the database and I can introspect them if needed, but I don't want
to write code by hand.
For example, field PSOPRDEFN.OPRCLASS stores an optional reference to a particular row where PSCLASSDEFN.OPRID=PSOPRDEFN.OPRCLASS, essentially a foreign key relationship. If there is no relationship PSOPRDEFN.OPRCLASS has one ' ' (space character) in it.
I also have a page for a given PSCLASSDEFN row, where the url is:
url(r'^(?i)permissions/(?P<CLASSID>[A-Z0-9_&]{1,50})/$',
'pssecurity.views.psclassdefn_detail',
name="psclassdefn_detail"),
Note that the ?P CLASSID regular expression does not allow for blanks which corresponds to gets stored in the PSCLASSDEFN table - I figure it's safer to limit what the user can put in the url request.
Back to my generated template: I want to hyperlink to the relation, if it exists. I feed my home-grown template generator a json "directive" indicating what I want put into the template (thanks for the inspiration, django-tables2):
....
{
"colname": "LANGUAGE_CD"
},
{
"urlname": "security:psclassdefn_detail",
"colname": "OPRCLASS",
"kwargs": [
{
"colname": "dbr",
"accessor": "dbr"
},
{
"colname": "CLASSID",
"accessor": "inst.OPRCLASS"
}
]
},
...
Some fairly trivial code generation then results in:
<div class="row">
<div class="col-xs-6 fieldlabel" title="LANGUAGE_CD" >Language Code</div>
<div class="col-xs-6 fieldvalue text-left _fv_LANGUAGE_CD">{{inst.LANGUAGE_CD}}</div>
</div>
<div class="row">
<div class="col-xs-6 fieldlabel" title="OPRCLASS" >Primary Permission List</div>
<div class="col-xs-6 fieldvalue _fv_OPRCLASS">
{% if inst.OPRCLASS|slugify %}
{{inst.OPRCLASS}}
{% endif %}
</div>
</div>
My problem is that started getting random Template url resolution errors when displaying some of the PSOPRDEFN data. I eventually tracked it down to the blank OPRCLASS fields in some rows.
In order to avoid this I first added
{% if inst.OPRCLASS %}
<a ...></a>
{% endif %}
That didn't work because the field is not empty, it is blank (and therefore doesn't match the CLASSID regex). So, this is where I read the filter docs again and found that slugify strips out blanks and non-alpha.
{% if inst.OPRCLASS | slugify %}
<a ...></a>
{% endif %}
Works, as a workaround. The problem is that CLASSID only stores alphanum, but that's not always true for other fields. I wouldn't mind introspecting the table column definition at template generation runtime to see what to do, but I need to find an appropriate way to disable url reversal, for only some rows.
Questions. Is there a better filter, such as a |strip? I suppose I could always build my own filter.
Even better, is there a tag to selectively catch NoReverseMatch' exceptions at template generation time?
{% try NoReverseMatch %}
{{inst.OPRCLASS}}
{% endtry %}
The reason I was so verbose in my description is because this is not something that can be worked around using Models. And neither can I custom-tune the template by hand. I find Django works quite well without models in most cases, but url reversing in templates can be quite brittle when a few rows of data do not match expectations. Hardening it would be very beneficial.
You can assign the result of the url tag to a variable.
{% url 'path.to.view' arg arg2 as the_url %}
{% if the_url %}
link
{% else %}
No link
{% endif %}
This syntax does not raise an exception if reversing the view fails.

Django and tabbed navigationin templates

I am building a django project which among others has a customer model. Any customer can be a foreign key to some calendar entry models or some picture models. I want to be able to get in to a customers page (e.g domain/customoer/1) and be able to navigate to the different models the customer is related with (e.g all the pictures for the customer, all the calendar entries of the customer). I am using bootstrap for the "presentation of the site. My idea was to use tabs. So I created a pil for my main template the customer.html
<ul class="nav nav-pills">
<li class="active">Personal Data</li>
<li>History</li>
<li>Analysis</li>
<li>Diagnosis</li>
<li>Treatment</li>
<li>Appointments</li>
<li>Graphics</li>
</ul>
and i was thinking of including a template for each pill
<div class="tab-content">
<div id="personal-data" class="tab-pane active ">
<div id="history" class="tab-pane">History is in the making</div>
<div id="analysis" class="tab-pane">
{% include 'customer/analysis.html' with customer=customer %}
</div>
<div id="diagnosis" class="tab-pane">Diagnosis is differential</div>
<div id="treatment" class="tab-pane">Treatment what treatment??</div>
<div id="appointments" class="tab-pane">Ap point ment</div>
<div id="graphics" class="tab-pane">Now this is going to be hard!</div>
The templates in each tab can do different things like upload pics navigate to different pages etc.
When i hit on a pill the url (domain/customer/1/) won't change (naturally) to inform me to which tab i am at the moment. So my question is how can i know in which tab i am ath the moment? I want the user to be able to do different things from different tabs (upload pics etc) and I want to be able to redirect to the specific tab after the view is called? Maybe #id could be appended to the url to specify the tab, but it doesn't happen with bootstrap.
What is the best way to deal with tabs in django? Ajax maybe? Will I not have the same problem? Any ideas or lings would be nice too
I use template inheritance for this kind of thing. It's simple and flexible. For example, you can define your main navigation in your base template like so:
...
<li {% block news %}{% endblock %}>News</li>
<li {% block features %}{% endblock %}>Features</li>
<li {% block sport %}{% endblock %}>Sport</li>
...
Then, in your base templates for each of those apps you'd have something like:
<!-- news/base_news.html -->
{% extends 'base.html' %}
...
{% block news %}class="active"{% endblock %}
...