In my templates, in many places, I've got repeating parts, like:
<th class="column-title">
<a href="?{% query_transform order_by='x' %}">
{{ objForm.x.label_tag }}</a>
</th>
<th class="column-title">
<a href="?{% query_transform order_by='y' %}">
{{ objForm.y.label_tag }}</a>
</th>
<th class="column-title">
<a href="?{% query_transform order_by='z' %}">
{{ objForm.z.label_tag }}</a>
</th>
Is there a way, to write some "function" to render such html part like: (pseudocode)
in html:
render("x")
render("y")
render("z")
in python:
def render(param):
return " <th class="column-title">
<a href="?{% query_transform order_by='+param+' %}">
{{ objForm'+param+'.label_tag }}</a>
</th>"
PS. I know, that theoreticaly I can prepare ordered list in view, and then iterate over it in a template, but I think it is not a good solution ,as I prefer to build my view, fields order etc on the template side.
You can use the include template tag to insert your common template code where you need it.
<table>
<thead>
<tr>
{% include "table_header.html" with field=objForm.x %}
{% include "table_header.html" with field=objForm.y %}
{% include "table_header.html" with field=objForm.z %}
<tr>
</thead>
</table>
and
<a href="?{% query_transform order_by=field.name %}">
{{ field.label_tag }}
</a>
Related
here i send my details
how can i stop this for example if i run http://127.0.0.1:7000/search_acctable/?txt=Kalpesh but if now i again run my code this is run like http://127.0.0.1:7000/search_acctable/?txt=Kalpesh/search_acctable/?txt=any in django how can i solve this
i need help to solve this problem
views.py
def s_index(request):
current_url = request.build_absolute_uri()
#print(current_url)
src = request.POST.get('txt_search')
#if request.POST['btn_clear']:
# return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # return to previous page
if request.POST['btn_search']:
rec=accmaster.objects.filter(Q(acc_name__contains=src) | Q(acc_city__contains=src)| Q(acc_op__contains=src) ).values() # for filter with and conition onyl put comma if want or condition use pipe sign and Q
if rec.exists():
rec=accmaster.objects.filter(Q(acc_name__contains=src)| Q(acc_city__contains=src)| Q(acc_op__contains=src)).values()
grp_city=accmaster.objects.filter( Q(acc_name__contains=src) | Q(acc_city__contains=src)| Q(acc_op__contains=src)).values('acc_city').annotate(Sum('acc_op')).order_by('acc_city')
template=loader.get_template('index.html')
output=accmaster.objects.filter(Q(acc_name__contains=src)| Q(acc_city__contains=src)| Q(acc_op__contains=src)).values().aggregate(Sum('acc_op'))
context ={
'rec':rec,
'output':output['acc_op__sum'],
'grp_city':grp_city,
}
return HttpResponse(template.render(context,request))
else :
return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # return to previous page
urls.py
from django.urls import path
from . import views
urlpatterns=[
path('',views.index,name='index'),
path('addacc/',views.add,name='addacc'),
path('addacc/addrecord/',views.addrecord,name='addrecord') ,
path('delete/<int:id>',views.delete,name='delete') ,
path('update/<int:id>',views.update,name='update'),
path('update/updaterecord/<int:id>',views.updaterecord,name='updaterecord'),
path('index/',views.s_index,name='s_index'),
#path('',views.form_view,name='mform')
]
index.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function printreport(){
//var divtoprint=document.getElementById("maindiv");
var printcontext=document.getElementById("maindiv").innerHTML;
var originalcontext=document.body.innerHTML;
var nwin=window.open("");
nwin.document.open();
nwin.document.write('<html><head><link rel="stylesheet" media="print" href="{% static 'mystyleprint.css' %}" ></head><body>');
nwin.document.write(printcontext);
nwin.document.write("</body></html>");
//document.write(printcontext);
//document.body.innerHTML=printcontext;
//printWindow.document.write(divtoprint);
nwin.print();
nwin.document.close();
nwin.close();
}
</script>
<link rel="stylesheet" href="{% static 'mystyle.css' %}" >
<link rel="stylesheet" href="{% static 'mystyleprint.css' %}" media="print"> <!-- make seprate css for print document and make media print-->
</head>
<body >
<form action="index/" method="post" >
{% csrf_token %}
<div>
<button type="button">Add Account</button>
<label>Search :</label> <input id="txt_search" name="txt_search" autocomplete="off">
<input type="submit" id="btn_search" name="btn_search" value="Search" onclick="myfunction()">
<input type="button" id="btn_clear" name="btn_clear" value="clear"" onclick="history.back()">
<input type="button" name="btn_print" value="Print" onclick="printreport()">
</div>
<br>
<div id="maindiv">
<table id="maintable">
{% with no="s" %}
<h1> Account List </h1>
<tr>
<th> Sr.No </th>
<th> Name </th>
<th> City </th>
<th> Opening Balance </th>
<th id="thedit"> Edit </th>
<th id="thdelete"> Delete </th>
</tr>
{% for y in grp_city %}
<tr>
<td id="tdcity" colspan=4 style="color:magenta"> {{ y.acc_city }}</td>
{% for x in rec %}
{% if x.acc_city == y.acc_city %}
<tr>
<td style="width:4%" id="srno"></td>
<td>{{ x.acc_name }}</td>
<td style="width:20%"> {{ x.acc_city}}</td>
<td align="right" style="width:10%"> {{ x.acc_op}}</td>
<td style="width:4%" id="redit"> <img src="{% static 'icon/update.png' %}"></td>
<td style="width:4%" id="rdelete"> </td>
</tr>
{% endif %}
{% endfor %}
<td colspan=4 align="right" style="color:magenta; font-size:18px;" >Total: {{ y.acc_op__sum|floatformat:2 }} </td>
<td colspan=2 id="nodisp"> </td>
</tr>
{% endfor %}
<tr>
<td colspan=4 align="right" style="color:red; font-size:20px">Total : {{output|floatformat:2}} </td>
</tr>
</table>
</div>
<p>
</p>
{% endwith %}
</form>
</body>
</html>
i don't know to how to handle it i am new to django
I have a webapp that renders a table of content. Content to be rendered in returned from a backend and Jinja2 is used to cycle through the data to put into appropriate columns and rows. This part works exactly as I expect. A web user performs some operation with data at each row using some buttons on each row.
In case the backend needs to display messages, I use flash(), with the message(s) rendered at the end of the table. Again, as constructed this works as I expect.
However, as the number of rows of the table grow, the place where messages are flash()'d wind up scrolling off the screen. So I was wondering if I could render flash()'d messages at each row. The intent is that the user receives messages as needed directly under each "affected" row.
The main challenge is to hide the message rows until a message needs to be rendered, and I am not 100% sure how best to do that.
An alternative I was considering is to not use flash(), but deliver additional content as needed for "message" rows. I guess I still have the challenge of checking if anything needs to be rendered at a particular row, and how best to do that...
Here's my current HTML:
<table class="styled-table">
<thead>
<tr>
<th>
Filename
</th>
<th width="70%">
Content
</th>
<th>
id
</th>
<th></th> <!-- edit file button -->
<th></th> <!-- delete file button -->
</tr>
</thead>
<tbody>
{% for content in filesContent %}
<tr>
<td>
<!-- file name -->
<div>
{{ content[2] }}
</div>
</td>
<td>
<!-- file content -->
{{ content[3] }}
</div>
</td>
<td>
<div>
{{ content[1] }}
</div>
</td>
<td>
<td>
<!-- edit button -->
<div>
<a id="{{ content[2] }}" href="/editFile/{{ content[2] }}"><img
src="{{ url_for('static', filename='images/edit_small.png') }}"
alt="edit"></a>
</div>
</td>
<td>
<!-- delete button -->
<div>
<a id="{{ content[2] }}" href="/deleteFile/{{ content[2] }}"><img
src="{{ url_for('static', filename='images/trash_small.png') }}"
alt="delete"></a>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
<!--
The backend script returns messages using flash().
-->
<div class="fromBackEnd">
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for message in messages %}
{% if "Error" not in message: %}
<div class="alert alert-info">
{{ message[1] }}
</div>
{% endif %}
{% if "Error" in message: %}
<div class="alert alert-warning">
{{ message[1] }}
</div>
{% endif %}
{% endfor %}
{% endif %}
{% endwith %}
</div>
What I'd like to be to do is something like (HTML simplified for brevity):
<table>
{% for content in filesContent %}
<tr>
... my current td content ...
<tr>
<!-- NEW MESSAGE ROWS TO BE DISPLAYED ONLY IF 'messageContent' not null -->
<tr id="<SOMEUNIQUEID>" style="display:none">
<!-- span across all columns -->
<td>
{{ messageContent }}
</td>
</tr>
{% endfor %}
</table>
This way, messages are rendered right under the "affected" row, and easier for users to see. I could use some javascript to change the display style, but maybe I could just use {% if... %} around the tr??
Any guidance would be greatly appreciated!!!
I'm working on a project and I made a form but when I submit sth it doesn't send it to database although in cmd it shows that request method is post.I really don'tkhow how to deal with it.
thats template code:
{%extends 'base.html'%}
{%block title%}
<title>projects</title>
{%endblock title%}
{%block content%}
<div class="container">
</br>
<form method="post">
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" name="project" placeholder="new project?">
</div>
<button type="submit" class="btn btn-primary">add</button>
</form>
</br>
</br>
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col"> project-title</th>
<th scope="col">update</th>
<th scope="col">delete</th>
<th scope="col">divide</th>
</tr>
</thead>
<tbody>
{% for obj in all_projects %}
<tr>
<td>{{ obj.proTitle }}</td>
<td>{{ obj.done }}</td>
<td>Delete</td>
<td>Devide</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{%endblock content%}
any advise will be greatly appreciated:))
I solved it ;
in the input tag i put name="project" but the attribute that I defined in my model was "proTitle"
so when I chnged it the problem solved.
Template file that is located in one of the apps:
{% extends 'base_well_surfer.html' %}
{% block content %}
<table class="table table-bordered table-hover">
<thead class="thead-dark">
<tr>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr><td>Back to home</td></tr>
<tr><td>Dynamically search in Well Surfer Database</td></tr>
</tbody>
</table>
{% endblock %}
my goal is to have a link that takes me back to the homepage.
Is there a more elegant way of creating the link other than hardcoding the "http://" in front of the "{{ request.get_host }}" in the template?
Thanks
It maybe a little naive question but I have been trying to understand how I can use the new Date Based views in django, but without an example, I am at a dead end. What I want to do is to show all my blog entries on a page (with pagination) and in the side navigation I want to show the archiving done according to year and month.
What I want is very basic and can be seen in the picture attached below.
If somebody can provide me an example then it would be really great. I can handle the templates, but just need to know how to use the class based generic views. I haven't really really used much if generic views.
The simplest example:
views.py
from django.views.generic.dates import MonthArchiveView
from myapp.models import Article
urlpatterns = patterns('',
url(r'^articles/monthly/$',MonthArchiveView.as_view(
model=Article,
paginate_by=12,
date_field='publish_date',
template_name='archive_templates/monthly.html',
),name="monthly"),
)
You need to call the view with a correct day and month, otherwise you'll get an exception. Default arguments are year in Y format, and month in b (lowercase short month name).
Example call articles/monthly/?year=2012&month=feb
Here is a sample archive_templates/monthly.html you can use.
I am using css classes from the excellent twitter bootstrap framework. Highly recommended!
This snippet goes through the available months:
Archive for {{ month|date:"F" }} {{ month.year }}<br />
<div class="pagination pull-left">
<ul>
{% if previous_month %}
<li class="prev">
<a href="{% url monthly %}?year={{ previous_month|date:"Y" }}&month={{ previous_month|date:"b" }}">
← {{ previous_month|date:"M Y" }}
</a>
</li>
{% endif %}
{% if next_month %}
<li class="next">
<a href="{% url monthly %}?year={{ next_month|date:"Y" }}&month={{ next_month|date:"b" }}">
{{ next_month|date:"M Y" }} →</a>
</li>
{% endif %}
</ul>
</div>
{% endif %}
This snippet does the pagination:
{% if is_paginated %}
<div class="pagination pull-right">
<ul>
<li class="{% if page_obj.has_previous %}prev {% else %} prev disabled {% endif %}">
←</li>
<li class="disabled"><strong>{{ page_obj.number }} of {{ paginator.num_pages }}</strong></li>
<li class="{% if page_obj.has_next %}next{% else %} next disabled {% endif %}">
→
</li>
</ul>
</div>
{% endif %}
The actual list of objects is very simple to iterate over:
<table class="zebra-striped" width="100%">
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Author</th>
<th>Published On</th>
</tr>
</thead>
<tbody>
{% for obj in object_list %}
<tr>
<th>{{ forloop.counter }}</th>
<td>{{ obj.title }}</td>
<td>{{ obj.author }}</td>
<td>{{ obj.publish_date|date:"d/m/Y" }}</td>
</tr>
{% endfor %}
</tbody>
</table>
From here you should be able to figure out how to develop your archive menu.