I am trying to call parent and child element of a model, I have gone through the MPTT model documentation. I did as mentioned on the documentation, but my template is failing to print children
What can be the possible cause of this problem?
Here is my Views:
def category_view(request):
category = Categories.objects.all()
brands = Brands.objects.all()
context ={
'category':category,
'brands':brands,
}
return render(request,'./ecommerce/categories.html', context)
and Here is my template HTML:
{% load mptt_tags %}
{% recursetree category%}
<div class="category-wrap mb-4">
<div class="category category-group-image br-sm">
<div class="category-content">
<h4 class="category-name">{{ node.name }}
</h4>
<ul class="category-list">
{% if not node.is_leaf_node %}
<li>{{children}}</li>
{% endif %}
</ul>
</div>
</div>
</div>
<!-- End of Category Wrap -->
{% endrecursetree %}
Parent element is printed but children element is not being printed
Doing a lot of hit and trial, generic approach solved my problem. Others having similar problem could be benefited from my answer, hence posting the solution.
Views:
category = Categories.objects.filter(parent=None)
Template:
{% for category in categories %}
<div class="category-wrap mb-4">
<div class="category category-group-image br-sm">
<div class="category-content">
<h4 class="category-name">{{ category.name }}
</h4>
<ul class="category-list">
{% for cat in category.get_children %}
<li>{{ cat.name }} </li>
{% endfor %}
</ul>
</div>
</div>
</div>
<!-- End of Category Wrap -->
{% endfor %}
Related
What I want
I'm building an approval workflow using django-viewflow and django-material.
The individual tasks are rendered as a main form with context on a very narrow column on the right-hand side.
I want to change the layout so that the task context (the detail views of all involved model instances) is better readable to the user, and also customise which fields are shown (eg. exclude a user's password hash).
Where I'm stuck
Is there a way to override which data is available as process_data short of overriding viewflow's get_model_display_data and include_process_data? E.g. I'd like to have the related instance's __str__() as title.
Does viewflow have any canonical way to provide individual detail card templates? My alternative would be to completely re-work the contents of the process_data sidebar using context['process'] as the central instance, but that would tie the templates to the data model.
Are django-material formsets with read-only fields and a custom layout the answer I'm after? (I will try this out as soon as I have a viewflow pro license.)
I'd be grateful on any pointers here.
What I've tried
I'm overriding/extending the viewflow templates. As per templatetag include_process_data, the template process_data.html supplies the column of model instance detail cards, fed by data from
get_model_display_data.
It's e.g. easy to override process_data.html to change the cards into a MaterializeCSS collapsible list:
{% load i18n viewflow material_frontend viewflow_frontend %}
<!--
This is template "APP_NAME/PROCESS_NAME/process_data.html" overriding "viewflow/flow/process_data.html".
We override instead of extending as "viewflow/flow/process_data.html" has no content block.super
Changes:
* Collapsible list of process context instead of cards.
-->
<script type="text/javascript">
$(document).ready(function () { $('.collapsible').collapsible(); });
</script>
<ul class="collapsible">
{% for root, fields, root_url in process_data %}
<li>
<div class="collapsible-header">
<span class="card-title">{{ root }} #{{ process.pk }}</span>
{% if root_url and request.user.is_staff %}
<a href="{{ root_url }}" class="card-edit" target="_blank" data-turbolinks="false" style="float:right">
{% trans 'edit' %}
</a>
{% endif %}
</div>
<div class="collapsible-body process_data_content">
<dl class="dl-horizontal">
{% for name, value in fields %}
<dt>{{ name }}:</dt>
<dd>
{% if value is True %}{% trans 'Yes' %}{% else %}
{% if value is False %}{% trans 'No' %}{% else %}
{% if value and value.url %}{{ value.name }}{% else %}
{{ value }}{% endif %}{% endif %}{% endif %}
</dd>
{% endfor %}
</dl>
</div>
{% if not hide_active_tasks and forloop.counter == 1 and process.active_tasks %}
<li>
<div class="collapsible-header">
<span class="card-title">{% trans 'Active tasks' %}</span>
</div>
<div class="collapsible-body process_data_content">
<table>
<thead>
<tr>
<th>{% trans 'Task' %}</th>
<th>{% trans 'Owner' %}</th>
</tr>
</thead>
<tbody>
{% for task in process.active_tasks %}
{% if task.flow_task.task_type == 'HUMAN' or task.flow_task.task_type == 'JOB' %}
<tr>
<td>
{{ task.flow_task}}/#{{ task.pk}}
</td>
<td>{{ task.owner|default:"" }}</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
</div>
</li>
{% endif %}
</li>
{% endfor %}
</ul>
Overriding the template viewflow/flow/task.html with my own APP_NAME/PROCESS_NAME/TASK_NAME.html template at the cost of including model-specific information can show e.g. customised cards of related instances over the main form. I would refactor the individual cards into their own templates.
{% extends "viewflow/flow/task.html" %}
{% block left-panel__top %}
<!--
This is template "APP_NAME/PROCESS_NAME/TASK_NAME.html" extending "viewflow/flow/task.html".
-->
<!-- Help specific to this step goes here. -->
{% with activation.process as p %}
<div class="row">
<h3>Nested formsets</h3>
<p>These cards are placeholders for formsets nested within the main application form.</p>
<p>Nested formsets and the main application form can be updated at the same time and have exactly one submission button.</p>
</div>
<div class="row">
<!-- Organisation Questions: Answers -->
<!-- TODO refactor to template include -->
{% for x in p.organisationanswer_set.all %}
<div class="col s12 m6 xl4">
<div class="card blue-grey darken-1">
<div class="card-content white-text">
<span class="card-title">
{{ x.question.question }}
</span>
<p><strong>Your answer:</strong> {{ oa.answer }}</p>
</div>
<div class="card-action">
Provide an answer
</div>
</div>
</div>
{% endfor %}
<!-- Dataset Questions: Answers -->
{% for x in p.datasetanswer_set.all %}
<div class="col s12 m6 xl4">
<div class="card blue-grey darken-1">
<div class="card-content white-text">
<span class="card-title">
{{ x.question.question }}
</span>
<p><strong>Your answer:</strong> {{ x.answer }}</p>
</div>
<div class="card-action">
Provide an answer
</div>
</div>
</div>
{% endfor %}
<!-- Approvals: Receipts - TODO show this in task after custodian approval -->
{% for x in p.approvalreceipt_set.all %}
<div class="col s12 m6 xl4">
<div class="card blue-grey darken-1">
<div class="card-content white-text">
<span class="card-title">
{{ x.approval }}
</span>
<p><strong>Your approval receipt:</strong> {{ x.receipt }}</p>
</div>
<div class="card-action">
Provide an answer
</div>
</div>
</div>
{% endfor %}
</div>
{% endwith %}
<div class="row">
<h3>Main application form</h3>
<p>These main application form would include the forms above as nested formsets.</p>
<p>This note will disappear once this has been implemented.</p>
</div>
{% endblock %}
For the basic cases create a template named as [app_label]/[flow_label]/process_data.html For example check the shipment demo
Viewflow is the thin workflow layer on top of the standard Django model-view-template pattern. Any customization practices for Django are valid for Viewflow
For the complex cases it's better to not to tune some universal implementation, but create your own set of templates for Viewflow, ex cookbook/custom_ui
I am following this guide:
https://www.saaspegasus.com/guides/django-stripe-integrate/#contents
I get to "Adding metadata to your Stripe objects" and am told to create a metadata.py file. It doesn't tell me where to import #dataclass and List from so I had to guess. The issue is that, moving forward from this point in the guide, the metadata does not print to my template but I can retrieve product information. I'm thinking this guide is missing or assuming I know stuff about metadata that is required to make it work.
my metadata.py:
from dataclasses import dataclass
from pip import List
from project.subscriptions import features
#dataclass
class ProductMetadata(object):
"""
Metadata for a Stripe product.
"""
stripe_id: str
name: str
features: List[str]
description: str = ''
is_default: bool = False
PREMIUM = ProductMetadata(
stripe_id='<prod id>',
name='Premium',
description='yerp',
is_default=False,
features=[
features.UNLIMITED_WIDGETS,
features.LUDICROUS_MODE,
features.PRIORITY_SUPPORT,
],
)
features.py:
UNLIMITED_WIDGETS = 'Unlimited Widgets'
LUDICROUS_MODE = 'Ludicrous Mode'
PRIORITY_SUPPORT = 'Priority Support'
views:
from django.shortcuts import render
from djstripe.models import Product
def pricing_page(request):
context = {
'products': Product.objects.all()
}
return render(request,'subscriptions/pricing_page.html', context=context)
urls:
path('pricing_page/', view=pricing_page, name='pricing_page'),
template:
{% extends "base.html" %}{% load static socialaccount %}
{% block content %}
<h1>Plans</h1>
<section>
<p class="title">Pricing Plans</p>
<div class="columns">
{% for product in products %}
<div class="column">
<p class="subtitle">{{ product.name }}</p>
{% for plan in product.plan_set.all %}
<div>
<p class="heading">{{ plan.nickname }}</p>
<p>{{ plan.human_readable_price }}</p>
</div>
{% endfor %}
</div>
{% endfor %}
</div>
</section>
<div class="plan-interval-selector">
{% for plan in plans %}
<button class="button">{{ plan.name }}</button>
{% endfor %}
</div>
<div class="columns plan-selector">
{% for product in products %}
{{ product.metadata|pprint }}
<div class="column">
<div {% if product.metadata.is_default %}class="is-selected"{% endif %}>
<span class="icon">
<i class="fa {% if product.metadata.is_default %}fa-check{% else %}fa-circle{% endif %}">
</i>
</span>
<p class="plan-name">{{ product.metadata.name }}</p>
<p class="plan-description">{{ product.metadata.description }}</p>
<div class="plan-price">
<span class="price">{{ product.metadata.monthly_price }}</span> / month
</div>
<ul class="features">
{% for feature in product.metadata.features %}
<li>
<span class="icon"><i class="fa fa-check"></i></span>
<span class="feature">{{ feature }}</span>
</li>
{% endfor %}
</ul>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
The first forloop gets attributes directly from the product and it works. The second one tries to get the attributes from the metadata. It loops for each product but does not output the metadata. Any advice?
{% for i in meal_category %}
{% for item in i.product_set.all %}
<div class="col-md-6 col-sm-6 col-xs-12 isotope-item {{ i|lower }} mb-5">
<div class="menu-list">
<span class="menu-list-product">
<img width="80" height="80" src="{{ item.image.url }}" alt="">
</span>
<h5>{{ item.name }} <span>৳ {% if item.discount %} {{ item.price|sub:item.discount }} {% else %} {{ item.price }} {%endif%}</span></h5>
<p>{{ item.description|truncatewords:6 }}</p>
</div>
</div>
{% endfor %}
{% endfor %}
Above code working nested loop(category wise product). The first loop work for the category and the second for category wise product. How to show 10 products belong a specific category?
You can try something like this taking last user product IDs in views.
last_ten_product = product.objects.filter(since=since).order_by('-product_id')[:10]
just create a method in your model and call it in template
self.product_set.all()[0:10]
I have a Class-Based ListView as shown below:
class JobByStateView(ListView):
model = State
template_name = 'jobs/jobs_by_state.html'
context_object_name = 'state_list'
ordering = ['name']
paginate_by = 15
I have added the path to urls.py file as shown below:
path('jobs/', JobByStateView.as_view(), name='job-by-state'),
And this how my template looks:
<div class="row">
<div class="col-md-4">
<ul class="list-unstyled mb-0">
{% for state in state_list %}
{% if forloop.counter|divisibleby:"5" == False %}
<li>
{{state.name}}
</li>
{% else %}
<li>
{{state.name}}
</li>
</ul>
</div>
<div class="col-md-4">
<ul class="list-unstyled mb-0">
{% endif %}
{% endfor %}
</ul>
</div>
</div>
When I try to access this templates via the url (http://localhost:8000/jobs) it works as expected and displays the data on the screen. But when I try embed this template within another template as shown below, nothing gets displayed on the web page.
{% include 'jobs/jobs_by_state.html' %}
I would like to display this template as a widget within another template.
Really appreciate, if anyone could please help me in fixing this issue.
Thank you so much in advance for your time and help!
=========================================================================
The other page template is:
{% extends 'base.html' %}
{% block page_content %}
{% include 'carousel.html' %}
{% for job in job_list %}
<div class="listing-wrapper">
<div class="listing-container border-top border-bottom">
<a href="{{ job.get_absolute_url }}">
<h2 class="heading mt-3 mb-1 mx-2 d-inline-block">{{ job.title}}</h2>
</a>
</div>
</div>
{% endfor %}
{% if is_paginated %}
<ul class="pagination justify-content-center my-4">
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link bg-dark text-white" href="?page{{page_obj.previous_page_number}}">← Previous Page</a>
</li>
{% endif %}
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link bg-dark text-white" href="?page{{page_obj.next_page_number}}">Next Page →</a>
</li>
{% endif %}
</ul>
{% endif %}
{% include 'jobs/jobs_by_state.html' with state_list=state_list %}
{% endblock page_content %}
{% block page_sidebar %}
{% include 'simple_search_widget.html' %}
<!-- Social Sharing Buttons -->
<div class="sharethis-inline-share-buttons mt-4"></div>
<!-- Newsletter Widget -->
{% include 'newsletter_widget.html' %}
{% endblock page_sidebar %}
The view for the parent template is as shown below:
class JobList(ListView):
model = Job
template_name = "jobs/job_listings.html"
context_object_name = "job_list"
ordering = ['-published_date']
paginate_by = 10
The following solution from #Charnel and #ChidG worked.
#Shahzan, ok, well you are referring to that variable in your template like this: {% include 'jobs/jobs_by_state.html' with state_list=state_list %}. So if the variable isn't in the context, it can't be passed to the included template, and so the included template won't display anything.
I am working on FAQs page where questions and answers are passed to a template sections based on their categories. I would like to reduce amount of html and use section div as a template
<div id="{{id}}">
<div class="h2">{{category}}</div>
{% for q in faqs %}
{% if q.category == '{{category}}' %}
<ul class="collapsible">
<li>
<div class="collapsible-header">{{q.question}}></div>
<div class="collapsible-body"><span>{{q.answer}}</span></div>
<div class="divider"></div>
</li>
</ul>
{% endif %}
{% endfor %}
</div>
My main html contains following code:
{% with id='m_faq'%}
{% with category='Methodology'%}
{% include 'main/faqs_section.html' %}
{% endwith %}{% endwith %}
I am only able to pass variables id and category.
Is there a way to the for loop as well?
I think the solution would be to create a list for categories in views.py
cat = [ 'Category1', 'Category2', 'Category3','Category4']
pass it to context dictionary and then put additional 'for loop' around section div.
{% for c in cat %}
<div id="">
<div class="h4">{{c}}</div>
{% for q in faqs %}
{% if c == q.category %}
<ul class="collapsible">
<li>
<div class="collapsible-header">{{q.question}}</div>
<div class="collapsible-body"><span>{{q.answer}}</span></div>
<div class="divider"></div>
</li>
</ul>
{% endif %}
{% endfor %}
</div>
{% endfor %}
That will generate a template with list of faqs divided in to sections..