I have some data which I am passing from my views to my templates, whenever the else if the statement is true(that is the if the statement is false) the statement appears after my HTML header().
My main issue is that why is the else block not under the HTML heaader where I have put it in the code
templates.html
<table class="table table-borderless table-data3">
<thead>
<tr>
<th>No</th>
<th>Email</th>
<th>Telephone</th>
<th>Country</th>
<th>Status</th>
<th>Image</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% if supplier %}
{% for supplier in suppliers %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{supplier.email}}</td>
<td>{{supplier.telephone}}</td>
<td>{{supplier.country}}</td>
<td class="process">Active</td>
<td>{{supplier.image.url}}</td>
<td>
<div class="table-data-feature">
<button class="item" data-toggle="tooltip" data-placement="top" title="Edit">
<i class="zmdi zmdi-edit"></i>
</button>
<button class="item" data-toggle="tooltip" data-placement="top" title="Delete">
<i class="zmdi zmdi-delete"></i>
</button>
</div>
</td>
</tr>
{% endfor %}
{% else %}
<h2>No supplier available</h2>
{% endif %}
</tbody>
</table>
You can not write a h2 in <tbody> or at least not directly. Yolu write this wrapped in a <tr> and <td>:
{% if suppliers %}
…
{% else %}
<tr><td colspan="7">No supplier available</td></tr>
{% endif %}
You also made a typo in the if statement: it is suppliers, not supplier.
Note: Django has a {% for … %}…{% empty %} template tag [Django-doc] that
can be used to render a message if the collection you iterate over is empty.
You can use the {% for … %}…{% empty %} django template tag. Example:
HTML
{% for supplier in suppliers %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{supplier.email}}</td>
<td>{{supplier.telephone}}</td>
<td>{{supplier.country}}</td>
<td class="process">Active</td>
<td>{{supplier.image.url}}</td>
<td>
<div class="table-data-feature">
<button class="item" data-toggle="tooltip" data-placement="top" title="Edit">
<i class="zmdi zmdi-edit"></i>
</button>
<button class="item" data-toggle="tooltip" data-placement="top" title="Delete">
<i class="zmdi zmdi-delete"></i>
</button>
</div>
</td>
</tr>
{% empty %}
<div><h2>No Suppliers Available</h2></div>
{% endfor %}
I get data from the pandas(DataFrame), which is in list of lists, like [['jay', 'M', 'CS'],[],[]] and so on . How can i put this data in table. I directly push the list-data in html file. first loop works fine, but it didn't pass in second loop, How can I do that? I am new to html.
{% for post in post_data %}
<tr>
{% for value in post %}
<td>
{{value}}
</td>
{% endfor %}
</tr>
{% endfor %}
i pass 'tables': [df.to_html(classes='data', header="true")], data display in raw html.
<div class="card card-stats">
<div class="card-body ">
<div class="card-header ">
<!--div class="progress-container progress-info"-->
<!--<h6 class="card -title" style="color:#FFFFFF; background-color:#008B8B;" align="center">DataFiles</h6>-->
<table id="TripGrid" class="datafiletable" cellspacing="0" width="100%">
<thead style="background-color: #6699FF">
{% for header in post_header %}
<th>{{header}}</th>
{% endfor %}
</thead>
<tbody>
{% for table in tables %}
{{table}}
{% endfor %}
</tbody>
</table><br>
</div>
</div>
</div>
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)
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>
I am new to django , please bear with me ..
created a template using django formsets and it works all good except i am not able to give header to the can_delete column .
My Django views.py looks like :
def add_expenditure(request):
context = RequestContext(request)
ExpFormSet = modelformset_factory(Expenditure,extra=1,max_num=10,fields=('exp_date', 'description','amount'),can_delete=True)
if request.method == 'POST':
formset = ExpFormSet(request.POST)
if formset.is_valid():
formset.save(commit=True)
formset = ExpFormSet()
else:
print "errors in formset are ",formset.errors
else:
formset = ExpFormSet(queryset=Expenditure.objects.none())
return render_to_response('moni/add_expenditure.html', {'formset':formset}, context)
templete form code is as below :
<form id="expenditure_form" method="post" action="/moni/add_expenditure/">
{% csrf_token %}
<table border=10>
<tr>
<th>Serial No.</th>
<th><label >Date:</label></th>
<th><label for="id_description">Description:</label></th>
<th><label for="id_amount">Amount</label></th>
</tr>
{{ formset.management_form }}
{% for form in formset %}
<tr>
<td>{{forloop.counter}}</td>
{% for field in form %}
<td> {{ field.class }} {{ field }}
{% if field.name == "exp_date" %}
<a href="javascript:void(0)" class="todaylink" id= {{forloop.parentloop.counter0}} >Today</a>
{% endif %}
</td>
{% endfor %}
</tr>
<br>
{% endfor %}
</table>
<input type="submit" name="submit" value="Create Expenditure" />
</form>
and template looks like :
What i want is to have a header for delete check box as well .. just next to amount . I tried adding one more header but seems its not working as intended . Can someone provide any advices .. Below is how it looks after adding one more header
<form id="expenditure_form" method="post" action="/moni/add_expenditure/">
{% csrf_token %}
<table border=10>
<tr>
<th>Serial No.</th>
<th><label >Date:</label></th>
<th><label for="id_description">Description:</label></th>
<th><label for="id_amount">Amount</label></th>
<th><label for="id_delete">Delete</label></th>
</tr>
{{ formset.management_form }}
{% for form in formset %}
<tr>
<td>{{forloop.counter}}</td>
{% for field in form %}
<td> {{ field.class }} {{ field }}
{% if field.name == "exp_date" %}
<a href="javascript:void(0)" class="todaylink" id= {{forloop.parentloop.counter0}} >Today</a>
{% endif %}
</td>
{% endfor %}
</tr>
<br>
{% endfor %}
</table>
<input type="submit" name="submit" value="Create Expenditure" />
</form>
Any Advice as to how to create this header above delete check box ?
The problem is
{% for field in form %}
<td> {{ field.class }} {{ field }}
{% if field.name == "exp_date" %}
<a href="javascript:void(0)" class="todaylink" id= {{forloop.parentloop.counter0}} >Today</a>
{% endif %}
</td>
{% endfor %}
This create 5 TD and you have 4 TD in header.
Please try this
<tr>
<th>Serial No.</th>
<th><label >Date:</label></th>
<th><label for="id_description">Description:</label></th>
<th><label for="id_amount">Amount</label></th>
<th></th>
<th><label for="id_delete">Delete</label></th>
</tr>
Also you can remove element before delete checkbox.