I am using django-endless-pagination for my project. But its not working as it is supposed to. Neither is it showing the show more or neither does it work when I change the code to onscroll mode.
<script>$.endlessPaginate({paginateOnScroll: true});</script>
However the include tags are working as its showing the snaps in the template. And even both the scripts (i.e. the jquery and endless.js) are there. What am I missing? Your help and guidance will be very much appreciated. Thank you.
models.py:
class SnapGroup(models.Model):
name = models.CharField(max_length=150, blank=True, null=True)
date = models.DateField(default=date.today)
class Snap(models.Model):
date = models.ForeignKey(SnapGroup)
image = models.ImageField(upload_to=get_upload_file_name)
caption = models.CharField(max_length=150, blank=True, null=True)
views.py:
#page_template('snapgroups.html') # just add this decorator
def snaps(
request, template='snaps.html', extra_context=None):
context = {
'snapgroup': SnapGroup.objects.all(),
}
if extra_context is not None:
context.update(extra_context)
return render_to_response(
template, context, context_instance=RequestContext(request))
snaps.html:
{% if snapgroup.count > 0 %}
<div class="endless_page_template">
{% include page_template %}
</div>
{% 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 %}
{% else %}
<li><p>No SNAPGROUP yet!</p></li>
<span class="clear_both"></span>
{% endif %}
snapgroups.html:
{% load endless %}
{% paginate snapgroup %}
{% for sg in snapgroup %}
<h4 id="combination" class="snap_date">{{sg.date|date:'l'}}, {{sg.date}}</h4>
<ul>
{% for snap in sg.snap_set.all %}
<li><img src="{{MEDIA_URL}}{{snap.image}}" alt="{{snap.caption}}" /></li>
{% endfor %}
<span class="clear_both"></span>
</ul>
{% endfor %}
{% show_more %}
Solved my problem by this post. Hope this will help someone else.
Related
I have a Django project with posts and the ability to edit posts.
On the main index page, I am showing all posts, like a news feed.
Currently anyone can edit any post, but I want to make it so that only the owner of the post can edit. I'm just not sure how to write the urls.py file since I'm using:
path("", views.index, name="index"),
I would probably need to pass either the post id or the username to this, but I'm not sure how to write it. I tried:
path("index", views.index, name="index"),
path("index/<str:pk>", views.index, name="index"),
path("index/<str:username>", views.index, name="index"),
But I get errors.
views.py
def index(request):
list_of_posts = Post.objects.all().order_by('id').reverse()
paginator = Paginator(list_of_posts, 10)
num = request.GET.get('page', 1)
get_page_num = paginator.get_page(num)
return render(request, "network/index.html", {
"list_of_posts": list_of_posts,
"get_page_num": get_page_num,
})
models.py
class User(AbstractUser):
pass
class Post(models.Model):
text = models.TextField(max_length=500, blank=True,
null=True)
username = models.ForeignKey('User',
on_delete=models.CASCADE, related_name='author',
null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
like = models.ManyToManyField(
User, blank=True, related_name="liked_user")
def __str__(self):
return self.username.username
html to show edit button. I've tried:
{% if post.username == request.user.username %}
<button class="btn-btn primary" my-id="{{i.id}}" id="ebutton-
{{i.id}}" onclick="edit_form(this)" >Edit</button>
<br><br><br>
{% endif %}
Full html of this page:
{% extends "network/layout.html" %}
{% load static %}
{% block body %}
<br>
<h3> <center> Welcome. Here is your news feed: </center> </h3>
<br>
{% for i in get_page_num %}
<div class='card mb-3' style="max-width: 530px;" id="card-posts">
<div class="row no-gutters">
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title"><a href="{% url 'profile'
username=i.username %}">{{i.username}}</a></h5>
<span id="textinfo-{{i.id}}"
class="post">{{i.text}}</span> <br>
<textarea my-id="{{i.id}}" id="edit-me-{{i.id}}"
style="display:none;" class="form-control
textarea" row="3">{{i.text}}</textarea>
<br>
<p class="card-text">{{i.timestamp}}</p>
<div class="like mt-1">
<img my-id="{{i.id}}" id="is-it-liked-{{i.id}}"
class="like-class"
{% if not request.user in i.like.all %}
clicked="no"
src="https://img.icons8.com/emoji/452/white-heart.png"
{%else%}
clicked="yes"
src="https://img.icons8.com/emoji/452/red-heart.png"
{%endif%}
/> <span id="post-count-{{i.id}}">{{i.like.count}}.
</span>
</div>
<br>
{% if request.user == post.username %}
<button class="btn-btn primary" my-id="{{i.id}}"
id="ebutton-{{i.id}}" onclick="edit_form(this)"
>Edit</button>
<br><br><br>
{% endif %}
</div>
</div>
</div>
</div>
{% endfor %}
<br><br>
<div class="pagination">
<span class="step-links">
{% if get_page_num.has_previous %}
<a href="?page={{ get_page_num.previous_page_number }}"
class="page-link">Previous</a>
{% else %}
<li class="page-item disabled"><a class="page-
link">Previous</a></li>
{% endif %}
{% if get_page_num.has_next %}
<a href="?page={{ get_page_num.next_page_number }}" class="page-
link">Next</a>
{% else %}
<a class="page-link">Next</a>
{% endif %}
</span>
</div>
{% endblock %}
{% block script %} <script src="{% static
'network/network.js'%}"></script> {% endblock %}
With this way I need to pass username to the url but I cannot, without getting errors.
Overall I'm just looking for advice, on how to make the edit button only appear on posts that the current user is an owner on. So that way no one can edit anyone else's posts.
If you want to show all posts and only allow a post author to edit it, you need to inject all posts and the request user in your template context. Then in your template iterate through the posts and check if the author is equal to the request user before showing the edit button. But first you need a foreign key in your post model that refers to the author.
Urls.py
urlpatterns = [path("index/", views.index, name="index")]
Views
def index(request):
list_of_posts = Post.objects.order_by('-id')
request_user = request.user
return render(request, "network/index.html", {
"list_of_posts": list_of_posts,
"request_user": request_user
})
Models
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='posts')
# Other fields
Template
{% if post.user == request_user %}
<!--Show the edit button-->
{% endif %}
You can also access directly the request object in your template:
{% if post.user == request.user %}
<!--Show the edit button-->
{% endif %}
I needed to add
{% if request.user == i.username %}
because I was looping in the html page, for i in get_page_num:. I did not previously have the i.
{% if request.user == post.author %}
<button>Delete</button>
{% endif %}
This assumes that you have a Post model with an attribute of author
I trying to access the ImageField of a Model which is assigned via ForeignKey to another Model.
I have different Animal Apps in my Projects, with almost the same structure, like the following models.py. On the landingpage of My Project I want to display the last 3 entry of every (Species) Models with Name and Picture. If the Species has no Picture I would like to display the ImageField of the Farm, which is connected via ForeignKey to my species.
cows/models.py
class Farm(models.Model):
name = models.CharField(max_length=100)
farm_img = models.ImageField(upload_to='farm_images/',
max_length=255, null=True, blank=True)
class Cows(models.Model):
farm = models.ForeignKey(Farm, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=100)
entry_date = models.DateField(null=True, blank=True)
cow_img = models.ImageField(upload_to='farm_images/',
max_length=255, null=True, blank=True)
Views.py
class HomeIndex(TemplateView):
template_name = 'home.html'
def get_context_data(self, **kwargs):
context['chickens'] = Chicken.objects.order_by('-entry_date')[:3]
context['cows'] = Cows.objects.order_by('-entry_date')[:3]
context['cats'] = Cats.objects.order_by('-entry_date')[:3]
return context
home.html
<….>
{% for somecow in cows %}
<div class="col-3" id="p1">
<h2>{{ somecow.name }}</h2>
<h2>{{ somecow.entry_date }}</h2>
{% if somecow.cow_img %}
<img src="{{ somecow.cow_img.url }}" alt="Mod" height="100">
{% endif %}
</div>
{% endfor %}
<….>
Until here it worked.
But how can i access the FK.Model of the Model?
Or in other Words how can I tell Django:
“If you found no cow Picture in Cow.Model,then show a Farm picture from the assigned Farm.Model?”
As I understand I can access the assigned FK Models via
{% for something in MyModel1.MyModel2_set.all %}.
my approach for home.html
<….>
{% for somecow in cows %}
<div class="col-3" id="p1">
<h2>{{ somecow.name }}</h2>
<h2>{{ somecow.entry_date }}</h2>
{% if somecow.cow_img %}
<img src="{{ somecow.cow_img.url }}" alt="Mod" height="100">
{% else %}
{% for farm in somecow.farm_set.all %}
{% if farm.farm_img %}
<img src="{{ farm.farm_img.url }}" alt="Mod" height="100">
{% endif %}
{% endfor %}
{% endif %}
</div>
{% endfor %}
<….>
So far I received no error Message, but I also see no Farm Image. I am sure I mixed something up in home.html. On the other Side I think I maybe I missed something in my view, something like MyModel.objects.all()
I am thankful for every hint.
You're overcomplicating things. There is only a single farm per cow: you just need to access it directly.
{% else %}
{% if cow.farm.farm_img %}
<img src="{{ cow.farm.farm_img.url }}" alt="Mod" height="100">
{% endif %}
{% endif %}
I am trying to show all images associated with the currently selected user
This is built off of this solved question: django upload to image model with foreign key to user
Model.py
class Images(models.Model):
image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png')
user = models.ForeignKey(User, on_delete=models.CASCADE)
Views.py
#login_required
def index_account(request):
args = {'user': request.user }
return render(request, 've/cp/index_account.html', args)
Template > index_account.html
<p>Edit your images</p>
# test to see if it worked w/o if
{{ user.images.image}}
# ideal solution
{% if user.images.images %}
{% for img in user.images %}
<img src="{{ user.images.image.url }}"><br>
{% endfor %}
{% else %}
<p>No images</p>
{% endif %}
<br>
<hr>
The code you have provided is not going to work for what you want. So here is an example of something that probably will:
Example
views.py
from app_name.models import Images
#login_required
def index_account(request):
images = Images.objects.filter(user=request.user)
return render(request, 've/cp/index_account.html', {"images": images})
index_account.html
<p>Edit your images</p>
# ideal solution
{% if images %}
{% for img in images %}
<img src="{{ img.url }}"><br>
{% endfor %}
{% else %}
<p>No images</p>
{% endif %}
<br>
<hr>
Hope this helps!
I am using haystack (2.1.1) and whoosh in my django (1.7) website. i am happy because it is working, but not completely. the app show the right searches but when i click in the results it doesn't go to the product page. it looks like i haven't configured something that make {{ result.object.get_absolute_url }} doesnt work properly. I hope any of you can help me (as reference i am putting all the code)
this is my app models (products/models)
from django.db import models
class Products(models.Model):
name = models.CharField(max_length=120)
description = models.TextField()
image1 = models.ImageField(upload_to='product_images', blank=True, null=True)
price = models.FloatField(default=0.00)
slug = models.CharField(max_length=50, blank=False, null=True)
pub_date = models.DateTimeField()
def __unicode__(self):
return str(self.name)
class Meta:
ordering =['-id']
verbose_name = ('Product')
verbose_name_plural = ('Products')
this is my search_indexes.py, that i put in the same folder of my app (products/search_indexes.py)
import datetime
from haystack import indexes
from products.models import Products
class ProductsIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
name = indexes.CharField(model_attr='name')
description = indexes.CharField(model_attr='description')
pub_date = indexes.DateTimeField(model_attr='pub_date')
def get_model(self):
return Products
def index_queryset(self, using=None):
return self.get_model().objects.filter(pub_date__lte=datetime.datetime.now())
I did the changes in the settings file
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
},
}
create the file in my template folder "templates/search/indexes/products/products_text.txt"
{{ object.name }}
{{ object.description }}
the HTML and urls are the same as in the website of haystack (just change the result.object.title for result.object.name). in URLS: (r'^search/', include('haystack.urls')) and html (templates/search/search.html)
{% extends 'base.html' %}
{% block content %}
<h2>Search</h2>
<form method="get" action=".">
<table>
{{ form.as_table }}
<tr>
<td> </td>
<td>
<input type="submit" value="Search">
</td>
</tr>
</table>
{% if query %}
<h3>Results</h3>
{% for result in page.object_list %}
<p>
{{ result.object.name }}
</p>
{% empty %}
<p>No results found.</p>
{% endfor %}
{% if page.has_previous or page.has_next %}
<div>
{% if page.has_previous %}{% endif %}« Previous{% if page.has_previous %}{% endif %}
{% if page.has_next %}{% endif %}Next »{% if page.has_next %}{% endif %}
</div>
{% endif %}
{% else %}
{# Show some example queries to run, maybe query syntax, something else? #}
{% endif %}
</form>
{% endblock %}
as i said before it does the search and show it. but i don't know why the {{ result.object.get_absolute_url }} is not working, so it shows the product tittle but doesn't link them to their pages.
You just need to define a get_absolute_url method explicitly on your model class:
class Products(models.Model):
...
def get_absolute_url(self):
return "/products/%s/" % self.slug
It would be even better to use reverse within this method, which will depend on your urlconf. More details here.
I have a template showing a list of events. To prepare list of events I'm using generic views, and set 'paginate_by' parameter. Strangely when I load my page I see :
TemplateSyntaxError at /event/latest/
Caught an exception while rendering: 'int' object is not iterable
in 9th line of pagination.html template :
{% if is_paginated %}
{% load i18n %}
<div class="pagination">
{% if page_obj.has_previous %}
<< Prev
{% else %}
<span class="disabled prev"><< Prev</span>
{% endif %}
#here {% for page in pages %}
{% if page %}
{% ifequal page page_obj.number %}
<span class="current page">{{ page }}</span>
{% else %}
{{ page }}
{% endifequal %}
{% else %}
...
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
Next >>
{% else %}
<span class="disabled next">Next >></span>
{% endif %}
</div>
{% endif %}
Here is my view :
def events_nearest(request):
events = Event.nearest.all()
return object_list(request,
queryset = events,
extra_context = {'title': 'Nearest events'},
paginate_by = 12,
template_name = 'event/events_date.html')
And model :
class NearestManager(models.Manager):
def get_query_set(self):
return super(NearestManager, self).get_query_set().order_by('-data')
class Event(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=120)
slug = models.SlugField(max_length=255, unique=True, verbose_name='Slug')
about = models.TextField()
city = models.ForeignKey(City)
objects = models.Manager()
nearest = NearestManager()
Any ideas what can cause this ?
pages variable is the number of pages, which is int and hence the error: 'int' object is not iterable
you should be looping over page_range
{% for page in page_range %}
I met the same error. There is a note at
https://docs.djangoproject.com/en/dev/topics/pagination/
Changed in Django Development version: Previously, you would need to use {% for contact in contacts.object_list %}, since the Page object was not iterable.
So {% for page in pages.object_list %} could probably solve your problem.
For anybody stumbled upon this post:
As with Django 1.4 and later (as far as I know), the iterable object for pagination is now paginator.page_range , i.e. the for loop should be
{% for page_num in paginator.page_range %}
In your error line #9 {% for page in pages %} what exactly is pages
Can't see it in your code anywhere.