I am trying to implement end less pagination in Django App but stuck at how to implement twitter like end less scrolling :
My models.py
from django.db import models
from django.contrib import admin
#------------------------------------------------------------------------------
class Book(models.Model):
name = models.CharField(max_length=50)
pub_date = models.DateField(auto_now_add=True)
class bookAdmin(admin.ModelAdmin):
"""Book admin class"""
list_display = ('name','pub_date')
ordering = ('name',)
admin.site.register(Book,bookAdmin)
My views.py :
from models import Book
from django.template import RequestContext
from django.shortcuts import render_to_response
#------------------------------------------------------------------------------
def latest_books(request,template = 'latest_books.html',
page_template = 'latest_books_page.html' ):
context = {}
book_list = Book.objects.order_by('-pub_date')
context.update( {'book_list': book_list, 'page_template': page_template,} )
# override the template and use the 'page' style instead.
if request.is_ajax():
template = page_template
return render_to_response(
template, context, context_instance=RequestContext(request) )
My 'latest_books.html' template :
<html><head><title>Books</title></head>
<body>
<h1>Books</h1>
{% block js %}
{{ block.super }}
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.2.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="http://yourjavascript.com/337923491/endless.js" charset="utf-8"></script>
<script type="text/javascript" src="http://yourjavascript.com/151379951/endless-pagination.js"></script>
<script>$.endlessPaginate();</script>
{% endblock %}
{% block content %}
<div class="endless_page_template">
{% include page_template %}
</div>
{% endblock %}
</body></html>
My latest_books_page.html :
<h2>Viewing All Entries</h2>
{% load endless %}
<div>
<ul>
{% paginate book_list %}
{% for book in book_list %}
<li>{{ book.name }}</li> {{ book.pub_date }}
{% endfor %}
{% show_pages %}
</ul>
</div>
I am facing two issues first if i use {{ block.super }} as given in tutorial .Django gives this error 'BlockNode' object has no attribute 'context' and if i remove {{ block.super }}. I get simple pagination with next and previous functionality .
Can someone help me please. I want to implement on scroll load pagination...
Please try out my code:
views.py :
from models import Book
from django.template import RequestContext
from django.shortcuts import render_to_response
#------------------------------------------------------------------------------
def latest_books(request,template = 'latest_books.html',
page_template = 'latest_books_page.html' ):
context = {}
book_list = Book.objects.order_by('-pub_date')
context.update( {'book_list': book_list, 'page_template': page_template,} )
# override the template and use the 'page' style instead.
if request.is_ajax():
template = page_template
return render_to_response(
template, context, context_instance=RequestContext(request) )
latest_books.html :
<html><head><title>Books</title></head>
<body>
<h1>Books</h1>
<h2>Viewing All Entries</h2>
<div class="endless_page_template">
{% include page_template %}
</div>
{% block js %}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="{{ STATIC_URL }}js/endless_on_scroll.js"></script>
<script src="{{ STATIC_URL }}js/endless-pagination.js"></script>
<script>
$.endlessPaginate({paginateOnScroll: true,
endless_on_scroll_margin : 10,
paginateOnScrollChunkSize: 5
});</script>
{% endblock %}
</body></html>
latest_books_page.html :
{% load endless %}
{% paginate 10 book_list %}
{% for book in book_list %}
{{ book.name }}<br> {{ book.pub_date }}<br><br><br>
{% endfor %}
{% show_more "even more" "working" %}
Try out and let me know ... and enter 20-30 entries into your DB to check it out properly ...
You have to include page_template before call the {{block.super}}
<h2>Entries:</h2>
{% include page_template %}
{% block js %}
{{ block.super }}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="{{ STATIC_URL }}endless_pagination/js/endless-pagination.js"></script>
<script>$.endlessPaginate();</script>
{% endblock %}
Related
When I create a new post with an image, everything is fine, but if I edit it, I want to delete the image using the "clear" button, then this error appears, and if I change, then nothing changes, but there are no errors
here is models.py
`
from django.db import models
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
body = models.TextField()
header_image = models.ImageField(blank=True, null=True, upload_to="images/", default='#') #new
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post_detail', args=[str(self.id)])`
here is views.py
`
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from .models import Post
class BlogListView(ListView):
model = Post
template_name = 'home.html'
class BlogDetailView(DetailView):
model = Post
template_name = 'post_detail.html'
class BlogCreateView(CreateView):
model = Post
template_name = 'post_new.html'
fields = ['title', 'author', 'body', 'header_image']
class BlogUpdateView(UpdateView):
model = Post
template_name = 'post_edit.html'
fields = ['title', 'body', 'header_image']
class BlogDeleteView(DeleteView):
model = Post
template_name = 'post_delete.html'
success_url = reverse_lazy('home')
#property
def image_url(self):
"""
Return self.photo.url if self.photo is not None,
'url' exist and has a value, else, return None.
"""
if self.image:
return getattr(self.photo, 'url', None)
return None`
post_base.html
`{% load static %}
<html>
<head>
<title>Django blog</title>
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400"
rel="stylesheet">
<link href="{% static 'css/base.css' %}" rel="stylesheet">
</head>
<body>
<div>
<header>
<div class="nav-left">
<h1>Django blog</h1>
<h2>Admin</h2>
</div>
<div class="nav-right">
+ New Blog Post
</div>
</header>
{% if user.is_authenticated %}
<p>Hi {{ user.username }}!</p>
{% else %}
<p>You are not logged in.</p>
Log In<br>
<p>Sign up</p>
{% endif %}
{% block content %}
{% endblock content %}
</div>
</body>
</html>`
post_detail.html
`
{% extends 'base.html' %}
{% block content %}
<div class="post-entry">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</div>
<p>+ Edit Blog Post</p>
<p>+ Delete Blog Post</p>
<img src="{{ post.header_image.url|default_if_none:'#' }}">
{{ post.body|safe }}
{% endblock content %}`
post_new.html
`
{% extends 'base.html' %}
{% block content %}
<h1>New post</h1>
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" />
</form>
{% endblock content %}`
post_edit.html
`
{% extends 'base.html' %}
{% block content %}
<h1>Edit post</h1>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update" />
</form>
{% endblock content %}`
enctype='multipart/form-data' means that no characters will be encoded. that is why this type is used while uploading files to server. So multipart/form-data is used when a form requires binary data, like the contents of a file, to be uploaded.
You forgot to add enctype='multipart/form-data' in your post_edit.html form and that's the reason your files aren't sent to Django. Following code should work.
post_edit.html
{% extends 'base.html' %}
{% block content %}
<h1>Edit post</h1>
<form action="" method="post" enctype='multipart/form-data'>
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update" />
</form>
{% endblock content %}
I am learning django, I added a new app,
the link can be displayed in friendly_link.html,
the code is as follows:
admin.py
from django.contrib import admin
from .models import FriendlyLink
admin.site.register(FriendlyLink)
models.py
from django.db import models
class FriendlyLink(models.Model):
title = models.CharField(max_length=100, default='', verbose_name='title')
url = models.CharField(max_length=100, default='', verbose_name='url')
class Meta:
verbose_name_plural = 'links'
def __str__(self):
return self.title
views.py
from django.shortcuts import render
from .models import FriendlyLink
def friendly_link(request):
friendly_link = FriendlyLink.objects.order_by('title')
context = {'friendly_link': friendly_link}
return render(request, 'friendly_link.html', context)
urls.py
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^links$', views.friendly_link, name='friendly_link'),
]
friendly_link.html
{% extends "base.html" %}
{% block title %}Links{% endblock %}
{% block content %}
<ul>
{% for link in friendly_link %}
<li>{{ link.title }}</li>
{% empty %}
{% endfor %}
</ul>
{% endblock %}
base.html
{% load i18n static %}<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
{% block content %}{% endblock %}
<footer>
<ul>
<!--This code doesn't work-->
{% for link in friendly_link %}
<li>{{ link.title }}</li>
{% empty %}
{% endfor %}
</ul>
</footer>
...
</body>
I want to put the link inside the <footer> element in base.html. How do I change the code? Thank you.
You should really read this documentation page:
https://django-adminlte2.readthedocs.io/en/latest/templates_and_blocks.html
Each block is clickable there and there's a detailed description on how to overwrite each one.
For your problem, you will probably nav_footer
{% block nav_footer %}
{{ block.super }}
...
{% endblock %}
{{ block.super }} is optional and will append your content to the block instead of overwriting it.
I am trying to build a website using Django 2.2.1,So the problem I currently have is I have a model named "Product".
I also have a template named "product_list.html".
My "views.py" file is:-
from .models import Product
from .forms import ProductForm
# Create your views here.
def product_detail_view(request):
obj = Product.objects.all()
context = {
"title": obj,
"description": obj,
"price": obj
#context = {
# 'object': obj
}
return render_to_response("product_list.html",context)
My models.py file :-
from django.db import models
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=50)
description = models.TextField(null=True)
price = models.DecimalField(max_digits=100, decimal_places=2)
My product_list.html file :-
{% extends 'base.html' %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Product List</title>
</head>
<body>
{% block content %}
<ul>
<li>
{{ title }}
</li>
<li>
{{ obj.title }}
</li>
</ul>
<ul>
{% for prod in title %}
<li>
{{ prod.title | upper }}
</li>
{% endfor %}
</ul>
<ul>
{% for prod in description %}
<li>
{{ prod.description|default:"nothing" }}
</li>
{% endfor %}
</ul>
<ul>
{% for prod in price %}
<li>
{{ prod.price }}
</li>
{% endfor %}
</ul>
<ul>
{% for prod in price %}
<li>
{{ prod.title }}
{{ prod.description }}
{{ prod.price }}
</li>
{% endfor %}
</ul>
{% endblock %}
</body>
</html>
The output I get is:-
https://www.dropbox.com/s/xmogdmgerf3cbu6/Image%205-7-19%20at%2010.11%20PM.jpg?dl=0
So the Issue is how can i select for example:-
i only want the title and description of product 1 .
(( As i have tried the same in my product_list.html file...
I have tried both {{ title }} and {{ obj.title }}
both of them couldn't provide me with the data i wanted from the
database.))
i was only able to render and get that data when i was using {{ for }}
with the function objects.all().
The other option i see is to change my view function .. and update it with
"objects.get(id)"
but then i would have to make multiple views if i am not wrong.
Are there any other function or any other django template language filters that could provide me with the same result while still using the "objects.all()"
function.
or are there any other mistakes or Errors I have ?
def product_detail_view(request):
obj = Product.objects.all()
context = {
"title": obj,
"description": obj,
"price": obj
#context = {
# 'object': obj
}
return render_to_response("product_list.html",context)
The title, description and price you have specified have the same contents. However, the contents that will be fetched from the database contain titles, descriptions and prices. So, you have to specify the contents that you want to fetch from the databses.
Meaning when can say:
data=Product.objects.all()
context={"data":data}
then you have to specify the titles, descriptions, prices in the templates.
For instance
{% for datum in data %}
{{ datum.title }}
{% endfor %}
visit this link
I am currently using Django version 1.11.2 and would like to use the FilteredSelectMultiple widget outside of the admin page.
This is my forms.py:
class TBDAuthGroupManageForm(forms.Form):
permissions = forms.ModelMultipleChoiceField(queryset=Permission.objects.all(),
required=True,
widget=FilteredSelectMultiple("Permissions", is_stacked=False))
class Media:
css = {'all': ('/static/admin/css/widgets.css',), }
js = ('/admin/jsi18n/',)
def __init__(self, parents=None, *args, **kwargs):
super(TBDAuthGroupManageForm, self).__init__(*args, **kwargs)
This is my views.py:
class TBDAuthGroupManageView(DetailView):
model = TBDAuthGroup
template_name = 'perms/tbdauthgroup_manage.html'
def get_context_data(self, **kwargs):
context = super(TBDAuthGroupManageView, self).get_context_data(**kwargs)
context['form'] = TBDAuthGroupManageForm()
return context
And this is my template:
{% extends "base.html" %}
{% load static %}
{% block css %}
{{ form.media }}
<script type="text/javascript" src="{% static 'js/jquery-3.1.1.min.js' %}"></script>
<script type="text/javascript" src="/static/admin/js/jquery.min.js"></script>
<script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
{% endblock %}
{% block content %}
{{ form }}
{% endblock %}
However when I render it in the page, I only get this:
and not this:
I would love to know what I'm doing wrong and how I could fix this so my form looks like the admin form.
{% block content %}
{{ form.media }}
<form>
{{ form.permissions }}
</form>
{% endblock %}
try this in your template
I am attempting to use markdown to avoid having to type HTML within my wiki form, but for some reason the form is displaying HTML code instead of the intended formatting.
My view function is as follows:
from django.shortcuts import render_to_response
from mywiki.wiki.models import Page
from django.http import HttpResponseRedirect
import markdown
def view_page(request, page_name):
try:
page = Page.objects.get(pk=page_name)
except Page.DoesNotExist:
return render_to_response('create.html', {'page_name':page_name})
content = page.content
return render_to_response('view.html', {'page_name':page_name, 'content':markdown.markdown(content)})
This is my view.html template:
{% extends 'base.html' %}
{% load wikilink %}
{% block title %}{{page_name}}{% endblock %}
{% block content %}
<h1>{{page_name}}</h1>
{{content|wikify}}
<hr/>
<a href='/mywiki/{{page_name}}/edit/'>Edit this page?</a>
{% endblock %}
And this is my base.html:
<html>
<head>
<title>{{% block title %}{% endblock %}</title>
</head>
<body>
<div>
Menu: <a href='/mywiki/Start/'>Start Page</a>
</div>
{% block content %}
{% endblock %}
</body>
</html>
I do have markdown installed, and my Django version is 1.4.1 (Mac).
Thanks.
Use Django's safe filter so as for your Html not to be escaped.
{{ content|safe }}
{% autoescape off %}
{{content|wikify}}
{% endautoescape %}
maybe ...