Im currently displaying a table with values, and in case those values doesn't exist im displaying a button to introduce such values.
The problem is that i need a break in the for loop but Django doesn't support break in templates.
The current state is this:
And the html for the table is the following:
<table style="width:100%">
<tr>
<th>Num de aluno</th>
{% for quest in questionlist
<th> {{quest.question_id.q_discription}} </th>
{% endfor %}
</tr>
{% for st in students %}
<tr>
<td> {{st.student_number}} </td>
{% for qt in questionlist %}
<td>
{%for tst in studentexamitems %}
{% if qt == tst.qitem_id and st == tst.student_id %}
{{tst.qscore}}
{% endif %}
{% endfor %}
<a href="{% url 'newTableEntry' qt.id st.id %}">
<button type="button" class="btn btn-success btn-xs">
<span class="glyphicon glyphicon-plus"></span> Grade
</button>
</a>
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
So the question is how do i remove the button in case of a existing grade, and keep the button in case of not existing?
As stated on the comments, there is no break in Django template system.
You can still solve this using if ... else.
If a grade is available, show the grade; if grade is not available, show the button.
{% for tst in studentexamitems %}
{% if qt == tst.qitem_id and st == tst.student_id %}
{{tst.qscore}}
{% else %}
<a href="{% url 'newTableEntry' qt.id st.id %}">
<button type="button" class="btn btn-success btn-xs">
<span class="glyphicon glyphicon-plus"></span> Grade
</button>
</a>
{% endif %}
{% endfor %}
Related
currently I'm writing a simple todolist with django. I have a view and html file for showing the list of items, and I want a number for each task in the table starting from 1. I'm using {% footloop.counter %} for that in my template.
Everything was ok until I wrote the paginator. when you choose to go to the next page, the counter starts from 1 again ,therefor the numbers in the table in each page start from one too. but I want the numbers to be continued in order until the last page. Is there any template tags or code snippets for that?
Thanks in advance.
here are the codes involved:
**list.html:**
{% for task in tasks %}
<tbody>
<tr>
<th scope="row" class="col-md-1">{{ forloop.counter }}</th>
<td class="col-md-2">{{ task.title }}</td>
<td class="col-md-3">{{ task.description|truncatewords:10 }}</td>
<td class="col-md-2">{{ task.time|date:"H:i" }} - {{ task.time|date:"D d M , Y" }}</td>
</tr>
</tbody>
{% endfor %}
<!--Pagination-->
{% if is_paginated %}
<div class="container p-4">
<div class="pagination justify-content-center">
<span class="step-links">
{% if page_obj.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ page_obj.number }} of {{page_obj.paginator.num_pages }}
</span>
{% if page_obj.has_next %}
next
last »
{% endif %}
</span>
</div>
</div>
{% endif %}
You can try to build your own template tag and use it on the template like below :-
#register.filter
def adjust_for_counter(value, page):
value, page = int(value), int(page)
counter_value = value + ((page - 1) * settings.RESULTS_PER_PAGE)
return counter_value
and call it like below in the html :-
{{ forloop.counter|adjust_for_pagination:page }}
For more details you can refer to below link :-
https://djangosnippets.org/snippets/1391/
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
I'm Creating Small Size of Web Interface.I created the edit button in Web Interface.But ,it's not working.It Creating as a new Entry in Database.Can anyone help me.One more thing is How to retrieve the values from database while editing existing values.Thanks for advanced.
Here is The Python Code:
class UserForm(FlaskForm):
type=StringField('type')
#app.route('/newuser', methods=['GET', 'POST'])
def add_user():
form = UserForm()
if form.validate_on_submit():
user_details = {
'type': form.type.data
}
sqlsession.add(user_details)
return redirect(url_for('vehicle_type'))
return render_template('vehicletype.html', form=form)
#app.route('/control/edit/<int:id>',methods=['POST','GET'])
def edit(id):
qry=sqlsession.query(Vehicletype).filter(Vehicletype.id==id).first()
form = UserForm(request.form, object=qry)
if form.validate_on_submit():
form.populate_obj(qry)
sqlsession.update(qry)
sqlsession.commit()
return redirect(url_for('vehicle_type'))
return render_template('vehicletype.html', form=form)
Here is the Templates of the vehicletype.html Code:
{% extends "base.html" %}
{% block head %}
{{super()}}
{% endblock %}
{% block navbar %}
{{super()}}
{% endblock %}
{% block content %}
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Vehicletype > Create Vehicletype</li>
</ol>
</div><!--/.row-->
<div class="row">
<div class="col-md-6">
<form role="form" action="/post/vehicletype" method="post">
<div class="form-group">
<label>VehicleType: </label>
<input name="type" class="form-control" placeholder="enter vehicletype">
</div>
<input type="submit" class="btn btn-primary" value="Submit ">
<input type="reset" class="btn btn-default" value="Reset">
</form>
</div>
</div>
{% endblock %}
Here is the vehicletypedetails.html code:
{% extends "base.html" %}
{% block head %}
{{super()}}
{% endblock %}
{% block navbar %}
{{super()}}
{% endblock %}
{% block content %}
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Vehicletype>View</li>
</ol>
</div><!--/.row-->
<div class="row">
<div class="col-md-12">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>
Id
</th>
<th>
VehicleType
</th>
<th>
Dateofsub
</th>
<!--<th>
Control
</th>-->
<th>
Delete
</th>
</tr>
</thead>
{% for values in vehicletype %}
<tr>
<th>{{values.id}}</th>
<td>{{values.type}}</td>
<td>{{values.dateofsub}}</td>
<!--<td>Reset Password</td>-->
<td>Delete</td>
<td>edit</td>
</tr>
{% endfor %}
</table>
<em class="fa fa-xl fa-plus-circle color-blue" ></em>
</div>
</div>
{% endblock %}
I have been trying to solve this issue for 6 days .But I Could not find any solution. Please could you help me anyone.
Your code to edit an existing entry has a route of /control/edit/<int:id>, but your form you're using to submit the user-changes is pointing at a different route located at /post/vehicletype.
You'll need to change your return from:
return render_template('vehicletype.html', form=form)
to:
return render_template('vehicletype.html', form=form, car_id=id)
And then change your html code from:
<form role="form" action="/post/vehicletype" method="post">
to:
<form role="form" action="{{ url_for('edit', id=car_id) }}" method="post">
With that in place, your form code will be getting submitted to the correct route for processing.
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>
I am debugging a Django project, and want to display another field from the database in a table on the webpage.
The Django HTML for the table as it's currently displayed in the webpage is:
<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="{% cycle 'odd' 'even' %}{% if project.office == 2 %} col{% endif %}">
{% with initial_details=project.initial_details survey=project.survey %}
{# Open lightbox #}
<td>
{% 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>
<a href="#p2" class="gallery">
<div id="p2">
<iframe class="lightbox-content" src="{% url 'projects:survey' project.id %}report/" width="1200" height="800" id="p1" style="border:none;" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>
</div>
</a>
<a href="#p3" class="gallery">
<div id="p3">
<iframe class="lightbox-content" src="{% url 'projects:preconcept_notes' project.id %}report/" width="1200" height="800" id="p1" style="border:none;" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>
</div>
</a>
<a href="#p4" class="gallery">
<div id="p4">
<iframe class="lightbox-content" src="{% url 'projects:concept' project.id %}report/" width="1200" height="800" id="p1" style="border:none;" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>
</div>
</a>
<a href="#p5" class="gallery">
<div id="p5">
<iframe class="lightbox-content" src="{% url 'projects:handover' project.id %}report/" width="1200" height="800" id="p1" style="border:none;" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>
</div>
</a>
</div>
{% endif %}
{% endif %}
</td>
{# Standard columns #}
{% with project.team as team %}
<td>{{project.project_name}}</td>
<td>{{project.town|xor}}</td>
<td>{{project.postcode}}</td>
<td>{{project.client.full_name_a|xor}}</td>
{# Status-specific columns #}
{% if detailed_status == "ds1"|ds or detailed_status == "ds2"|ds %} {# New project leads #}
<td>{{project.created|date:"d/m/y"}}</td>
<td>{{initial_details.site_visit.date|date:"d/m/y"}}</td>
<td>{{initial_details.discussed_budget|money:'£'|xor}}</td>
<td> </td>
<td> </td>
{% elif detailed_status == "ds3"|ds %} {# CDI Sent #}
<td>{{project.cdi.sent|date:"d/m/y"}}</td>
<td>{{initial_details.discussed_budget_updated|money:"£"|xor}}</td>
<td> </td>
<td> </td>
<td> </td>
{% elif detailed_status == "ds4"|ds %} {# CDI Signed #}
<td>{{team|getval:'Designer'|xor}}</td>
<td>{{project.budget_overview.current_exc_vat|money:"£"|xor}}</td>
<td>{{project.survey.meeting.date|date:"d/m/y"}}</td>
<td>{% for emp in project.survey.get_surveyors %}{{emp}}, {% endfor %}</td>
<td>{{initial_details.estimated_start|date:"m/Y"}}</td>
<td> </td>
{% elif detailed_status == "ds5"|ds %} {# Survey completed #}
<td>{{team|getval:'Designer'|xor}}</td>
<td>{{project.budget_overview.updated_exc_vat|money:"£"|xor}}</td>
<td>{{initial_details.preconcept_meeting.date|date:"d/m/y"}}</td>
<td>{{initial_details.first_presentation.presentation_date|date:"d/m/y"}}</td>
<td>{{initial_details.estimated_start|date:"m/Y"}}</td>
{% elif detailed_status == "ds6"|ds %} {# Tendering/costing drawings #}
<td>{{team|getval:'Designer'|xor}}</td>
<td>{{project.budget_overview.updated_exc_vat|money:"£"|xor}}</td>
<td>{{initial_details.estimated_start|date:"m/Y"}}</td>
<td> </td>
<td> </td>
{% elif detailed_status == "ds7"|ds %} {# Post presentation #}
<td>{{team|getval:'Designer'|xor}}</td>
<td>{{project.budget_overview.updated_exc_vat|money:"£"|xor}}</td>
<td>{{project.chance}}{% if project.chance %}%{% endif %}</td>
<td>{{initial_details.last_presentation.date|date:"d/m/y"}}</td>
<td>{{initial_details.estimated_start|date:"m/Y"}}</td>
{% else %}
{# Standard-ish columns #}
<td>{{team|getval:'Architect'|xor}}</td>
<td>{{project.budget_overview.updated_exc_vat|money:"£"|xor}}</td>
<td>{{project.live_date|date:"d/m/y"}}</td>
<td>{{initial_details.desired_start|date:"d/m/y"}}</td>
<td> </td>
{% endif %}
<!--ERF(09/11/2016 # 1540) Add an 'elif' for the site manager (ds9 is the 'Live Project' table) -->
{% if detailed_status == "ds9"|ds %}
<td>{{team|getval:'Site manager'|xor}}</td>
<!--td>{{project.site_manager}}</td-->
{% endif %}
{% if user.is_staff or user.is_superuser %}
<td>
<a class="delete double-check m-l-xl" data-view-url="{% url 'projects:delete' project.id %}"><img class="icon" src="{% static "img/bin.png" %}"></a>
</td>
{% endif %}
<td data-view-url="{% url 'projects:update_detailed_status' project.id %}" style="width:10em;">
{{detailed_status_changer.visible_fields.0}}
</td>
{% endwith %}
{% endwith %}
</tr>
{% endfor %}
{% endwith %}
</table>
and this is currently showing a table with the following column headings:
Project name, Town, Postcode, Contact Name
These column heading are fields belonging to the Class Project, which is defined in the models.py file:
class Project(models.Model):
...
ds2 = 20
...
ds9 = 120
...
ds13 = 200
DETAILED_STATUS_CHOICES = (
...
ds9, 'Live project'),
...
)
# Several form fields added here, e.g.
employees = models.ManyToManyField(Employee, through=ProjectEmployee)
client = models.ForeignKey(Client, on_delete=models.SET_NULL, null=True, blank=True)
# Several 'def's here, e.g.
def team(self):
employees = self.assigned.all()
...
sm = [person for person in employees if person.role==Role.SM]
...
return{
...
'Site manager': sm[0].employee.first_name if sm else '',
...
}
# Several `#property` definitions here, e.g.
#property
def estimated_compeltion(self):
...
I want to display the Site manager field from the database in the table on the webpage- I tried adding it to the Python code as shown above, but this hasn't made a difference to what is displayed on the webpage, even though that appears to be exactly the same way that all of the other fields from the database are displayed.
What am I missing here? I would expect the Django HTML to display every field that I am telling it to in the Python code, since I am using forloops to get the fields... Why is it that I can't see the 'Site manager' field that I've added to the code in the table on the HTML web page?
In your <td/> you are using project.site_manager
It seems though that your Project model doesn't have such a field, that's why nothing is shown.
Maybe you could create a getter for project_manager in your Project class like so :
def get_site_manager(self):
sm = [person for person in self.assigned.all() if person.role==Role.SM]
return sm[0].employee.first_name if sm else ''
And use it in your template as such :
<td>{{project.get_site_manager()}}</td>