Show variable from flask in include html page - python

I have header.html:
<body>
<a class="navbar-brand mr-4 d-flex align-items-center" href="{{ url_for('dash') }}">
<img class="img-fluid" src="../static/assets/images/live-steam/logo.png" alt="Image">
<p class="px-1 font-weight-bold font-14">{{sys_domain}}</p>
</a>
</body>
and .py code:
#flask.route('/header')
def header():
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute('SELECT * FROM system_settings')
user = cur.fetchone()
sys_domain = (user['system_name'])
return render_template("header.html", sys_domain=sys_domain)
When i include this header page to another page '{{sys_domain}}' show nothing!
example of page that header.html include to it:
<body>
<header>
{% include 'header.html' %}
</header>
</body>

I believe it is because when you try to use include, it will not call via the flask route. It is including the template directly and rendering it. You can check this official template documentation link
You can use the "with" keyword of jinja2 to call it that way.
You can check this link to have an idea of this.
You can retrieve the user['system_name'] from mysql as sys_domain variable in the route function of .py code from where you are calling the html file in which header.html is to be called. Then you can do something like this.
{% with sys_domain=sys_domain %}
{% include 'header.html' %}
{% endwith %}

Related

Django python error: auctions.models.Listing.DoesNotExist: Listing matching query does not exist

I am try to display a listing page. Though it displays well, django keeps giving this error as below:
raise self.model.DoesNotExist(
auctions.models.Listing.DoesNotExist: Listing matching query does not exist.
the index view displays all the listings by iteration, and the listing view displays a specific listing view by receiving a variable as "form.title".
my code is as follows:
views.py:
def listing_view(request, title):
# if get a listing page
categories = Category.objects.all()
# Get all the forms submitted
forms = Listing.objects.all()
# get the highest bid for a listing
highest_price = Bid.objects.filter(title=title).order_by("-bid_price").first()
# Get the listing with the title
listing = Listing.objects.get(title=title)
if highest_price is not None:
listing.current_price = highest_price.bid_price
# else set starting price as the current price
else:
listing.current_price = listing.starting_price
listing.save()
index.html:
<!-- image of a listing -->
<div class="col-4">
<a href="{% url 'listing_view' form.title %}">
{% if form.image %}
<img src="{{ form.image.url }}" alt="" width="267px" />
{% elif form.image_url %}
<img src="{{ form.image_url }}" alt="" width="267px" />
{% endif %}
</a>
</div>
listing.html:
<!-- image in the left of the container -->
<div class="col-4">
{% if listing.image %}
<img src="{{ listing.image.url }}" alt="" width="267px" />
{% elif listing.image_url %}
<img src="{{ listing.image_url }}" alt="" width="267px" />
{% endif %}
</div>
the html file here is to clarify that the variable "listing" is needed in the listing page display, because it says does not exist, so I tried to use try and except instead of statement, but it gives me another error as below:
UnboundLocalError: local variable 'listing' referenced before assignment
I understand that I made it a local variable, so return render couldn't reach it.
But how can I get the listing object without the errors?
Any help appreciated!
Thanks!
There could be errors which are related to more things, Make sure you have made the MIGRATION and MIGRATED your Listing model via
python manage.py makemigrations
python manage.py migrate
If that is done correctly then make sure that in your returning value of the view listing_view passes in the context something like this
return render(request, 'yourdir/index.html)

How can I open a page with only one django model object's info after clicking it's ImageField on another page?

I am displaying django models on one of my website's pages. When I press one's ImageField on the page, I want it to open another page including only that one object. How do I do that ?
I thought about using the filter method in my views.py for filtering through my objects and finding that exact one, but I don't know what arguments to use.
Any ideas? (I am a beginner in django)
VIEWS.PY
from django.shortcuts import render
import requests
from . import models
def index(request):
return render(request, 'base.html')
def new_search(request): ********NOT IMPORTANT (I THINK)********
search = request.POST.get('search')
models.Search.objects.create(search=search)
objects = models.Object.objects.all()
results = objects.filter(name__contains=search).all()
args = { 'results': results }
return render(request, "my_app/new_search.html", args)
def individual_page(request):
link = request.GET.get('object-link')
objects = models.Object.objects.all()
return render(request, "my_app/individual_page.html")
MY TEMPLATE
{% extends "base.html" %}
{% block content %}
{% load static %}
<h2 style="text-align: center">{{ search | title }}</h2>
<div class="row">
{% for result in results %}
<div class="col s4">
<div class="card medium">
<div class="card-image">
<a name="object-link" href="{% url 'individual_page' %}"><img src="{{ result.image.url }}" alt=""></a>
</div>
<div class="card-content">
<p>{{result.name}}</p>
</div>
<div class="card-action">
View listing: Price TEST
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
So, the thing I want to do is: when I press the anchor tag that includes the image, I get redirectioned to another page which contains only that one object's info.

Python/ Django- copying buttons from one HTML page to another

I have just taken over the development of some project management software that has been written in Python/ Django- having not used Python or Django much at all before...
There are a few buttons displayed on one of the webpages that it would be useful to display on another page within the application. I can see that these buttons are defined in budget.html with the following code:
{% block page_options %}
<a class="button m-r-md" href="{% url 'costing:export_csv' budget.id %}">Export to Excel</a>
<a class="button m-r-md" href="{% url 'costing:schedule_of_works_post_dep' budget.id %}" target="_blank">Schedule of works</a>
<a class="button m-r-md" href="?pdf=1" target="_blank">PDF</a>
<input data-view-url="{% url 'costing:combined_budget' project.id %}?search=" type="text" id="item_search" placeholder="Item search" />
{% endblock page_options %}
The other page, where I want to be able to use them- variations.html has the following code already in its {%block page_options %} block:
{% block page_options %}
<button class="button modalBtn" name="variation">+ Add variation</button>
<a class="button" href="{% url 'costing:add_omit_builder' project.id %}">+ Add group</a>
<a class="button" id="scas" data-view-url="{% url 'costing:preview_scas' project.budget_overview.version.id %}" href="{% url 'costing:scas_2_variations' project.budget_overview.version.id %}">+ Standard cost assumptions</a>
<!--ERF(17/11/2016 # 1700) Add buttons to export adds/ omits table to excel -->
{% endblock page_options %}
So I tried copying and pasting the code from the first page into this block in the second page:
{% block page_options %}
<button class="button modalBtn" name="variation">+ Add variation</button>
<a class="button" href="{% url 'costing:add_omit_builder' project.id %}">+ Add group</a>
<a class="button" id="scas" data-view-url="{% url 'costing:preview_scas' project.budget_overview.version.id %}" href="{% url 'costing:scas_2_variations' project.budget_overview.version.id %}">+ Standard cost assumptions</a>
<!--ERF(17/11/2016 # 1700) Add buttons to export adds/ omits table to excel -->
<a class="button m-r-md" href="{% url 'costing:export_csv' budget.id %}">Export to Excel</a>
<a class="button m-r-md" href="{% url 'costing:schedule_of_works_post_dep' budget.id %}" target="_blank">Schedule of works</a>
<a class="button m-r-md" href="?pdf=1" target="_blank">PDF</a>
<input data-view-url="{% url 'costing:combined_budget' project.id %}?search=" type="text" id="item_search" placeholder="Item search" />
{% endblock page_options %}
but when I now try viewing this page in the browser, I get an error page which says:
NoReverseMatch at /costing/5915/variations/
I'm not sure why I'm getting this error... do I need to reference any of the calls to the views that I'm using in the code I've copied in elsewhere in the HTML file? Both of the HTML files are in the same app, so share the same models.py file- so I would have thought that they would both be able to use all of the models & views defined within this app?
Is this the case? If so, why am I getting this error on the variations page?
Based on what you said I suppose problem is that your don't have "budget" value in context variable. I think that view which using first template send "budget" in it's context.
But second view don't. That is why when you try to get budget.id in the second template you get the error.
Try to modify context in your view and add "budget" variable to it.
def my_view(request, pk):
budget= get_object_or_404(Budget, pk=pk)
return render(request, 'budget.html', {'budget': budget})
Or if you are using class based view you should override get_context_data method:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['budget'] = self.budget
return context

django endless pagination(twitter style) not working - .endless_more class not in html but used in js

i am using django endless pagination . its working normally that just shows the numbers at the bottom .
but, i tried to integrate twitter style into it:
http://django-endless-pagination.readthedocs.org/en/latest/twitter_pagination.html#pagination-on-scroll
I have followed exactly but didnt work .
When I looked at the js code, i have seen they have used .endless_more in js class, but the generated html file has only two classes for links :
1)endless_page_current
2)endless_page_link
but they used a.endless_more in js.
Can you tell me the correct way to implement?
Thanks
Views :
from endless_pagination.decorators import page_template
#page_template("my_index_page.html")
def myview(request,template='my_index.html', extra_context=None):
data = {}
if extra_context is not None:
data.update(extra_context)
myobj = Myobj.objects.all()
data['myobj'] = myobj
return render_to_response(template, data, context_instance=RequestContext(request))
Template :
my_index.html
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="{{ STATIC_URL }}js/endless.js"></script>
<script src="{{ STATIC_URL }}js/endless_on_scroll.js"></script>
{% include page_template %}
my_index_page.html
{% load templatetags %}
<center>
<div>
{% load endless %}
{% paginate myobj %}
{% for obj in myobj %}
{{ obj.name }}
{% endfor %}
{% show_pages %}
</div>
<center>
Here, I seriously beleive that i need to add some classes like endless_more , which the django-endless-documentation missed.
i'm using that on my portal, and it seems fine your code, you just missed one thing
{% show_more %}
that's what actually enables the twitter-style infinite pagination
edit here:
you may want to add this too:
<script type="text/javascript" charset="utf-8">
var endless_on_scroll_margin = 20;
</script>
where "20" is the number of pixels (from the bottom of the page) that triggers the scrolling
you may want to try more than one value till you get the perfect one for your project
see here and here

Detect mobile browser (not just iPhone) in python view

I have a web application written in Django that has one specific page I'd like to implement a mobile version of the template (and slightly different logic) for. I'd like to be able to implement it ala this sudo code:
def(myView)
do some stuff
if user-is-on-a-mobile-device:
do some stuff
return (my mobile template)
else:
do some stuff
return (my normal template)
I don't have a huge amount of time and I'm pretty early on in my coding learning curve :) - I found what looks to be a very powerful pluggable app called bloom for getting mobile device capablities - http://code.google.com/p/django-bloom/wiki/BloomDevice
However it seems to make a request via JSON to get lots of device specs I don't need, which seems a bit inefficient to me.
Does anyone have a suggest simpler method? My detection doesn't need to be 100%, just iPhone, iPod, android, and mainstream devices...
Does the http_user_agent string have some kind of mobile flag I can check for?
Update:
I just found: http://code.google.com/p/minidetector/
Which seems to do exactly what I want, I'm going to test now. Feel free to tell me i'm wrong!
best practice: use minidetector to add the extra info to the request, then use django's built in request context to pass it to your templates like so.
from django.shortcuts import render_to_response
from django.template import RequestContext
def my_view_on_mobile_and_desktop(request)
.....
render_to_response('regular_template.html',
{'my vars to template':vars},
context_instance=RequestContext(request))
then in your template you are able to introduce stuff like:
<html>
<head>
{% block head %}
<title>blah</title>
{% if request.mobile %}
<link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-mobile.css">
{% else %}
<link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-desktop.css">
{% endif %}
</head>
<body>
<div id="navigation">
{% include "_navigation.html" %}
</div>
{% if not request.mobile %}
<div id="sidebar">
<p> sidebar content not fit for mobile </p>
</div>
{% endif %>
<div id="content">
<article>
{% if not request.mobile %}
<aside>
<p> aside content </p>
</aside>
{% endif %}
<p> article content </p>
</aricle>
</div>
</body>
</html>
go for the fork of minidetecor called django-mobi, it includes documentation on how to use it.
https://pypi.python.org/pypi/django-mobi

Categories