Why my paging bootstrap style does not work? - python

I practice "Flask Web Development"blog article when paging links paging,bootstrap style does not work.But the other can be used.I was using macros import, hope that other places can be common this.Is it necessary to add at import time? .
somebody help me.
this is index.html
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% import '_macros.html' as macros %}
{% block head %}
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% block scripts %}
{{ super() }}
<script type="text/javascript">
$('[data-spy="scroll"]').each(function () {
var $spy = $(this).scrollspy('refresh')
})
</script>
{% endblock %}
{% block styles %}
{{ super() }}
<style type="text/css">
body {
background-color: #ffffff;
/*background-color: #F0F0F0;*/
position: relative;
}
.header {
background-color: #FFFFFF;
background-attachment: scroll, fixed;
background-position: top left, top left;
background-repeat: repeat, no-repeat;
background-size: auto, auto 100%;
color: rgba(255, 255, 255, 0.5);
height: 100%;
left: 0;
padding: 8em 4em 0 0;
position: fixed;
text-align: right;
top: 0;
width: 20%;
padding: 0 0 0 0;
}
.img {
background-color: #235F2A;
height: 23.6076%;
width: 61.8%;
margin-top: 14.5924%;
margin-left: 19.1%;
margin-right: 19.1%;
padding: 0 0 0 0;
}
.breadcrumb {
margin-left: 25.28%;
margin-top: 3%;
width: 68.33%;
background-color: #FFFF93;
}
.sketcho {
width: 83.7%;
background-color: #ffffff;
opacity: 1;
margin-left: 7.72%;
margin-top: 8.5%;
}
.container-fluid {
margin-left: 20%;
padding-left: 0px;
padding-right: 0px;
}
.sketch {
width: 83.7%;
background-color: #ffffff;
opacity: 1;
margin-left: 7.72%;
margin-top: 1%;
}
section {
padding-left: 17px;
padding-right: 17px;
}
.paging {
margin-left: auto;
text-align: center
}
.center {
margin-top: 320px;
height: 35px;
}
.row_button {
width: 35px;
height: 35px;
float: left;
}
</style>
{% endblock %}
{% endblock %}
{% block title %}Index{% endblock %}
{% block page_content %}
<body id="top">
<div class="container-fluid">
{% for Article in Articles %}
<div class="row sketch">
<section id="one">
<header class="major">
{{ Article.head }}
</header>
<p>{{ Article.body }}</p>
<ul class="actions">
<li>
<button type="button" class="btn btn-info">Learn More</button>
</li>
</ul>
</div>
{% endfor %}
<div class="row paging">
{{ macros.pageination_widget(pageination, '.index') }}
</div>
</div>
<script src="{{ url_for('static',filename='js/jquery-3.2.1.min.js') }}"></script>
<script src="{{ url_for('static',filename='js/bootstrap.min.js') }}"></script>
</body>
{% endblock %}
_macros.html
{% macro pageination_widget(pageination, endpoint) %}
<nav aria-label="Page navigation">
<ul class="pageination">
<li {% if not pageination.has_prev %} class="disabled" {% endif %}>
<a href="{% if pageination.has_perv %}{{ url_for(endpoint, page=pageination.page - 1, **kwargs) }}{% else %}#{% endif %}">
«</a>
</li>
{% for page in pageination.iter_pages() %}
{% if page %}
{% if page == pageination.page %}
<li class="active">
{{ page }}
</li>
{% else %}
<li>{{ page }}</li>
{% endif %}
{% else %}
<li class="disabled"></li>
{% endif %}
{% endfor %}
<li {% if not pageination.has_next %} class="disabled" {% endif %}>
»
</li>
</ul>
</nav>
{% endmacro %}

It seems like you have a typo on your class names.
Try <ul class="pagination"> instead of <ul class="pageination">.
You can find the full docs for the classes to use here:
https://getbootstrap.com/docs/3.3/components/#pagination-default

Related

Page not found (404) No cart matches the given query

The error is raised :
Page not found (404) No cart matches the given query.
Request Method: GET Request
URL: http://127.0.0.1:8000/change_quan?cid=1&quantity=2
Raised by: myapp.views.change_quan
when i am trying to save quantity value in database
i tried but this error raised always
my views.py
def productcart(request):
context = {}
items = cart.objects.filter(user__id=request.user.id,status=False)
context["items"] = items
if request.user.is_authenticated:
if request.method=="POST":
pid = request.POST["pid"]
qty = request.POST["qty"]
img = request.POST["img"]
dis_price = request.POST["dis_price"]
is_exist = cart.objects.filter(product__id=pid,user__id=request.user.id,status=False)
if len(is_exist)>0:
context["msg"] = "item already exist in cart"
context["cls"] = "alert alert-warning"
else:
product = get_object_or_404(Product,id=pid)
usr = get_object_or_404(User,id=request.user.id)
c = cart(user=usr,product=product,quantity=qty,image=img,total_price=dis_price)
c.save()
context["msg"] = "{} Added in cart".format(product.name)
context["cls"] = "alert alert-success"
else:
context["status"] = "Please login first to add products to cart"
return render(request,'E-commerce-cart.html',context)
def get_cart_data(request):
items = cart.objects.filter(user__id=request.user.id,status=False)
sale,total,quantity=0,0,0
for i in items:
sale+=i.product.discount
total+=i.product.price
quantity+=i.quantity
res={
"total":total,"offer":sale,"quan":quantity
}
return JsonResponse(res)
def change_quan(request):
qty = request.GET["quantity"]
cid = request.GET["cid"]
print(request.GET)
cart_obj = get_object_or_404(cart,id=cid)
cart_obj.quantity = qty
cart_obj.save()
return HttpResponse(1)
my urls.py
"""emarket URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from os import name
from django.contrib import admin
from django.urls import path
from myapp import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.home,name='home'),
path('shop/',views.shop,name='shop'),
path('login/',views.create_user,name='login'),
path('logout/',views.user_logout,name='logout'),
path('cart/',views.productcart,name='cart'),
path('checkout/',views.checkout,name='checkout'),
path('product_detail/',views.product_detail,name='prodct-detail'),
path('find_us/',views.find_us,name='find'),
path('blog/',views.blog,name='blog'),
path('base/',views.base),
path('api/categories',views.all_categories,name="all_categories"),
path('api/brand',views.brand,name="brand"),
path('api/products',views.product_filter_api,name="product_filter_api"),
path('user_check/',views.check_user,name="check_user"),
path('filter_product/',views.filter_product,name="filter_product"),
path('add_to_favourite/',views.add_to_favourite,name="add_to_favourite"),
path('all_favourites/',views.all_favourites,name="all_favourites"),
path('forgotpass',views.forgotpass,name="forgotpass"),
path('resetpass',views.resetpass,name="resetpass"),
path('get_cart_data',views.get_cart_data,name="get_cart_data"),
path('change_quan',views.change_quan,name='change_quan'),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
my models.py
class cart(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.ForeignKey(Product,on_delete=models.CASCADE)
image = models.ImageField(default=False)
total_price=models.FloatField(default=False)
quantity = models.IntegerField()
status = models.BooleanField(default=False)
added_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
def __str__(self):
return self.user.username
my html code
{% extends 'base.html' %}
{% block head %}
<style>
.k{height: 1px;background-color: rgb(211, 207, 207);}
.s{color:rgb(240, 240, 240);
letter-spacing: 3px;
font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
font-weight: 400;}
.cncl_icn{
float: left;
margin: 15px;
padding-top: 10px;
}
.a:hover{
background-color:rgba(152, 209, 255, 0.705);color: rgb(255, 255, 255);box-shadow:0px 0px 7px 7px rgba(204, 201, 201, 0.5) ;
}
#media screen and (max-width:680px){
.b{opacity: 0;}
/* .v{position: absolute;top: 5px;} */
.s{font-size: 15px;}
}
#media screen and (min-width:1024px){
.s{font-size: 20px;}
}
</style>
{% endblock %}
{% block body %}
{% if user.is_superuser %}
<div class="container-fluid "></div>
<h1 class="jumbotron my-5" >you are not Allowed here</h1>
{% else %}
{% if status %}
<h1 class="jumbotron my-5">{{status}}</h1>
{% else %}
{% if msg %}
<div class="{{cls}}">{{msg}}</div>
{% endif %}
<div class="row v " style="margin-right: 0%;">
<div class="col-lg-7" >
<div class="row text-center p-3 b" style="background-color: rgba(2, 184, 184, 0.863); background-attachment: fixed;">
<div class="col-md-3 "> <h3 class="s">Product</h3></div>
<div class="col-md-3 "><h3 class="s">Price</h3></div>
<div class="col-md-3 "><h3 class="s">Qantity</h3></div>
<div class="col-md-3 "><h3 class="s">Total</h3></div>
</div>
{% for i in items %}
<div class="row a border-bottom" id="col{{i.product.id}}">
<div class="col-md-3 text-center " >
<i class="far fa-times-circle cncl_icn" id="cross{{i.product.id}}" style="font-size: 30px;"></i>
<img class="mt-4" src="/media/{{i.image}}" alt="check ur internet!" height="150px">
<h4 class="ml-5" style="color: black;">{{i.product.name}}</h4>
<p class="ml-5">Size:{{i.product.size}} , color:{{i.product.color}}</p>
</div>
<div class="col-md-3 text-center mt-5">
{%if i.total_price < i.product.price%}
<del style="font-weight: bold; color: grey;" >${{i.product.price}}</del> $<p class="d-inline" style="font-weight: bold;" id="price{{i.product.id}}">{{i.total_price}}</p>
{% else %}
$<p class="d-inline" style="font-weight: bold;" id="price{{i.product.id}}">{{i.product.price}}</p>
{% endif %}
</div>
<div class="col-md-3 text-center">
<div class="form-group mt-4">
<div class="input-group">
<div class="input-group-btn ">
<button id="down" class="btn btn-default" onclick="change_quan('{{i.product.id}}','minus')" style="font-size: 25px;background: none;border: none;font-weight: bold;">-</button>
</div>
<input type="number" id="cart{{i.product.id}}" class="form-control text-center pt-3" value="{{i.quantity}}" style="width: 30px;border: none;font-weight: bold;background: none;">
<div class="input-group-btn">
<button id="up" class="btn btn-default" onclick="change_quan('{{i.product.id}}','plus')" style="font-size: 25px;background: none;border: none;font-weight: bold;">+</button>
</div>
</div>
</div>
</div>
<div class="col-md-3 mt-5 text-center">
{%if i.total_price < i.product.price %}
$<p class="d-inline" style="font-weight: bold;" id="total{{i.product.id}}">{{i.total_price}}</p>
{% else %}
$<p class="d-inline" style="font-weight: bold;" id="total{{i.product.id}}">{{i.product.price}}</p>
{% endif %}
</div>
</div>
<script>
$(function() {
$("#cross{{i.product.id}}").hover(function() {
$("#cross{{i.product.id}}").toggleClass("fas fa-times-circle").toggleClass("far fa-times-circle")
})
// to remove product from cart
$("#cross{{i.product.id}}").confirm({
title: 'Confirm',
content: 'Are you sure to remove this product from cart',
theme: 'modern',
buttons:{
confirm: function() {
$('#col{{i.product.id}}').remove()
},
cancel: function (){}
}
})
})
</script>
{% endfor %}
</div>
<script>
function grandTotal(){
$.ajax({
url:"{% url 'get_cart_data' %}",
type:'get',
success:function(data){
p = Math.round((data.offer/data.total)*100,2)
$('.item_total').html("&dollar;"+data.total)
$('#offer').html("&dollar;"+data.offer)
$('#per').html("("+p+"%)")
$('#quantity').html(data.quan)
c = (data.total)-(data.offer)
$('#grand_Total').html("&dollar;"+c)
}
})
}
grandTotal()
function change_quan(id,action){
let old = $("#cart"+id).val();
quan = 0
if(action=="plus"){
quan+=parseInt(old)+1
$('#total'+id).text( parseFloat($('#total'+id).text()) + parseFloat($('#price'+id).text()))
}
else{
quan+=parseInt(old)-1
$('#total'+id).text( parseFloat($('#total'+id).text()) - parseFloat($('#price'+id).text()))
}
$("#cart"+id).val(quan);
$.ajax({
url:"{% url 'change_quan' %}",
type:"get",
data:{cid:id,quantity:quan},
success:function(data){
alert(data)
}
});
}
</script>
<div class="col-md-5 text-center py-5" style="background-color: rgba(255, 176, 218, 0.397);">
<div id="cartt"></div>
<div class="row">
<img src="/static/Images/estore1.png" alt="" height="300px" style="margin: auto;">
</div>
<div class="pb-3 " style="font-size:30px;font-weight: bold;">--------------------</div>
<h4 class="pt-3" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">Total: <span style="font-size: 28px;" class="item_total"></span></h4>
<h4 class="pt-1" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">Quantity: <span style="font-size: 28px;" id="quantity"></span><span style="text-transform: none;"> Items</span></h4>
<h4 class="pt-1" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">You Saved: <span style="font-size: 28px;" id="offer"></span><span class='text-success'style="font-size: 20px;" id="per"></span></h4>
<h4 class="py-1" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">Grand Total: <del style="font-size: 25px; color:grey;" class="item_total"></del><span style="font-size: 28px;" id="grand_Total"></span></h4>
<h4 class="pt-3">Shipping charges will calculated at checkout</h4>
<form class="pt-3" action="" >
<!-- <input type="text" placeholder="Coupon code.." name="cod" class="mt-3 text-center" style="letter-spacing: 2px;font-size: 20px;border-radius: 25px;width: 250px;height: 47px;background-color: rgb(255, 255, 255);border:2px solid thistle;" >
<input type="submit" class="mt-3" value="Apply Code"name="acd" style="letter-spacing: 2px;font-size: 25px;border-radius: 25px;border: none;width: 250px;height: 45px;background-color: rgb(161, 158, 158);color: rgb(255, 255, 255);" > -->
<input type="submit" value="CHECKOUT" name="che" class="mt-5" style="letter-spacing: 2px;font-size: 25px;border-radius: 25px;border: none;width: 250px;height: 45px;background-color: black;color: rgb(255, 255, 255);" >
</form>
</div>
</div>
{% endif %}
</div>
{% endif %}
{% endblock %}
if data does not exist 'get_object_or_404' will throw 404 error, As per your request You are trying to retrieve data with primary key 1, but data is not available
That’s why you get this error. so please check you table or try with other pk value
def change_quan(request):
qty = request.GET["quantity"]
cid = request.GET["cid"]
print(request.GET)
cart_obj = get_object_or_404(cart,id=cid) # please check this cid value
cart_obj.quantity = qty
cart_obj.save()
return HttpResponse(1)
get_object_or_404 is not the correct choice here. Since object with id=cid was not found in database, 404 error was raised. This is the expected behaviour of get_object_or_404.
Did you mean to use get_or_create object incase the object that is trying to be fetched from database is not found?

How to run python code in html page using django

I am learning web development using django framework. I have little trouble in running python code in an html page. I need to iterate through a list of strings which basically contains the paths of images that I want to show in a carousel. I am getting this error "Invalid block tag on line 83: 'with.i', expected 'endblock'. Did you forget to register or load this tag?" in galleryPage.html file when I try to open that page. These are the few lines of code that I've written so far
/views.py/
def galleryPage(request):
from os import listdir
from os.path import isfile, join
ImageList = []
imagePath = "static/images/gallery/"
for f in listdir(imagePath):
temp = join(imagePath, f)
if isfile(temp):
temp = "../" + temp
ImageList.append(temp)
return render(request, "galleryPage.html", {"imageList": ImageList})
/galleryPage.html/
{% extends 'base.html' %}
{% block title %} GALLERY {% endblock %}
{% block slideshow %}
* {box-sizing: border-box;}
body {font-family: Verdana, sans-serif;}
.mySlides {display: none;}
img {vertical-align: middle;}
/* Slideshow container */
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
/* Caption text */
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
/* Number text (1/3 etc) */
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
/* The dots/bullets/indicators */
.dot {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active {
background-color: #717171;
}
/* Fading animation */
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
#-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
#keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
/* On smaller screens, decrease text size */
#media only screen and (max-width: 300px) {
.text {font-size: 11px}
}
{% endblock %}
{% block content %}
<div class="slideshow-container">
{% with.i = 0 %}
<indent>
{{ for image in imageList.0: }}
{% ++i %}
<div class="mySlides fade">
<div class="numbertext"> {% i %} / {{ imageList.size() }} </div>
<img src="{{ image }}" style="width:100%">
<div class="text">Caption Text</div>
</div>
</indent>
{% endwith %}
</div>
<br>
<div style="text-align:center">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
<script>
var slideIndex = 0;
showSlides();
function showSlides() {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {slideIndex = 1}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
setTimeout(showSlides, 2000); // Change image every 2 seconds
}
</script>
{% endblock %}
{% with.i = 0 %}
should be
{% with i=0 %}
Why do you have imageList.0 instead of imageList?
Also, I think you may want to consider combining your current "with" and "for" into one "for" loop like in the docs I posted above:
{% for key, image in imageList %}
<div class="mySlides fade">
<div class="numbertext"> {% key %} / {{ imageList.size() }} </div>
<img src="{{ image }}" style="width:100%">
<div class="text">Caption Text</div>
</div>
{% endfor %}
This way you won't need to increment i yourself and you take away some complexity (and some sources of errors).

Django - chart won't display values correctly

The goal here is to show each bar corresponding to association and total members as displayed below:
What I get is this one big block with no value.
Seems that no one has the same issue here that I have been looking for.
Still a newbie so appreciate all your help & guidance, folks!
models.py
class Member(models.Model):
member_no = models.AutoField(primary_key=True)
association = models.ForeignKey('Association')
...
class Association(models.Model):
asoc_name = models.CharField(max_length=50, null=True, blank=True)
class Meta:
db_table = 'Association'
def __str__(self):
return self.asoc_name
def __unicode__(self):
return self.asoc_name
class AssociationSummary(Association):
class Meta:
proxy = True
verbose_name = 'Association Summary'
verbose_name_plural = 'Association Summary'
admin.py
#admin.register(AssociationSummary)
class ChartAssociationAdmin(admin.ModelAdmin):
change_list_template = 'admin/chart_association.html'
def changelist_view(self, request, extra_context=None):
response = super(ChartAssociationAdmin, self).changelist_view(
request,
extra_context=extra_context,
)
try:
qs = response.context_data['cl'].queryset
except (AttributeError, KeyError):
return response
metrics = {
'association': Count('asoc_name'),
'total': Sum('member'),
}
response.context_data['summary'] = list(
qs.values('asoc_name', 'member').annotate(**metrics)
)
response.context_data['summary_total'] = dict(
qs.aggregate(**metrics)
)
summary_over_time = qs.values('asoc_name', 'member').annotate(total=Sum('member'))
summary_range = summary_over_time.aggregate(
low=Min('total'),
high=Max('total'),
)
high = summary_range.get('high', 0)
low = summary_range.get('low', 0)
response.context_data['summary_over_time'] = [{
'asoc_name': x['asoc_name'],
'total': x['total'] or 0,
'pct':\
((x['total'] or 0) - low) / (high - low) * 100
if high > low else 0,
} for x in summary_over_time]
return response
chart_association.html
{% extends 'admin/change_list.html' %}
{% block content_title %}
<h1> Association Summary </h1>
{% endblock %}
{% block result_list %}
<div class=”results”>
<table>
<thead>
<tr>
<th>
<div class=”text”>
<span>Association</span>
</div>
</th>
<th>
<div class=”text”>
<span>Total Members</span>
</div>
</th>
</tr>
</thead>
<tbody>
{% for row in summary %}
<tr class="{% cycle 'row1' 'row2' %}">
<td> {{ row.asoc_name }} </td>
<td> {{ row.total }} </td>
</tr>
{% endfor %}
</tr>
<tr style="font-weight:bold; border-top:2px solid #DDDDDD;">
<td> Total </td>
<td> {{ summary_total.total }} </td>
</tr>
</tbody>
</table>
</div>
<br>
<h2> Association Chart </h2>
<style>
.bar-chart {
display: flex;
justify-content: space-around;
height: 160px;
padding-top: 60px;
overflow: hidden;
}
.bar-chart .bar {
flex: 100%;
align-self: flex-end;
margin-right: 2px;
position: relative;
background-color: #79aec8;
}
.bar-chart .bar:last-child {
margin: 0;
}
.bar-chart .bar:hover {
background-color: #417690;
}
.bar-chart .bar .bar-tooltip {
position: relative;
z-index: 999;
}
.bar-chart .bar .bar-tooltip {
position: absolute;
top: -60px;
left: 50%;
transform: translateX(-50%);
text-align: center;
font-weight: bold;
opacity: 0;
}
</style>
<div class="results">
<div class="bar-chart">
{% for x in summary_over_time %}
<div class="bar" style="height:{{x.pct}}%">
<div class="bar-tooltip">
{{ x.total | default:0 }}<br>
{{ x.asoc_name }}
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
{% block pagination %}{% endblock %}

Dynamically increase the height of the div container

I have two div containers for which I have fixed the height and width. One of the containers holds the body of the blogpost and other holds the list of all the posts created. Since, body of a blogpost or list of posts can be larger than the size of their div container. So, I want to dynamically increase container's size when they exceed its size. How can I achieve it either using css or javascript?
css file
body {
background-color:#FFCCFF;
}
#container {
position:absolute;
top:50px;
left:100px;
right:100px;
bottom:50px;
}
#content {
margin-top:20px;
padding:0;
width:70%;
height:550px;
border:1px solid black;
background-color: #282828 ;
color:white;
}
#footer {
width:100%;
height:50px;
border:1px solid black;
}
#rightnav {
position:absolute;
top:18px;
right:20px;
width:275px;
height:550px;
background-color: #282828 ;
}
#rightnav p {
margin:0px 0 10px 0px;
padding:0px;
color:#CCCCFF;
}
#rightnav h2 {
text-align: center;
background-color: #000000;
margin:0;
color:#FF9900;
}
#rightnav a {
text-decoration: none;
}
#posts {
padding:0;
width:80%;
border:1px solid black;
}
#posts h2 {
margin:0;
padding:0;
}
#posts p {
margin:5px;
padding:0;
}
#content a {
text-decoration: none;
background-color: none;
color:black;
}
base.html #every other html files inherit from this base file
{% load staticfiles %}
<html>
<head>
<link rel="stylesheet" href="{% static 'css/base.css' %}" type="text/css">
</head>
<body>
<div id = "container" style="clear:both;">
<div id = "content">
{% block post %}
{% endblock %}
</div>
<div id = "rightnav">
<h2>Popular Posts</h2>
{% block popular_posts %}
{% endblock %}
</div>
</div>
</body>
</html>
post.html #the template which deals with showing posts
{% extends "blog/base.html" %}
{% block post %}
{% load django_markdown %}
<h2>{{post.title}}</h2>
{{ post.body|markdown }}
{% endblock %}
{% block popular_posts %}
{% for post in posts %}
<p>{{ post.title }}</p>
{% endfor %}
{% endblock %}
Adding to Marcanuy's answer, you have to remove the bottom:50px given to the #container div.
And by removing position:absolute from unwanted places will make your css neat. If you want to position your div side by side, you can use display:flex for your parent (#container) div.
EDIT: Have also removed the position:absolute property and have added margin:50px to make your div center-aligned. (You can also use padding property)
Refer : JsFiddle
#container {
position:absolute;
top:50px;
left:100px;
right:100px;
}
#content {
padding:0;
width:70%;
min-height:550px;
border:1px solid black;
background-color: #282828 ;
color:white;
}
#rightnav {
width:275px;
min-height:550px;
background-color: #282828 ;
}
Change your height with min-height, this will make your containers have at least the specified height, then they will grow and fit their content needs.
#rightnav {
min-height:550px;
}
#content {
min-height:550px;
}

How can i include a view function in django template?

I am new in django. So i need a help for including a view function within Template. I am searching but i am tired for finding my expectation. i want to use only django template tag. Would you please help me?
{View.py
def singUpLunch(request):
query_results = Menu.objects.all()
form=SingUpForm(request.POST or None)
if form.is_valid():
save_it=form.save(commit=False)
save_it.save()
messages.success(request,'Thanks for your co-operation')
return render_to_response('singUp.html',locals(),context_instance=RequestContext(request))
}
{my model
class SingUp(models.Model):
employee_id = models.AutoField(unique=True,primary_key=True)
name = models.CharField(max_length=20,choices=STATUS_CHOICES)
email = models.EmailField()
date = models.DateField()
lunch = models.BooleanField()
class Meta:
unique_together = ["name", "email","date"]
ordering = ['-date']
USERNAME_FIELD = 'employee_id'
REQUIRED_FIELDS = ['mobile']
def __unicode__(self):
return smart_unicode(self.email)
}
class SingUp(models.Model):
employee_id = models.AutoField(unique=True,primary_key=True)
name = models.CharField(max_length=20,choices=STATUS_CHOICES)
email = models.EmailField()
date = models.DateField() # auto_now_add=True, blank=True default=date.today(),blank=True
lunch = models.BooleanField()
class Meta:
unique_together = ["name", "email","date"]
ordering = ['-date']
USERNAME_FIELD = 'employee_id'
REQUIRED_FIELDS = ['mobile']
def __unicode__(self):
return smart_unicode(self.email)
my Template
{% load url from future %}
{% block content %}
{% if not email %}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Log in</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style>
body
{
margin: 0;
padding: 0;
color: #555;
font: normal 12pt Arial,Helvetica,sans-serif;
background:#ffffff url(check2.jpg) repeat-x;
width: 130%;
height: 100%;
position: fixed;
top: 40px;
left: 480px
}
.span3.well {
min-height: 20px;
padding: 19px;
margin-bottom: 20px;
background-color: #f5f5ff;
border: 1px solid #e3e3e3;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
}
</style>
</head>
<body>
<head><div class='page-header pagination-centered'><img src=/static/logo.png class='img-rounded pagination-centere' /></div> </head>
{{ state }}
<div class="span3 well" style="height: auto;margin-left: 1.7%;width: 30%;">
<h2>Please Login
New User: &nbsp<a href="/signup/">
SignUp</a></h2>
<div class="leftpane">
<form action="" method="post"> {% csrf_token %}
{% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% endif %}
Email:
<input type="text" name="email" value="{{ email}}" /><br /><br />
password:
<input type="password" name="password" value="" /><br /><br />
<input type="submit" value="Log In" />
</form>
</div>
<div class="aboutus_portion">
</div>
</div>
<!-- <div id="rightcontent">
<li class=" dir"><h3>Admin</h3> </li>
</div>
-->
</body>
</html>
{% else %}
{% include 'singUpLunch' %} # here i want to call the view singUpLunch function
{% endif %}
{% endblock %}
You can see this Django custom template tags
Django expects template tags to live in a folder called 'templatetags' that is in an app module that is in your installed apps...
/my_project/
/my_app/
__init__.py
/templatetags/
__init__.py
my_tags.py
#my_tags.py
from django import template
register = template.Library()
#register.inclusion_tag('other_template.html')
def say_hello(takes_context=True):
return {'name' : 'John'}
#other_template.html
{% if request.user.is_anonymous %}
{# Our inclusion tag accepts a context, which gives us access to the request #}
<p>Hello, Guest.</p>
{% else %}
<p>Hello, {{ name }}.</p>
{% endif %}
#main_template.html
{% load my_tags %}
<p>Blah, blah, blah {% say_hello %}</p>
The inclusion tag renders another template, like you need, but without having to call a view function. Hope that gets you going.

Categories