Django Template strange behavior of layout - django

I have a function which generate a pdf.file and send it by email. And it works perfect. And I have a Table on my frontend
like above.
In my Django Model - Point 1 set by default as False, by condition if Point 1 is False - Cell 2 is empty, else - marked as Done. When I changing Table via Django form it works fine as well (frontend marked as Done). The problem is when I trying to change this via function which generate a pdf. I have added below lines of code in my pdf.generate Function:
def generatePdf(request, pk):
point = get_object_or_404(MyObj.objects.select_related('related'), pk=pk)
...
email.send(fail_silently=False)
point.one = True
print(point.one)
messages.success(request, 'Success')
return HttpResponseRedirect....
at the terminal I got the message that value changed properly from False to True
but for some reason Cell 2 in my Table on the frontend still is empty...
Part of frontend code:
{% for item in object_list %}
...
<td>
{% if item.one %}
<span><i class="fa fa-solid fa-check"></i></span>
{% else %}
<span></span>
{% endif %}
</td>
...
{% endfor %}
Summarizing the above said - why frontend condition working properly only if I change via Django form (function) and not if I trying to change via generatePdf function? Cell value in database changed properly in both ways!

I just forgot to add:
point.save()
in order to save to database changes.
So simple...

Related

Make navbar active on url and any url's following from it

I am trying to make my navbar element active if the user is on the current url and any url's leading from it.
For example, I want the navbar to be active on:
http://example.com/products
AND
http://example.com/products/discounted-items
I was using this:
{% if url_name == 'products' %}active{% endif %}
and was very happy till I realised that once I progress from the 'products' page to 'products/discounted-items' it would cease being active.
Is there a clean way to do this in django?
Thank you very much.
In your case you could simply do the following:
{% if 'products' in url_name %}active{% endif %}
Be aware that this also causes /productsfoobar to be active.
To prevent that you could use products/ instead of checking it without the trailing-slash.
In case (as i seen the page) if u are using Bootstrap u can add "active" in the class field in nav

Conditional Statement not working in Django template while accessing a dictionary with dot operator

I am trying to offer a download option if the file daily-yyyy-mm.csv exits but it always shows Not Avaialable
even if the file exists.
I have made a dictionary (file_list) in views.py which saves True for that index if the file exists. I have checked the path generated at os.path.join and it is correct and also the dictionary has True for the files that exist. I think the problem is using 2 nested dot operators while accessing the dictionary in template.
Template
{% for upload in upload_list %}
<tr>
{%if file_list.upload.upload_report_date %}
<td><a href="{%static 'media/daily-{{ upload.upload_report_date|date:"Y-m" }}.csv" download >Download</a></td>
{% else %}
<td>Not Available</td>
{% endif %}
</tr>
{% endfor %}
Views.py
upload_list = Upload.objects.all().order_by('-upload_at')
file_list={}
for upload in upload_list:
try:
if os.path.exists(os.path.join(settings.MEDIA_ROOT,'daily-%s.csv' % (upload.upload_report_date).strftime("%Y-%m"))):
file_list[upload.upload_report_date]=True
except:
pass
I am using python 2.7 and django 1.6.7 .
You currently try to access the dictionary file_list from within your template: file_list.uplad.upload_report_date.
With this you will always land in else because you can't access it that way.
Your code tries to get the propery upload of file_list which will always return None since it doesn't exist.
What you could do is to create a list of the available files (since you already called your variable _list):
file_list = []
for upload in upload_list:
try:
if os.path.exists(...):
file_list.append(upload.upload_report_date)
except:
pass
Then inside your template:
{% if upload.upload_report_date in file_list %}
...

Additional field shows up outside table in admin change_list view

I have a model called Project in an app called projects that I registered with the admin site so the instances can be added/edited/etc. This works as expected. Now I want to add a button for each project in the change list view on the admin site, that links to a custom form that requires a Project instance to do things. I followed a bunch of different tutorials to customize the admin site and managed to add another field to the table of the change list view. However the entries show up outside the table (see image).
I added the custom field by overwriting the admin/change_list.html template and calling a custom template tag custom_result_list within it. This tag adds a table field to the change list and then calls the admin/change_list_results.html template to render it. I have confirmed with a debugger that the item is added to the entries of the change list before the template is rendered (see image).
I cannot explain why the table is not rendered correctly even though the additional field has the same structure as the auto-generated ones. I have to admit I have resorted to Cargo Cult Programming, because I do not understand how this is supposed to work, despite spending too many hours trying to solve this simple problem.
Here's the relevant code.
In file /projects/templatetags/custom_admin_tags.py:
from django import template
from django.contrib.admin.templatetags.admin_list import result_list as admin_result_list
def custom_result_list(chl):
extended_cl = {}
extended_cl.update(admin_result_list(chl))
extended_cl["result_headers"].append({
'class_attrib': r' class="column-__str__"',
'sortable': False,
'text': 'Configure Project'
})
idx = 0
snippet = '<td class="action-button">{}</td>'
for project in chl.result_list:
extended_cl["results"][idx].append(snippet.format(project.id, project.unmod_name))
idx += 1
return extended_cl
register = template.Library()
register.inclusion_tag('admin/change_list_results.html')(custom_result_list)
In file templates/admin/projects/project/change_list.html:
{% extends "admin/change_list.html" %}
{% load i18n admin_urls static admin_list %}
{% load custom_admin_tags %}
{% block result_list %}
{% if action_form and actions_on_top and cl.show_admin_actions %}{% admin_actions %}{% endif %}
{% custom_result_list cl %}
{% if action_form and actions_on_bottom and cl.show_admin_actions %}{% admin_actions %}{% endif %}
{% endblock %}
To fix your issue:
from django.utils.html import format_html
replace your snippet.format(...) with format_html(snippet,...)
Explanation:
in django, all strings you pass from python are automatically HTML escaped. which here means, all your tags will not be considered as HTML. Such limitation is added to avoid any potential exploits by hackers. In your case, use of a template to render html is highly recommended. However, you can also send raw html from python using format_html helper function.

Parameter Missing: Expected parameter(s): Flask Python Py2neo

I am just getting started with Python, Flask and Neo4j. I am struggling with trying to pass a parameter from a url to a cypher query via py2neo.
I have tried a number of suggestions from the forums, tutorials and examples on github but have not managed to get this to work and was hoping someone could point me in the right direction.
This is views.py
#Single Comic
#app.route('/comic/<issue>/')
def comic(issue):
# Get comic
issue = comics.get_issue(issue)
return render_template('issue.html', issue=issue)
This is my models.py (if I hard code the issue number into the query it shows correctly)
class comics:
def __init__(self, issue):
self.issue = issue;
def get_issue(issue):
query = '''
MATCH (c:Comic) WHERE c.Issue=$issue
RETURN c.Issue as issue, c.Title as title
'''
return graph.run(query)
This is the issue.html template
{% extends "base.html" %}
{% block content %}
{% for row in issue %}
<h1>{{ row.issue }}: {{ row.title }} </h1>
<img src="/static/comics/{{ row.issue }}.png" alt="{{ row.title }}">
{% endfor %}
{% endblock %}
When I try to browse www.mydomain.com/comic/1 I get a "Parameter Missing: Expected parameter(s): issue" error
Many thanks
You're almost there.
For Cypher substitution, you simply need to pass the parameter as a keyword argument into graph.run. So you'll end up with something like:
class comics:
def __init__(self, issue):
self.issue = issue;
def get_issue(issue):
query = '''
MATCH (c:Comic) WHERE c.Issue=$issue
RETURN c.Issue as issue, c.Title as title
'''
return graph.run(query, issue=issue)
It looks like you were expecting the variable to be absorbed from the enclosing scope, but this is a remote query wherein both statement template and parameters are transmitted over the wire. So the driver doesn't do the substitution, it happens on the server, within the Cypher engine. To that end, everything needs to be supplied explicitly.

How do I look in a list of items, find the user and see if it exists in a different table and change the template as a result?

I have a simple follow/following setup running.
When a user (request.user) see's an object she likes, she can click the follow button and follow that user.
When she returns I want that button on the object to now not be enabled cause she is already following that user.
What is happening is that in the background, the follower/followee record is being made. The object in question has the id of the followee. I just can't figure out how to add that representation to the object_list.
In REST I would add a field to the serializer and that would take care of it. I could then evaluate the truthiness of the new field.
Any ideas on how to accomplish this?
You should do it as a separate query and make the test in the template.
view:
def objects_list(request):
...
return render(request, "the_template_path.html", {
'objects': ObjectName.objects.all()[0:100],
'followed_object_ids': ObjectName.objects.filter(follower=request.user).values_list('id', flat=True)
})
template:
{% for object in objects %}
{% if object.id in followed_object_ids %}
...
{% else %}
...
{% endif %}
{% endfor %}
That will get you started. Obviously you don't want to use generic names like object.
It would then probably be better to move the followed_object_ids query in a middleware so you don't always do it (really useful if you have featured objects widgets everywhere for instance).