I have a download button in my HTML that has a href to a path on my system for the corresponding file. How can I load that path into my view when at user clicks download? Also this value is unique for each download button.
If there's any other way that I can do this without exposing my system path in the href I would much prefer to know that. Thanks in advance.
Right now I have some HTML that looks like this. How do I grab the info from item.OutputPath into my view when clicked?
<div class="dashboard-2">
<div class="tasks-finished">
<h1>Finished tasks</h1>
</div>
<div class="tasks-list">
<table>
<tr>
<th>Name</th>
<th>Task ID</th>
<th>Status</th>
</tr>
{% for item in query_finished %}
<tr>
<td>{{ item.TaskNavn }}</td>
<td>{{ item.TaskID }}</td>
<td>Download </tr>
{% endfor %}
</table>
</div>
</div>
Additonal info:
I need this value because i'm trying to save it as a variable to serve protected files using Nginx.
Exposing the system path is a bad idea in itself, but using it as an input parameter would be a huge security risk.
It is better to pass the id of your item to your download view. Something like this:
# template
<td>Download</tr>
# urls.py
path('download/<int:pk>/', views.download_item, name='item-download'),
# views.py
def download_item(request, pk):
# Make sure to perform any required checks, e.g. item.owner=request.user
item = get_object_or_404(Item, pk=pk)
output_path = item.OutputPath
...
Related
I have single html page with dynamic images from database in Django.
I also have a modal in the same page set to invisible and opens when image is clicked.
My intension is when I click on any image it should open a html model with the clicked image and its description text from db.
How do I display data of the current clicked image and its description.
I have tried to pass {{profile.image.url}} but this gives one information on click to all images.
I didn't have to give sample code on this.
You can achieve this by passing the id of the object you want to retrieve using AJAX request.
Let's suppose, this is your HTML table
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Date</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for incident in page_obj %}
<tr>
<td>{{ incident.id }}</td>
<td>{{ incident.title }}</td>
<td>{{ incident.created }}</td>
<td>
<span class="badge badge-pill badge-success">{{ incident.get_status_display }}</span>
</td>
<td>
<button class="btn btn-sm btn-outline-info" onclick="populateForm('{{ incident.id }}')" data-toggle="modal" data-target="#incidentModal">Edit</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
Use this type of function according to your model and fields
function populateForm(id) {
$.ajax({
url: "{% url 'incidents:update' 1 %}".replace("1", id),
type: "GET",
success(response) {
let incident = JSON.parse(response)[0].fields;
$("#id_title").val(incident.title);
$("#id_description").val(incident.description);
$("#id_responder").val(incident.responder);
$("#id_status").val(incident.status);
$("#id_functional_impact").val(incident.functional_impact);
$("#id_information_impact").val(incident.information_impact);
$("#id_recovery_impact").val(incident.recovery_impact);
},
});
}
views.py
from django.core import serializers
from django.http import JsonResponse, Http404
from django.views.generic import UpdateView
from incidents.models import Incident
from incidents.forms import IncidentForm
class IncidentUpdateView(UpdateView):
form_class = IncidentForm
model = Incident
def get_success_url(self):
return reverse('incidents:list')
def get(self, request, pk):
if request.is_ajax():
incident = get_object_or_404(Incident, pk=pk)
response = serializers.serialize("json", [incident])
return JsonResponse(response, safe=False)
raise Http404('Page not found')
There are 2 options on how to achieve this:
render modals for all images with django and open them when user clicks one of the images.
create 1 modal and write some javascript to fetch information about the clicked image in the background. Note, that you'll also need to create an endpoint in Django that will accept image ID and return image information.
Good day,
I'm asking myself, if it's possible to transfer multiple informations as primary-keys inside my template!?
For example, when clicking on a link inside my table...
In this case im transfering the item-id:
<tbody>
{% for item in dataset %}
<tr>
<td>
Item-Name
</td>
</tr>
{% endfor %}
</tobdy>
Now I want to transfer the id and - let's say - the name! Is something like this even possible?
<tbody>
{% for item in dataset %}
<tr>
<td>
Item-Name
</td>
</tr>
{% endfor %}
</tobdy>
And if it's possible, do I have to chage something inside my urls.py? Right now it's looking like this:
path('index/<str:pk>', views.example, name="Example"),
Thanks for all your help and a great day!
Your url should be
{% url 'Examplepage' id=item.id name=item.name %}"
And your path should be
path('index/<str:id>/<str:name>/', views.example, name="Example"),
Hat I'm trying to accomplish is to delete file from server ('static' folder, to be specific).
My jinja template:
<table>
<tr>
{% for file in files_.items %}
<td data-title="title" style="text-align: center">{{ file.title }}</td>
<td data-title="download">Download</td>
{% if current_user.username == "admin" %}
<td data-title="delete" style="text-align: center">Delete</td>
{% endif %}
</tr>
{% endfor %}
</table>
and my function:
#app.route('/upload/<path:filename>/', methods=['GET', 'POST'])
#login_required
def delete(filename):
item = db.session.query(File).get(filename)
os.remove(os.path.join(app.static_folder, item.filename))
db.session.query(File).filter_by(file=filename).delete()
db.session.commit()
return render_template('dashboard.html',delete=delete)
What I'm trying to do is to after clicking on delete in html I want to delete record from database and file from the server. Right now I'm not sure if my approach to call this function is correct, since I've tried to use prints as a primitive log system and there was nothing in the terminal, co I would say function was not called. Also my guess is that I would need to pass filename to it, so Ive tried
{{ delete(filename=file.file) }}
but it returned
UndefinedError: 'delete' is undefined
{{ delete(filename=file.file) }} in template tells python "when rendering template, call function delete()". What you want to do is generate link which, when clicked, will call delete endpoint.
So, use {{ url_for('delete', filename=...) }}
Goal: {% for loop %} over a list (using Jinja2) and then print out results {{print}} in a HTML table using Bootstrap.
Problem: List is not printing in the template.
In the view_config, I used query .all() to return a list of all the assessment_results objects. They are returning... I confirmed this via terminal/print debugging. However, the for loop is not returning the values needed to populate a table; as read in Jinja2 tutorial. I don't think I need to use a for loop in the view_config as I have seen others do (see here), but I am new to this and am trying to figure out how these two programs (SQLALCHEMY and Jinja2) interact.
An example from the printout after using .all() mentioned above:
[<Assessment_Result(owner='<User(username ='baseball', firstname ='Jen', lastname ='See', email='girl#aol.com')>', assessment='<Assessment(name='Becoming a Leader', text='better decisions')>')>]
view_config code:
views.py
#view_config(route_name='assessment_results', request_method='GET', renderer='templates/assessment_results.jinja2')
def all_assessment_results(request):
with transaction.manager: # < --- THIS WAS THE ISSUE !
assessment_results = api.retrieve_assessment_results()
if not assessment_results:
raise HTTPNotFound()
return {'assessment_results': assessment_results}
Corresponding Jinja2 template using Bootstrap:
assessment_results.jinja2
<div class="container">
<table class="table table-hover">
<thead>
<tr>
<td> Assessment ID </td>
<td> Assessment </td>
<td> Owner </td>
</tr>
</thead>
<tbody>
<tr>
{% for x in assessment_results %}
<td>{{ x.assessments|e }}</td>
<td>{{ x.owners|e}}</td>
{% else %}
<td><em>no users found</em></td>
{% endfor %}
</tr>
</tbody>
</table>
</div>
You should look at the documentation
http://jinja.pocoo.org/docs/dev/templates/#for
You want to iterate over a dict, so consider using iteritems, itervalues or what ever you want.
Also note that your query will not return a dict, it will return a list or rows that matched.
I am also not sure if the for-else works in jinja. But you should avoid using that anyways.
I would like to click on a link from my Django page and based on the link i clicked display a new database query filter from that name on the list
<tr>
<th>RootGroup List</th>
</tr>
{% for status in root %}
<tr>
<td><a href={{status.rootgroup }}> {{ status.rootgroup }} </a></td>
#I WANT TO CLICK THE LINK AND DISPLAY A NEW DATABASE BASED ON THE NAME WITH A FILTER OF THE NAME
</tr>
{% endfor %}
def display(request):
x = re.search('d.*','% url ''detail'' poll.id %')
rootFilter = Viewroot.objects.filter(rootstatus__gt=0, type = 1, ("LINK NAME")).values('rootgroup').distinct() #RootGroup List
#return render_to_response('status/index.html', { 'root' : rootFilter },context_instance=RequestContext(request))
#return HttpResponse( x.group(0)),render_to_response('status/index.html', {'app' : appFilter})
return HttpResponse("You displayed ", j )`
Basically, you can make this work by using named groups in your urls.py patterns, e.g.:
(r'^links/(?P<value>\w+)/$', display)
Then, you can access saved part of url inside your view, like:
def display(request, value=None):
print value
And, of course, you should use appropriate url in the template:
<td> {{ status.rootgroup }} </td>
Also see documentation.