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
Related
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 %}
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)
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.
I need to send the value of the selected option in a drop down to the views.
Html code of template is as follows:
<select name="version" id="version" onchange="location = this.value;">
<option>Select version to compare with</option>
{%for ver in version_list%}
<option value={{ver}} href="{% url 'process_data' ver %}">{{ver}}</option>
{% endfor %}
</select>
Above html code is giving me the following error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/index/11.5.1.18900-96
http://127.0.0.1:8000/index/11.5.1.18900-97
Using the URLconf defined in Piechart_Excel.urls, Django tried these URL patterns, in this order:
admin/
index/
process_data/<str:ver> [name='process_data']
The current path, index/11.5.1.18900-96, didn't match any of these.
However, if I am sending the value as follows i.e. without any drop down:
{{ver}}
everything is working as expected.
Urls.py file content is as follows:
from django.urls import path
from fusioncharts import views
urlpatterns = [
path('index/', views.index, name='index'),
path('process_data/<str:ver>', views.process_data, name='process_data'),
]
Can anyone tell why is it not working in the case of drop down but working otherwise? If we have to send any value from the html template using drop down, then how to do so?
Thanks.
Your using a link inside an option tag, which I argue there are better ways however ... you can try this.
<select name="version" id="version" onchange="location = this.value;">
<option>Select version to compare with</option>
{%for ver in version_list%}
**<option value="{% url 'process_data' ver %}">{{ver}}</option>**
{% endfor %}
</select>
You also might have to edit the onchange event
onChange="window.location.href=this.value"
If that doesn't work then you could convert to links and then convert it into a dropdown menu using css or a css framework.
<ul>
<li>{{ver}}</li>
<ul>
Complete Dropdown example
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Select version to compare with
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
{%for ver in version_list%}
<a class="dropdown-item" href="{% url 'process_data' ver %}">{{ver}}</a>
{% endfor %}
</div>
</div>
This is assuming you import bootstrap see the following links for details:
https://getbootstrap.com/docs/4.0/getting-started/introduction/
https://getbootstrap.com/docs/4.0/components/dropdowns/
urls.py:
url(r'^signin_client$', views.signin_client, name='signin_client') # normal view,
url(r'^signup_owner$', SignupOwnerWizard.as_view()), # wizard view
In a 'normal view' case: <a href='{% url "myapp.views.signin_client" %}'> works.
But I can't figure how to do the same thing for my "wizard view". Of course, I don't want to hardcode the url.
Add name to the pattern:
url(r'^signup_owner$', SignupOwnerWizard.as_view(), name='signup_owner'),
And than use the name in {% url %} tag:
<a href='{% url "signup_owner" %}'>
If you use namespaces you would need a namespace prefix:
<a href='{% url "mynamespace:signup_owner" %}'>