Flask-SQLalchemy pagination error, Could not build url for endpoint - python

I am trying to implement pagination with Flask-SQLAlchemy
Here is what I have done for my route
#app.route('/client/<int:page_num>',methods=['POST','GET'])
def client(page_num=None):
form = ClientForm(request.form)
if current_user.is_active ==True:
if current_user.user_role == "super_admin":
if form.validate_on_submit():
message=addOrUpdateClient(form, current_user)
return jsonify(json.dumps(message))
if (page_num):
clients = Client.query.paginate(per_page=5, page=page_num, error_out=True)
else:
clients = Client.query.paginate(per_page=5, page=1, error_out=True)
return render_template('client.html/', user=current_user,form = form,clients= clients)
else:
next_page = url_for('login')
return redirect(next_page)
And my template file is
{% if clients %}
<h4>All client</h4>
<div class="table-responsive">
<table class="table table-striped" id="client_table">
<thead>
<tr>
<th>Client Name</th>
<th>Client Short Name</th>
</tr>
</thead>
<tbody>
{% for client in clients.items %}
<tr>
<td>{{client.client_name}}</td>
<td>{{client.client_code}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% for client in clients.iter_pages(left_edge=3, right_edge=3, left_current=3, right_current=3) %}
{% if page %}
{{page}}
{% else %}
{% endif %}
{% endfor %}
{% endif %}
But when I tried to load I get the following error
Could not build url for endpoint 'client'. Did you forget to specify values ['page_num']?
Before adding this pagination , my code were working fine . One more thing to be noted here , is that I didn't even hit '/client' route . I got this error in index page http://localhost:5000/
Edit:
It seems , there is a problem in my html template , although I am still not sure
I was building url for navigation in my html template like following
<li class="nav-item">
<a class="nav-link" href="{{ url_for('client') }}">
<i class="ti-shield menu-icon"></i>
<span class="menu-title">Client</span>
</a>
</li>
And the IDE is pointing error at this line.

Related

For loop returning iterations of same result from OMDB API

I have been scouring the internet for the answer to this and I am at the point where I feel like I am probably missing something glaringly in my face.
I am attempting to request search results from the omdb api (https://www.omdbapi.com/). I have create countless iterations of the screenshots below, but here is where I am at right now with my code.
Essentially, I am able to see the movie title and year for only the first search result, and I cannot figure out how to loop through each result and display on my webpage. Any help is appreciated.
Code below:
(python code)[https://i.stack.imgur.com/6xVsL.png]
(html)[https://i.stack.imgur.com/crWk7.png]
(terminal)[https://i.stack.imgur.com/wq65p.jpg]
(webpage result)[https://i.stack.imgur.com/sLNdF.png]
Copy/Pasted Code:
app.py:
#app.route('/movies/search_results', methods=['GET'])
def show_search_results():
"""Logic for sending an API request and displaying the JSON response as an HTML. Expects a GET request."""
movies = []
s = request.args.get("search")
results = requests.get(f"{API_BASE_URL}search/movies/",params={"s": s}).json()
results = results['Search']
for movie in results:
movies.append(movie)
return render_template('movies/search_results.html', movies=movies)
#app.route('/movies/detail')
def show_movie_details():
"""For displaying information about the individual movie. Not a list. GET request only."""
movie = requests.get(f'{API_BASE_URL}', params={"i":id})
print(movie)
return render_template('movies/detail.html', movie=movie)
search_results.html:
{% block title %} {% endblock %}
{% block nav1 %} active {% endblock %}
{% block content %}
<div class="container-fluid" id="movie-list">
<div class="row row-cols-2 justify-content-center mt-2" style="--bs-gutter-x:0; ">
<p> Search Results for "{{s}}"</p>
<table>
<thead>
<tr>
<th>IMDB ID</th>
<th>Movie Title</th>
<th>Year Released</th>
</tr>
</thead>
<tbody>
{% for movie in movies %}
<tr>
<td>
<a href="/movies/detail" id="id">
{{ movie['imdbID'] }}
</a>
</td>
<td>
{{ movie['Title'] }}
</td>
<td>
{{ movie['Year'] }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}
{% block footer %} {% endblock %}
{% extends 'base.html' %}
{% block content %}
<div class="card mb-3">
<div class="card-body">
<h5 class="card-title">Title: {{ movie['Title'] }}</h5>
<p>
<span class="text-info">Description: </span>
</p>
<div><h5 class="card-title text-success">Playlists with this movie:</h5></div>
<p class="card-text"></p>
</div>
</div>
{% endblock %}
I did try creating an empty variable, and then assigning the results of my for loop to that variable as an iterable, but I ran into the same problem there too.
Try not using the 'page' key in the params dict you are passing in the api request, then you should get all the results.
Also as mentioned in #Barmar comment you are returning your results inside the loop, you should move the return statement one tab to the left.

django foorloop counter restarts in a new page

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/

how to prevent data from being repeated in the template even though the context is being nested

I am trying to implement an upvote and downvote functionality in my website. I am getting the data in two's and i think this reason is because the suppliers_votes_count is being nested in the suppliers data cominf from the view. How can I avoid this please.
This is an image that shows the template
And a proof for this is that if i print the result outside of the loop, it works normally.
To understand the question better, check the view-supplier.html, you will t=see this {% for vote in suppliers_votes_count %} being nested in this {% for supplier in suppliers %}. I think this is what causes that.
views.py
def Viewsupplier(request):
title = "All Suppliers"
suppliers = User.objects.filter(user_type__is_supplier=True)
# Get the updated count:
suppliers_votes_count = {}
for supplier in suppliers:
upvote_count = supplier.upvotes
downvote_count = supplier.downvotes
supplier_count = {supplier: {'upvote': upvote_count, 'downvote': downvote_count } }
suppliers_votes_count.update(supplier_count)
context = {"suppliers":suppliers, "title":title, "suppliers_votes_count": suppliers_votes_count}
return render(request, 'core/view-suppliers.html', context)
view-suppliers.html
<table class="table table-borderless table-data3">
<thead>
<tr>
<th>No</th>
<th>Email</th>
<th>Votes</th>
</tr>
</thead>
<tbody>
{% for supplier in suppliers %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{supplier.email}}</td>
<td>
<div class="table-data-feature">
<a href="{% url 'upvote' supplier.id %}" class="m-r-10">
<button class="item" data-toggle="tooltip" data-placement="top" title="Like">
<i class="zmdi zmdi-thumb-up">
{% for vote in suppliers_votes_count %}
{{vote.upvotes}}
{% endfor %}
</i></button>
</a>
<a href="{% url 'downvote' supplier.id %}">
<button class="item" data-toggle="tooltip" data-placement="top" title="Dislike">
<i class="zmdi zmdi-thumb-down">
{% for vote in suppliers_votes_count %}
{{vote.downvotes}}
{% endfor %}
</i></button>
</a>
</div>
</td>
</tr>
{% empty %}
<tr><td class="text-center p-5" colspan="7"><h4>No supplier available</h4></td></tr>
{% endfor %}
</tbody>
</table>
I was going to offer to combine supplier data and vote counts onto one object and avoid nested loops in the template but then realized that since you can do this in the view
upvote_count = supplier.upvotes
downvote_count = supplier.downvotes
there is no reason to build, pass and process separately suppliers_votes_count
so in the template instead of this
{% for vote in suppliers_votes_count %}
{{vote.upvotes}}
{% endfor %}
use this
supplier.upvotes
similar to downvotes

Django- call to is_valid() appears to cause MultiValueDictKeyError

When trying to upload an image file to a form on one of my Django webpages, I can select the image by clicking 'Choose File' and selecting the file in the Dialog box that is displayed.
However, when I then click the 'Upload' button, to upload the image to the project via the form, I get an error page which says:
MultiValueDictKeyError at /projects/6215/upload-budget-pdf/
The 'Traceback' on the error page shows that the error is happening in the view:
def upload_budget_pdfs(request, project_id):
project = Project.objects.get(id=project_id)
# budget_formset = BudgetUploadFormset(request.POST, request.FILES)
drawing_formset = DrawingUploadFormset(request.POST, request.FILES, prefix="drawings")
if drawing_formset.is_valid():
print 'Saving drawing_formset'
print "Before", [b.id for b in project.budget_versions.all()]
for drawing_form in drawing_formset:
if drawing_form.instance.budget:
print 'Instance', drawing_form.instance.budget
drawing = drawing_form.save(commit=False)
drawing.budget = drawing_form.instance.budget
drawing.save()
print drawing, [b.id for b in project.budget_versions.all()]
else: print 'Drawing formset not valid.',drawing_formset.errors
budget_formset = BudgetPresentationFormset(request.POST, request.FILES, instance=project, prefix="presentations")
if budget_formset.is_valid() and budget_formset.has_changed():
updated_budget_presentations = budget_formset.save()
elif budget_formset.has_changed(): print 'Budget formset not valid.',budget_formset.errors
return HttpResponseRedirect(reverse('projects:concept', args=[project_id]))
and the particular line it's complaining about is:
if drawing_formset.is_valid():
As I understand, this error is usually caused by a call to request.POST?
I am calling request.POST in the parameter where I define drawing_formset:
drawing_formset = DrawingUploadFormset(request.POST, request.FILES, prefix="drawings")
From what I've seen elsewhere on SO, it seems I should be passing a parameter to request.POST, i.e. that line would become:
drawing_formset = DrawingUploadFormset(request.POST["someParameter"], request.FILES, prefix="drawings")
But I'm not sure exactly what I should be passing to the call to POST as a parameter...? Is this definitely what I need to do to fix the MultiValueDictKeyError? If so, what would I need to be passing as a parameter, or if not, how can I resolve this issue?
Edit
The full error message displayed in the browser when I click the 'Upload' button, having attached an image file to the form, is:
MultiValueDictKeyError at /projects/6215/upload-budget-pdf/
"u'drawings-3-id'"
Request Method: POST
Request URL: http://localhost:8000/projects/6215/upload-budget-pdf/
Django Version: 1.9.1
Exception Type: MultiValueDictKeyError
Exception Value:
"u'drawings-3-id'"
Exception Location: /Users/.../.virtualenvs/.../lib/python2.7/site-packages/django/utils/datastructures.py in getitem, line 85
Python Executable: /Users/.../.virtualenvs/.../bin/python
Python Version: 2.7.6
and the Traceback shows:
/Users/.../Documents/Dev/.../.../projects/views.py in upload_budget_pdfs
if drawing_formset.is_valid(): ...
▼ Local vars
Variable Value
project
<Project: Test 1>
drawing_formset
<django.forms.formsets.DrawingFormFormSet object at 0x113223cd0>
project_id
u'6215'
request
<WSGIRequest: POST '/projects/6215/upload-budget-pdf/'>
The output displayed in the console when I click the 'Upload' button, and am taken to the webpage displaying the error is:
Internal Server Error: /projects/6215/upload-budget-pdf/
Traceback (most recent call last):
File "/.../.../.virtualenvs/.../lib/python2.7/site-packages/django/core/handlers/base.py", line 140, in get_response
response = middleware_method(request, callback, callback_args, callback_kwargs)
File "/.../.../Documents/Dev/.../.../.../middleware.py", line 72, in process_view
return permission_required(required_permission)(view_func)(request,*view_args,**view_kwargs)
File "/.../.../.virtualenvs/.../lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/.../.../Documents/Dev/.../.../projects/views.py", line 1003, in upload_budget_pdfs
if drawing_formset.is_valid():
File "/.../.../.virtualenvs/.../lib/python2.7/site-packages/django/forms/formsets.py", line 316, in is_valid
self.errors
File "/.../.../.virtualenvs/.../lib/python2.7/site-packages/django/forms/formsets.py", line 290, in errors
self.full_clean()
File "/.../.../.virtualenvs/.../lib/python2.7/site-packages/django/forms/formsets.py", line 338, in full_clean
form = self.forms[i]
File "/.../.../.virtualenvs/.../lib/python2.7/site-packages/django/utils/functional.py", line 33, in get
res = instance.dict[self.name] = self.func(instance)
File "/.../.../.virtualenvs/.../lib/python2.7/site-packages/django/forms/formsets.py", line 144, in forms
for i in range(self.total_form_count())]
File "/.../.../.virtualenvs/.../lib/python2.7/site-packages/django/forms/models.py", line 587, in _construct_form
pk = self.data[pk_key]
File "/.../.../.virtualenvs/.../lib/python2.7/site-packages/django/utils/datastructures.py", line 85, in getitem
raise MultiValueDictKeyError(repr(key))
MultiValueDictKeyError: "u'drawings-3-id'"
Edit
The original view that's displaying the page on which I click the 'Upload' button to try to upload an image to the form is:
def concept(request, project_id):
project = Project.objects.prefetch_related('budget_versions').get(id=project_id)
deposit = Deposit.objects.get_or_create(project=project)[0]
presentations = project.budget_versions.select_related('meeting').prefetch_related('budget_items', 'cci_items', 'presenters').filter(version_number__isnull=False).annotate(vn=F('version_number') * -1).order_by('presentation_date', 'created', '-vn')
end_details = EndDetails.objects.get_or_create(project=project)[0]
presentation_formset = BudgetPresentationFormset(prefix="presentations", instance=project, queryset=presentations)
drawing_formset = DrawingUploadFormset(prefix="drawings", queryset=Drawing.objects.filter(budget__in=presentations).order_by('budget__presentation_date', 'budget__created'))
context = {
'project': project,
'presentations': presentations,
'presentation_formset': presentation_formset,
'drawing_formset': drawing_formset,
'deposit_form': DepositInfoForm(instance=deposit),
'ended_form': EndDetailsForm(instance=end_details),
'budget_notes_form': BudgetNotesForm(instance=project.budget_overview),
}
return render(request, 'projects/concept.html', context)
and the part of the template that's displaying the relevant parts of the page (i.e. the form, buttons, etc) is:
{% block content %}
<form method="POST" enctype="multipart/form-data" data-vat-status="{{project.vat_status}}" data-view-url="{% url 'projects:concept_save_ajax_2' project.id %}" class="autosave_form formset full-width" action="{% url 'projects:upload_budget_pdfs' project.id %}">
{% csrf_token %}
<div id="presentations" class="app-wrap center-apps middle">
{% with get|apps:'Budgets' as costing_app %}
{% for presentation in presentations %}
<div id="presentation-{{presentation.id}}" class="app sm {% if presentation.current_marker %}{{costing_app.color}}{% else %}{{app.color}}{% endif %}">
<a class="show-presentation bottom-right" name="presentation-{{presentation.id}}"><img class="icon" src="{% static 'img/edit-white.png' %}"></a>
<ul class="flush">
<li class=""><h2 class="p-t-lg">Presentation {{forloop.counter}}</h2></li>
<li>{{presentation.presentation_date|date:"d M y"|xor}}</li>
<li>{{presentation.details|xor|truncatechars:50}}</li>
{% if presentation.current_marker %}<li>({% if project.deposit_received%}Deposit{% else %}Current{% endif %} budget)</li>{% endif %}
</ul>
</div>
{% if forloop.last %}
{% endif %}
{% endfor %}
{# Add a new presentation #}
<div id="presentation-new" class="app sm {{costing_app.color}} outline">
<a id="new_presentation" data-view-url="{% url 'projects:save_new_presentation' project.id %}" class="filler show-presentation" name="presentation-new"></a>
<a name="presentation-new"></a>
<span class="big-head">+</span>
<h2 class="no-m">Add presentation</h2></li>
</div>
{% endwith %}
</div>
<div class="middle">
{{presentation_formset.management_form}}
{{drawing_formset.management_form}}
<div class="col-9 centered-block p-t-lg">
<table class="left fixed text-sm slim">
{# New presentation without budget #}
<tbody>
</tbody>
{# Edit presentation details #}
{% for presentation_form in presentation_formset %}
<tbody id="pres{{forloop.counter}}" class="presentation-form" name="presentation-{{presentation_form.instance.id|xor:'new'}}" style="display: none;">
{% if not forloop.last and presentation_form.instance.budget_items.count %}
<tr class="split-rows">
<td colspan="3">Exc VAT {% if not presentation_form.instance.current_marker %}{{presentation_form.instance.grand_total_exc_vat|money:'£'}}{% else %}{{project.budget_overview.updated_exc_vat|money:'£'}}{% endif %}</td>
<td colspan="3">Inc VAT {% if not presentation_form.instance.current_marker %}{{presentation_form.instance.grand_total_inc_vat|money:'£'}}{% else %}{{project.budget_overview.updated_inc_vat|money:'£'}}{% endif %}</td>
</tr>
{% endif %}
<tr>
{% for hidden in presentation_form.hidden_fields %}
<td class="hidden">{{ hidden }}</td>
{% endfor %}
</tr>
{% for field in presentation_form.visible_fields %}
<tr class="split-rows">
{% if not field.name == 'pdf_package_dep' %}
<td colspan="6"><label>{{field.label}}</label></td>
{% endif %}
</tr>
<tr class="split-rows">
<td colspan="6">
{% if not field.name == 'pdf_package_dep' %}
{% if field.name == 'presentation_date' %}
{% with presentation_form.instance.meeting as meeting %}
{% include "projects/includes/meeting_bit.html" with employee=request.user.employee meeting=meeting UID=presentation_form.instance.id %}
{% endwith %}
{# <a class="ical_trigger button" data-view-url="{% url 'events:add_to_cal' %}" {% if not field.value %}style="display:none"{% endif %}>Add to calendar</a> #}
{% else %}
{{field}}
{% endif %}
{% endif %}
</td>
</tr>
{% endfor %}
{% if presentation_form.instance.id %}
{# PDF uploads #}
{% with drawing_form=drawing_formset|getval:forloop.counter0 %}
{# budget_pdf_form=budget_pdf_formset|getval:forloop.counter0 #}
<tr>
{% if not forloop.last %}
<td colspan="3"><label>Budget PDF package</label></td>
{% endif %}
<td colspan="3"><label>Drawings</label></td>
</tr>
<tr>
{% if not forloop.last %}
<td colspan="3" class="center">
{% if presentation_form.instance.pdf_package_dep %}
<a class="button file-download pdf" href="{% url 'costing:pdf_open' presentation_form.instance.id %}?pdf=package_dep" target="_blank"></a><a class="pdf-clear" data-view-url="{% url 'costing:pdf_clear' presentation_form.instance.id %}?pdf=package_dep"><img class="icon m-l-sm m-b-md" src="{% static "img/bin.png" %}"></a>
{% else %}
{{presentation_form.pdf_package_dep}}
{% endif %}
</td>
{% endif %}
{% for d_field in drawing_form.visible_fields %}
{% if drawing_form.instance.pdf %}
<td colspan="3" class="center">
<a class="button file-download pdf" href="{% url 'costing:pdf_open' presentation_form.instance.id %}?pdf=drawings" target="_blank"></a><a class="pdf-clear" data-view-url="{% url 'costing:pdf_clear' presentation_form.instance.id %}?pdf=drawings"><img class="icon m-l-sm m-b-md" src="{% static "img/bin.png" %}"></a>
</td>
{% else %}
<td colspan="3">{{d_field}}</td>
{% for d_hidden in drawing_form.hidden_fields %}
<td class="hidden">{{d_hidden}}</td>
{% endfor %}
{% endif %}
{% endfor %}
<tr>
<td colspan="1" class="p-t-md"></td>
<td colspan="4" class="p-t-md"><input type="submit" value="upload"></td>
<td colspan="1" class="p-t-md"></td>
</tr>
</tr>
{% endwith %}
{% endif %}
<tr>
<td colspan="3">
<a class="button email_trigger m-t-md" style="width:auto;" data-view-url="{% url 'comms:open_email_template' project.id %}?template=6&budget={{presentation_form.instance.id}}">Email client meeting report</a>
</td>
</tr>
<tr>
<td class="p-t-md">
<a {% if forloop.last %}id="refresh_presentations"{% endif %}class="update_presentation button fill">Done</a>
</td>
<td colspan="2">
{% if presentation_form.instance.id and not presentation_form.instance.budget_items.count %}
<a class="button fill" href="{% url 'costing:delete_presentation' presentation_form.instance.id %}">Delete</a>
{% endif %}
</td>
</tr>
</tbody>
{% endfor %}
</table>
</div>
</div>
</form>
<form method="POST" enctype="multipart/form-data" data-vat-status="{{project.vat_status}}" data-view-url="{% url 'projects:concept_save_ajax' project.id %}" class="autosave_form full-width">
{% csrf_token %}
<div class="col-12 box">
<div>
<table class="right fixed m-t-md">
<tr>
{% for hidden in deposit_form.hidden_fields %}
{{hidden}}
{% endfor %}
{% for field in deposit_form.visible_fields %}
<td class="p-r-md">{{field.label}}</td><td class="p-r-md">{{field}}</td>
{% endfor %}
<td><a class="email_trigger button" data-view-url="{% url 'comms:open_email_template' project.id %}?template=7">Raise invoice</a></td>
</tr>
</table>
</div>
</div>
<div class="col-6 box">
<div>
<div class="expand-header"><strong class="m-t-md">Costing notes</strong></div>
<table class="vertical-table left">
{% include "projects/includes/stacked_form.html" with form=budget_notes_form %}
</table>
</div>
</div>
<div class="col-6 box">
<div>
<div class="expand-header"><strong class="m-t-md">Project rejected by client?</strong></div>
<table class="vertical-form left">
{% include "projects/includes/stacked_form.html" with form=ended_form %}
</table>
</div>
</div>
</form>
{% endblock content %}
and DrawingUploadFormset is defined in forms.py with:
class DrawingUploadForm(ValidatedForm):
class Meta(object):
model = Drawing
fields = ['pdf',]
DrawingUploadFormset = modelformset_factory(Drawing, form=DrawingUploadForm, max_num=12, extra=1, can_delete=False)

Django- how to add another field to a table displayed in a web page

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>

Categories