I have Django 2.0.3 on Python 3.5.3. I search for simple way to small improve my standard Django Admin dashboard (main page of Django Admin).
Here is my template for Admin main page ./templates/admin/index.html:
{% extends "admin/base_site.html" %}
{% load i18n static %}
{% block extrastyle %}{{ block.super }}
<link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}"/>{% endblock %}
{% block coltype %}colMS{% endblock %}
{% block bodyclass %}{{ block.super }} dashboard{% endblock %}
{% block breadcrumbs %}{% endblock %}
{% block content %}
<div id="content-main">
{% if app_list %}
{% for app in app_list %}
<div class="app-{{ app.app_label }} module">
<table>
<caption>
<a href="{{ app.app_url }}" class="section"
title="{% blocktrans with name=app.name %}Models in the {{ name }} application{% endblocktrans %}">{{ app.name }}</a>
</caption>
{% for model in app.models %}
<tr class="model-{{ model.object_name|lower }}">
{% if model.admin_url %}
<th scope="row">{{ model.name }}</th>
{% else %}
<th scope="row">{{ model.name }}</th>
{% endif %}
{% if model.add_url and request.user.is_superuser %}
<td>{% trans 'Add' %}</td>
{% else %}
<td> </td>
{% endif %}
{% if model.admin_url and request.user.is_superuser %}
<td>{% trans 'Change' %}</td>
{% else %}
<td> </td>
{% endif %}
</tr>
{% endfor %}
</table>
</div>
{% endfor %}
{% else %}
<p>{% trans "You don't have permission to edit anything." %}</p>
{% endif %}
</div>
{% endblock %}
I delete sidebar block, because I never use it. And it looks like:
I want to add to each model link count of objects. For example, Cities (23), Citizenships (102) and similar for all models in list. I try to add function with #property decorator in ./app/models.py, but it's not working:
class APIConfig(models.Model):
...
#property
def with_active_status(self):
return self.objects.filter(is_active=True).count()
...
I call this property in Admin template, like {{ model.with_active_status }} and it shows nothing.
This can't be a property. You don't have an instance of the model to call it on. In any case, if you did have an instance it still wouldn't work, as model managers - objects - can only be accessed from the class, not the instance.
You should make it a classmethod:
#classmethod
def with_active_status(cls):
return cls.objects.filter(is_active=True).count()
Related
I am customizing django admin template.
I can successfully remove button like (+add model) or some filter by changing overriding change_list_results.html and change_list.html
but now I want to customize each rows of the model to off the link.(I don't want to let the user go each rows editing page.)
I am checking change_list_result.html
{% load i18n static %}
{% if result_hidden_fields %}
<div class="hiddenfields">{# DIV for HTML validation #}
{% for item in result_hidden_fields %}{{ item }}{% endfor %}
</div>
{% endif %}
{% if results %}
<div class="results">
<table id="result_list">
<thead>
<tr>
{% for header in result_headers %}
<th scope="col" {{ header.class_attrib }}>
{% if header.sortable %}
{% if header.sort_priority > 0 %}
<div class="sortoptions">
<a class="sortremove" href="{{ header.url_remove }}" title="{% trans "Remove from sorting" %}"></a>
{% if num_sorted_fields > 1 %}<span class="sortpriority" title="{% blocktrans with priority_number=header.sort_priority %}Sorting priority: {{ priority_number }}{% endblocktrans %}">{{ header.sort_priority }}</span>{% endif %}
</div>
{% endif %}
{% endif %}
<div class="text">{% if header.sortable %}{{ header.text|capfirst }}{% else %}<span>{{ header.text|capfirst }}</span>{% endif %}</div>
<div class="clear"></div>
</th>{% endfor %}
</tr>
</thead>
<tbody>
{% for result in results %}
{% if result.form and result.form.non_field_errors %}
<tr><td colspan="{{ result|length }}">{{ result.form.non_field_errors }}</td></tr>
{% endif %}
<tr class="{% cycle 'row1' 'row2' %}">{% for item in result %}{{ item }}{% endfor %}</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
and found that <tr class="{% cycle 'row1' 'row2' %}">{% for item in result %}{{ item }}{% endfor %}</tr> out the each row.
However how can I customize each item ???
Thanks for your any help.
In django 1.7+, you can remove the links from the list from the admin model:
class UsersAdmin(admin.ModelAdmin):
list_display_links = None
However, know that this will only remove the link - it will not prevent from users getting into the view/edit page of each row if they can come up with the relevant url. For that, you'll also need to handle that view as well.
See some of these discussions here: https://stackoverflow.com/a/5837386/3121897
This is my code:
<!-- Loop thru Table Macro begins-->
{% macro loopThruTable(currentParent, prod)%}
<li> {{prod.category_name}} </li>
{% set currentParent = prod.id %}
{{ checkParent(currentParent) }}
<ul>
<table>
<tr>
<th>Service</th>
<th>Price</th>
</tr>
{{ checkParentService(currentParent)}}
</table>
</ul>
{% endmacro %}
<!-- Loop thru Table Macro ends-->
<!-- CheckParent Macro begin-->
{% macro checkParent(currentParent) %}
{% for prod in myProd %}
{% if prod.parent_category_id == currentParent %}
<ul>
{{ loopThruTable(currentParent, prod) }}
</ul>
{% endif %}
{% endfor %}
{% endmacro %}
<!-- checkParent Macro Ends-->
<!-- CheckParentService Macro begin-->
{% macro checkParentService(currentParent) %}
{% for serv in myServ %}
{% if serv.parent_category_id == currentParent %}
<tr>
{{ loopThruTableService(currentParent, serv.name) }}
{{ loopThruTableService(currentParent, serv.price) }}
</tr>
{% endif %}
{% endfor %}
{% endmacro %}
<!-- checkParent Macro Ends-->
<!-- Loop thru Table Macro begins-->
{% macro loopThruTableService(currentParent, blah) %}
<td>{{blah}}</td>
{% endmacro %}
<!-- Loop thru Table Macro ends-->
{% extends 'admin/master.html' %}
{% block body %}
<ul>
{% set parent = 0 %}
{{ checkParent(parent) }}
</ul>
{% endblock %}
for all intents and purposes it is running mostly correctly, but it is adding an extra table at the end of each loop.
enter image description here
as you can see in the bottom, there's a "ServicePrice" that is separating each category.
enter image description here
here's another example. I know it has to do with my loops, but as far as jinja2 is concerned, I don't know if there's a method that exists where i check if the parent just 'exists' in my object.
Thanks,
I figured it out.
I had to add one extra for loop and if statement in the loopThruTable Macro.
It now looks like this:
{% macro loopThruTable(currentParent, prod)%}
<li> {{prod.category_name}} </li>
{% set currentParent = prod.id %}
{{ checkParent(currentParent) }}
{% for serv in myServ %}
{% if serv.parent_category_id == currentParent %}
<table>
<tr>
<th>Service</th>
<th>Price</th>
</tr>
{{ checkParentService(currentParent)}}
</table>
{% endif %}
{% endfor %}
{% endmacro %}
I'm still not entirely sure why that works. But it works.
I'm using django-tables2 to render my data in tables in the template..
everything is rendered fine with pagination..
The Designer of our company wants to change the Display of data into blocks instead of simple table. the following picture may explain more.
I Want to ask if I can use Django tables2 in this case ..since I don't want to loose the pagination
Is it possible to custom the django_tables2/table.html file to only fit this case (because I'm using django-tables2 in many other pages in the project)?
Any other ideas may be helpful.
Thanks in advance :)
Yes, you can create a custom template (based on django_tables2/table.html) and set a specific table's template Meta attribute to its path:
import django_tables2 as tables
class Table(tables.Table):
# columns
class Meta:
template = 'table-blocks.html'
or use the template argument to the Table constructor:
table = Table(queryset, template='table-blocks.html')
or use the second argument of the {% render_table %} templatetag:
{% load django_tables2 %}
{% render_table queryset 'table-blocks.html' %}
I was having the same requirement and i had been able to do it. To achieve the desired results i have used bootstrap4 and modified the "django_tables2/bootstrap4.html" template. My modified template only displays blocks which can further be enhanced by embedding more css in it.
{% load django_tables2 %}
{% load i18n %}
{% block table-wrapper %}
<div class="container-fluid relative animatedParent animateOnce p-0" >
{% block table %}
{% block table.tbody %}
<div class="row no-gutters">
<div class="col-md-12">
<div class="pl-3 pr-3 my-3">
<div class="row">
{% for row in table.paginated_rows %}
{% block table.tbody.row %}
<div class="col-md-6 col-lg-3 my-3">
<div class="card r-0 no-b shadow2">
{% for column, cell in row.items %}
<div class="d-flex align-items-center justify-content-between">
<div class="card-body text-center p-5">
{% if column.localize == None %}{{ cell }}{% else %}{% if column.localize %}{{ cell|localize }}{% else %}{{ cell|unlocalize }}{% endif %}{% endif %}
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock table.tbody.row %}
{% empty %}
{% if table.empty_text %}
{% block table.tbody.empty_text %}
<tr><td colspan="{{ table.columns|length }}">{{ table.empty_text }}</td></tr>
{% endblock table.tbody.empty_text %}
{% endif %}
{% endfor %}
</div></div></div> </div>
{% endblock table.tbody %}
{% block table.tfoot %}
{% if table.has_footer %}
<tfoot {{ table.attrs.tfoot.as_html }}>
<tr>
{% for column in table.columns %}
<td {{ column.attrs.tf.as_html }}>{{ column.footer }}</td>
{% endfor %}
</tr>
</tfoot>
{% endif %}
{% endblock table.tfoot %}
{% endblock table %}
</div>
{% block pagination %}
{% if table.page and table.paginator.num_pages > 1 %}
<nav aria-label="Table navigation">
<ul class="pagination justify-content-center">
{% if table.page.has_previous %}
{% block pagination.previous %}
<li class="previous page-item">
<a href="{% querystring table.prefixed_page_field=table.page.previous_page_number %}" class="page-link">
<span aria-hidden="true">«</span>
{% trans 'previous' %}
</a>
</li>
{% endblock pagination.previous %}
{% endif %}
{% if table.page.has_previous or table.page.has_next %}
{% block pagination.range %}
{% for p in table.page|table_page_range:table.paginator %}
<li class="page-item{% if table.page.number == p %} active{% endif %}">
<a class="page-link" {% if p != '...' %}href="{% querystring table.prefixed_page_field=p %}"{% endif %}>
{{ p }}
</a>
</li>
{% endfor %}
{% endblock pagination.range %}
{% endif %}
{% if table.page.has_next %}
{% block pagination.next %}
<li class="next page-item">
<a href="{% querystring table.prefixed_page_field=table.page.next_page_number %}" class="page-link">
{% trans 'next' %}
<span aria-hidden="true">»</span>
</a>
</li>
{% endblock pagination.next %}
{% endif %}
</ul>
</nav>
{% endif %}
{% endblock pagination %}
{% endblock table-wrapper %}
I have a Django site that uses the below template to render a crispy-forms model formset. Using django-debug-toolbar, I gathered that the include tags are rendering the bootstrap4 templates many, many times. I think this is what is killing my performance (i.e. 3-4 minutes to load an inline formset with 100 forms in it)
How should I replace the include tags to avoid the duplicate rendering? Should I use extend somehow?
I can replace the include tags with the actual html from the bootstrap4 crispy-forms templates, but those templates have nested templates as well. That creates an exercising of building a master crispy-forms template that includes everything...which seems like the wrong way to go about this. In addition, I tried replace the bootstrap4/field.html include tag with the actual html, and field.html was still duplicated, and the data lost it's table structure because of the loss of with tag='td'.
{% load crispy_forms_tags %}
{% load crispy_forms_utils %}
{% load crispy_forms_field %}
{% specialspaceless %}
{% if formset_tag %}
<form {{ flat_attrs|safe }} method="{{ form_method }}" {% if formset.is_multipart %} enctype="multipart/form-data"{% endif %}>
{% endif %}
{% if formset_method|lower == 'post' and not disable_csrf %}
{% csrf_token %}
{% endif %}
<div>
{{ formset.management_form|crispy }}
</div>
<div class='table-responsive'>
<table{% if form_id %} id="{{ form_id }}_table"{% endif%} class="table table-hover table-sm" id='dispositionTable'>
<thead>
{% if formset.readonly and not formset.queryset.exists %}
{% else %}
<tr>
{% for field in formset.forms.0 %}
{% if field.label and not field|is_checkbox and not field.is_hidden %}
<th for="{{ field.auto_id }}" class="form-control-label {% if field.field.required %}requiredField{% endif %}">
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
</th>
{% endif %}
{% endfor %}
</tr>
{% endif %}
</thead>
<tbody>
{% for form in formset %}
{% if form_show_errors and not form.is_extra %}
{% include "bootstrap4/errors.html" %}
{% endif %}
<tr>
{% for field in form %}
{% include 'bootstrap4/field.html' with tag="td" form_show_labels=False %}
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% include "bootstrap4/inputs.html" %}
{% if formset_tag %}</form>{% endif %}
{% endspecialspaceless %}
I have a Django project, in which one of my views is displaying a number of tables based on information stored in the database. The view is defined as follows:
def pipeline(request):
...
tables = []
def make_table(detailed_status, projects, status_view=False, first_table=False):
...
table_context_map = {
Project.ds2: {'fields': [['date added',1], ['site visit date',1], ['initial exc VAT',1]]},
...
# Similar lines to populate the tables with data from the database
...
}
table_context = table_context_map[detailed_status]
...
table_context['fields'] = [['project name',1], ['town',1], ['postcode',1], ['contact name',1]] + table_context['fields']
table = render_to_string('.../....html', table_context)
...
return render(request, 'abc.html', context)
What I'd like to do, is at a column to each table created by this view, and insert an 'autonumber' in that column for every row in the table. The tables will be populated dynamically, based on a database query whenever the view is run and the webpage loaded, I just want to number the list of items in each table as it's created.
How would I do this? I am knew to Python Django, so any help or guidance would be much appreciated.
Edit
The part of the HTML that is currently displaying these tables in the webpage looks like this:
<div class="content">
{% block tables %}
{% for table in tables %}
{# Only shows table headers on first table (css first of type on multisection thead) #}
{{table}}
{% endfor %}
{% endblock tables %}
</div>
Edit
The HTML for the file passed into the render_to_string(...) view has the following structure:
{% load getters money_handling staticfiles utilities %}
{% if projects %}
<div class="table-container m-t-lg">
<table class="multisection pipeline left">
<tr class="sub-summary">
<th colspan="4"><h3 class="p-l-sm">{{detailed_status_str}}</h3></th>
{% if total_i %}<th>Initial exc VAT: {{total_i|money:"£"}}</th>{% endif %}
{% if total_u %}<th>Latest exc VAT: {{total_u|money:"£"}}</th>{% else %}
<th></th>
{% endif %}
</tr>
</table>
<table class="multisection pipeline left m-b-xl">
<tr class="summary">
<th style="width: 3em;"></th>
{% for field in fields %}
<th class="text-sm p-l-sm p-t-sm p-b-sm" style="width:{{widths|getval:forloop.counter0}}">
{% if field.1 %}
{% if sort == field.0 and not reverse %}
{{field.0}}
{% else %}
{{field.0}}
{% endif %}
{% else %}
{{field.0}}
{% endif %}
</th>
{# Make all have the same number of columns (8) #}
{% if forloop.last %}
{% for i in ',,,,,,,,' %}
{% if forloop.counter|add:forloop.parentloop.counter0 < 11 %}
<th> </th>
{% endif %}
{% endfor %}
{% if detailed_status == "ds4"|ds %}
<th></th>
{% endif %}
{% endif %}
{% endfor %}
</tr>
{% with user.employee.full_name|is:'Nick Ross' as summary_link %}
{% for project in projects %}
<tr data-project-id="{{project.id}}" class="even {% if project.office == 2 %} col{% endif %}">
{% with initial_details=project.initial_details survey=project.survey %}
{# Open lightbox #}
<td>
{# ERF(22/11/2016 # 1450) Add a counter to display table row numbers #}
{% if user.is_superuser %}
<a class="gallery-loader" data-project-id="{{project.id}}"><i class="icon info"></i></a>
{% if forloop.first and first_table %}
<div id="iframe_gallery_wrap">
<a href="#p1" class="gallery">
<div id="p1">
<iframe class="lightbox-content" src="{% url 'projects:description' project.id %}report/" width="1200" height="800" id="p1" style="border:none;" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>
</div>
</a>
Probaly forloop.counter is what you are looking for.
Just use it in your template like this:
<ul>
{% for data in data_list %}
<li>{{ forloop.counter }}</li>
{% endfor %}
</ul>
As for your file hope my modifications will work (marked it with your username):
{% load getters money_handling staticfiles utilities %}
{% if projects %}
<div class="table-container m-t-lg">
<table class="multisection pipeline left">
<tr class="sub-summary">
<th colspan="4"><h3 class="p-l-sm">{{detailed_status_str}}</h3></th>
{% if total_i %}<th>Initial exc VAT: {{total_i|money:"£"}}</th>{% endif %}
{% if total_u %}<th>Latest exc VAT: {{total_u|money:"£"}}</th>{% else %}
<th></th>
{% endif %}
</tr>
</table>
<table class="multisection pipeline left m-b-xl">
<tr class="summary">
<th style="width: 3em;"></th>
<th>Number</th> #someone2088
{% for field in fields %}
<th class="text-sm p-l-sm p-t-sm p-b-sm" style="width:{{widths|getval:forloop.counter0}}">
{% if field.1 %}
{% if sort == field.0 and not reverse %}
{{field.0}}
{% else %}
{{field.0}}
{% endif %}
{% else %}
{{field.0}}
{% endif %}
</th>
{# Make all have the same number of columns (8) #}
{% if forloop.last %}
{% for i in ',,,,,,,,' %}
{% if forloop.counter|add:forloop.parentloop.counter0 < 11 %}
<th> </th>
{% endif %}
{% endfor %}
{% if detailed_status == "ds4"|ds %}
<th></th>
{% endif %}
{% endif %}
{% endfor %}
</tr>
{% with user.employee.full_name|is:'Nick Ross' as summary_link %}
{% for project in projects %}
<tr data-project-id="{{project.id}}" class="even {% if project.office == 2 %} col{% endif %}">
{% with initial_details=project.initial_details survey=project.survey %}
{# Open lightbox #}
<td>{{ forloop.counter }}</td> #someone2088
<td>
{# ERF(22/11/2016 # 1450) Add a counter to display table row numbers #}
{% if user.is_superuser %}
<a class="gallery-loader" data-project-id="{{project.id}}"><i class="icon info"></i></a>
{% if forloop.first and first_table %}
<div id="iframe_gallery_wrap">
<a href="#p1" class="gallery">
<div id="p1">
<iframe class="lightbox-content" src="{% url 'projects:description' project.id %}report/" width="1200" height="800" id="p1" style="border:none;" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>
</div>
</a>