Django can't upload file - python

I'm doing a django app with a form using image file upload. I have a default image in case user doesnt choose an image. But when I save the form, my image isn't saved in my files. Any idea ?
Here's my code :
First my views.py
class AnimalCreateView(generic.CreateView):
model = Animal
form_class = AnimalForm
template_name = 'myApp/animal_create.html'
success_url = reverse_lazy('animal:index')
Then my models.py
class Animal(models.Model):
name= models.CharField()
animal_photo= models.ImageField(upload_to="images/",default="images/noPhoto.svg", null=False, blank=True)
def __str__(self):
return f'{self.name}'
And my animal_create html :
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col-lg-8 offset-lg-2">
<h4>My anmials</h4>
<table class="table">
<thead>
<tr>
<th> </th>
<th>Name</th>
<th>Photo</th>
</tr>
</thead>
<tbody>
{% for animal in animal_list%}
<tr>
<td>{{animal.name}}</td>
<p> {{ animal.photo.url }} </p> #check url file
<td class="picture-thumb">
{% if animal.photo.url %}
<img src="{{ animal.photo.url}}"" />
{% else %}
<img src="{% static 'images/noPhoto.svg' %}" />
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endblock content %}
When I save my file and then check my html or django admin page, all the rows of animal_photo are using the default file...

Where are you using form from context? And also, to upload an images(files) you need to set
{% if form.is_multipart %}
<form enctype="multipart/form-data" method="post" action="/foo/">
{% else %}
<form method="post" action="/foo/">
{% endif %}
https://docs.djangoproject.com/en/3.1/ref/forms/api/#testing-for-multipart-forms

Related

Prompt Asking For Password When Pressing A Button

I would like to add a prompt everytime someone tries to press the button to 'Delete' or 'Download' a file (in my project, you can upload files with passwords, so that if someone wants to delete/download the file, he needs to enter a password).
The password itself is saved in the models.py using django - how would i be able to to so in my code (listing my viwes.py to the html code, urls.py, models.py, forms.py, HTML CODE Itself).
#login_required(login_url='login')
def My_Files(request):
files = File.objects.all()
return render(request, 'home/My Files.html', {"files" : files})
path("MyFiles", views.My_Files, name="my_files"),
path("MyFiles/<int:pk>/", views.delete_file, name="delete_file"),
{% extends 'layouts/base.html' %}
{% load static %}
{% block title %} {% endblock title %}
<!-- Specific CSS goes HERE -->
{% block stylesheets %}{% endblock stylesheets %}
{% block content %}
{% include "includes/footer.html" %}
<h2>My Files</h2>
<table class="table">
<thead>
<tr>
<th>File Name</th>
<th>File Description</th>
<th>Uploaded By</th>
<th>Download</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{% for file in files %}
<tr>
<td> {{ file.File_Name }}</td>
<td> {{ file.File_Type }}</td>
<td> {{ file.Uploaded_By }}</td>
<td>
<a href="{{ file.File.url }}" class="btn btn-primary btn-sm" target="_blank">
Download File
</a>
</td>
<td>
<form method="post" action="{% url 'delete_file' file.pk %}">
{% csrf_token %}
<button type="submit" class="btn btn-dange btn-sm">Delete</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock content %}
<!-- Specific JS goes HERE -->
{% block javascripts %}
<script>
}
},
},
},
});
</script>
{% endblock javascripts %}
class File(models.Model):
File_Name = models.CharField(max_length=200, null=True)
File_Type = models.CharField(max_length=30, null=True)
Uploaded_By = models.CharField(max_length=90,default=None,blank=True, null=True)
Password = models.CharField(max_length=100, null=True)
File = models.FileField(upload_to='Files')
def __str__(self):
return self.File_Name
def delete(self, *args, **kwargs):
self.File.delete()
super().delete(*args, **kwargs)
def UploadedBy(self,username):
self.File.Uploaded_By = username
# Create your forms here.
class FileForm(forms.ModelForm):
class Meta:
model= File
fields= ["File_Name", "File_Type","Uploaded_By","Password","File"]
You should define a form with a field for entering password which validates against the password of the specific file, then add your delete or download logic after form.is_valid() is called

Edit and Update method is working.But,how to retrieve the values from database while editing the existing values

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.

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>

Form fields not displayed in django html

I have written a code to make form , and i have no guess why the fields are not displayed here are my codes.
I want to get a request from the index.html page and using that request, I ran a query to display the results of the query on the same page.
views.py
def search123(request):
searc=search1()
if request.method=="POST":
searc=search1(request.POST or None)
if searc.is_valid():
if 'd_box' in request.POST:
item_map=item.objects.raw('SELECT * FROM `item` WHERE `category_id`=%s', [request.POST['d_box']])
lis=[]
for e in (item_map):
lis.append(e.id)
price_map=item_done.objects.filter(item_id__in=lis).order_by('item_id')
return render_to_response('index.html',{'posts':price_map},RequestContext(request))
return render_to_response('index.html',{'posts':searc},RequestContext(request))
index.html
<html>
<head>
</head>
<body>
<form method='POST' action=''>{% csrf_token %}
<h4> SEARCH </h4>
{{searc.as_table}}
<input type='submit' name="button7" value="button7">
</form>
{% regroup posts by item_id as post_list %}
<table border="4" style="width:1050px;border-collapse: collapse" >
<thead>
<tr>
<th>Item Codes</th>
<th>Name</th>
<th>MRP</th>
<th>Site price</th>
<th>Website</th>
</tr>
</thead>
<tbody>
{% for country in post_list %}
<tr>
<td>{{ country.grouper }}</td>
<td>
{% for item in country.list %}
<div style="margin: 5px 5px">{{item.name}}</div>
{% endfor %}
</td>
<td>
{% for item in country.list %}
<div style="margin: 5px 5px">{{item.mrp}}</div>
{% endfor %}
</td>
<td>
{% for item in country.list %}
<div style="margin: 5px 5px">{{item.site_price}}</div>
{% endfor %}
</td>
<td>
{% for item in country.list %}
<div style="margin: 5px 5px">{{item.crawl_id}}</div>
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</html>
forms.py
class search1(forms.ModelForm):
class Meta:
model=search
exclude=[]
i think you must import search model in forms.py an also in your template you write the form name wrong ! you write {{searc.as_table}} it must be {{search.as_table}}

Categories