badge notification by the number of new matches - python

I am trying to get a batch notification to work, but the badge throws several badges with the below code, and it does not show the number. I want the badge to display the number of content within several posts matches with an interest.
I am still a beginner at django, so please bear over with me, if this is a total bad approach.
interest.html
{% for item in interest %}
<ul class='nav nav-pills nav-stacked'>
<li><a href='/'>
<span class='badge pull-right'>
{% for word in post %}
{% if word == interest %}
{{ word.as_number }}
{% else %}
0
{% endif %}
{% endfor %}
</span>
{{ item.interest }}
</a></li>
</ul>
{% endfor %}
context_processors.py
def user_interest(request):
interest = Interests.objects.all()
interests_form = InterestsForm(request.POST or None)
post = Posts.objects.all()
if interests_form.is_valid():
new_interest = interests_form.save(commit=False)
new_interest.save()
#return HttpResponseRedirect('/')
#apparently it is not needed here
return {'interest': interest,
'interests_form': interests_form,
'post': post,
}
models.py
class Interests(models.Model):
interest = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)

I'm not fully understanding, but part of your problem may be this part:
{% if word == interest %}
You're comparing a particular Post with all of your Interests (since 'interest' = Interests.objects.all()). At the very least I would change that to:
{% if word == item %}
As this iterates through your interest list (using 'item') and compares it to each 'word' in your post list.

Related

How do I get all candidate in a position

Am trying to query every candidate that belong to a specific position and loop through it using the django template in my html. If I have just one position/poll all candidate will display in my frontend, but once i add another position/poll then the list of the candidate will not display again
def index(request):
context = {}
instruction = ""
positions = Position.objects.order_by('priority').all()
for position in positions:
candidates = Candidate.objects.filter(position=position)
for candidate in candidates:
votes = Votes.objects.filter(candidate=candidate).count()
if position.max_vote > 1:
instruction = "You may select up to " + str(position.max_vote) + " candidates"
else:
instruction = "Select only one candidate"
context = {
'positions': positions,
'candidates': candidates,
'votes': votes,
'instruction': instruction
}
return render(request, 'poll/index.html', context)
{% block content %}
<div class="row">
<div class="mt-5">
{% for p in positions %}
{{ instruction }}
<h1>{{ p.name }}</h1>
<p>{{ p.description }}</p>
{% for c in candidates %}
<h1>{{ candidate.fullname }}</h1>
{% endfor %}
{% endfor %}
</div>
</div>
{% endblock %}
Well, as much I understand you are querying objects inside the for loop and you are not storing the result of each iteration, whenever the next iterations happen, that overwrite the candidates and votes variable...

Django pass family in template inside for cycle

In a simple view I pass a family in template like this:
def page(request):
family= Author.objects.all()
return render(request, "myapp/page.html", {'family':family})
and I render in template like this:
{% for item in family %}
{{ item.pk }}
{% endfor %}
But, if I put my family inside a for cycle; for example:
def page(request):
family = []
for i in range(5):
family= Author.objects.filter(name='John')[i]
return render(request, "myapp/page.html", {'family':family})
it not render anything in template...
Any idea?
EDIT 1
I have more users in my app, every user has different blog and every blog has different post...
So when user is logged i need to show his blog and for every blog show last 5 post.
I do:
#login_required
def page(request):
user = request.user.id
numblog = Blog.objects.filter(user_id=user).aggregate(c=Count('id'))
for i in range(numblog['c']):
blogquery = Blog.objects.filter(user_id=user)[i]
postquery = Post.objects.filter(blog_id=blogquery.pk)[:5]
return render(request, "myapp/page.html", {'blogquery ':blogquery,'postquery ':postquery })
expected result in template:
{% for b in blogquery %}
{{ b.name }} ### here name of blog
{% for p in postquery %}
{% if p.blog_id == b.pk %}
{{ p.content }} ### here last 5 post of THAT blog
{% endif %}
{% endfor %}
{% endfor %}
EDIT 2
In a view, if I print result it work but not render in template
#login_required
def page(request):
user = request.user.id
numblog = Blog.objects.filter(user_id=user).aggregate(c=Count('id'))
for i in range(numblog['c']):
blogquery = Blog.objects.filter(user_id=user)[i]
postquery = Post.objects.filter(blog_id=blogquery.pk)[:5]
for p in postquery:
print (blogquery.pk, p.pk)
return render(request, "myapp/page.html", {'blogquery ':blogquery,'postquery ':postquery })
It is surprising how you don't understand that repeatedly assigning to the same variable within a loop will just give you the last value.
But nevertheless, you don't need any of this code. You should just follow the relationship in the template.
#login_required
def page(request):
blogs = Blog.objects.filter(user=user).prefetch_related('post_set')
return render(request, "myapp/page.html", {'blogs ': blogs })
{% for blog in blogs %}
{{ blog.name }}
{% for post in blog.post_set.all|slice:"5" %}
{{ post.content }}
{% endfor %}
{% endfor %}
(You haven't shown your models so I presume the related_name from Blog to Post is called post_set, change as necessary.
UPDATE
That's not correct. You don't need to use for loop. If you need to get the last 5 rows you can do this i.e.:
def page(request):
family= Author.objects.all().order_by('-pk')[:5]
return render(request, "myapp/page.html", {'family':family})
another approach is to limit the results in your template:
{% for item in family %}
{% if forloop.counter < 6 %}
{{ item.pk }}
{% endif %}
{% endfor %}

Django disable a link if list returns empty

I don't want to display a link if the list returns empty.
template.html
{% for item in cart %}
<h1>{{ item.product.product_title }}</h1>
Remove item
{% empty %}
<p>No items in cart</p>
{% endfor %}
{% if item is not None %}
<p>
Checkout
</p>
{% endif %}
views.py
def cartview(request):
if request.user.is_authenticated():
cart = Cart.objects.filter(user=request.user.id, active=True)
orders = ProductOrder.objects.filter(cart=cart)
#total = 0
count = 0
for order in orders:)
count += order.quantity
context = {
'cart': orders,
'count': count,
}
return render(request, 'store/cart.html', context)
else:
return redirect('index:index')
I want to hide checkout link if the cart list is empty. putting it in the for loop would make the link appear many times. I want to display checkout button only once.
Instead of 'item' check for 'cart' in the template.
{% if cart %}
<p>
Checkout
</p>
{% endif %}

django blog archive, index and pagination comprehensive application

Background:
I am building a blog about my research group. On the publication archive page I am going to display all the publications of my mentor. Here there is a side column to show the archive index allowing users to view the publications by year. And at the bottom of the page there is a django paginator which separate the publications in to several pages with 7 publications per page.
Problem:
When the pagination is used, the publications is divided into a list, so the {{publication.published_time}} only contain the data in the current page rather than the whole dataset. Thus, I wrote the hard code of year information in the front end and add the url to the corresponding year.
Apparently, I wish I can get the distinct year information about all publications on the basis of the existence of a paginator. Besides, transfer the year value directly in the URL.
Code:
url.py:
url(r'^publications/(?P<year>[0-9]{4})/$', PublicationYearArchiveView.as_view(),
name="publication_year_archive"),
views.py:
class PublicationYearArchiveView(YearArchiveView):
queryset = Publication.objects.all()
date_field = "published_time"
make_object_list = True
allow_future = True
def listing(request):
limit = 7
publication_list = Publication.objects.all().order_by('published_time').reverse()
paginator = Paginator(publication_list, limit) # Show 7 publications per page
page = request.GET.get('page')
try:
publications = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
publications = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
publications = paginator.page(paginator.num_pages)
return render(request,
'research_spacecoupe/research_accomplishment.html',
{'publications': publications})
research.html:
Paginator:
{% if publications.has_other_pages %}
<ul class="pagination">
{% if publications.has_previous %}
<li>«</li>
{% else %}
<li class="disabled"><span>«</span></li>
{% endif %}
{% for i in publications.paginator.page_range %}
{% if publications.number == i %}
<li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li>{{ i }}</li>
{% endif %}
{% endfor %}
{% if publications.has_next %}
<li>»</li>
{% else %}
<li class="disabled"><span>»</span></li>
{% endif %}
</ul>
{% endif %}
Index:
<div class="sidebar-module">
<h4>Archive</h4>
<ol class="list-unstyled">
<li>all publications</li>
<li>2017</li>
<li>2016</li>
<li>2015</li>
<li>2013</li>
<li>2012</li>
<li>2011</li>
<li>2010</li>
</ol>
</div>
Note:
Now the page does work, and I can click the year(eg. 2017) to view the publications published in 2017 and click the "All publications" to view all publications. But I want to replace the number of year with distinct publications.published_time of all publications. Anything I can do to fix it?
views.py:
from django.db.models.functions import ExtractYear
from django.db.models import Count
# ...
def listing(request):
# ...
years = Publication.objects \
.annotate(year=ExtractYear('published_time')) \
.values_list('year') \
.annotate(count=Count('id')) \
.values_list('year', flat=True) \
.order_by('year')
return render(request,
'research_spacecoupe/research_accomplishment.html',
{'publications': publications,
'years': years})
research_accomplishment.html:
<div class="sidebar-module">
<h4>Archive</h4>
<ol class="list-unstyled">
<li>all publications</li>
{% for year in years %}
<li>{{ year }}</li>
{% endfor %}
</ol>
</div>

django sort dict after query

have a table with websites and a many to one table with descriptions
trying to get a list, firstly getting the latest descriptions and then displaying them ordered by the content of the descriptions...
have the following in views.py
def category(request, category_name_slug):
"""Category Page"""
context_dict = {}
try:
category = Category.objects.get(slug=category_name_slug)
subcategory = SubCategory.objects.filter(category=category)
websites = Website.objects.filter(sub_categories=subcategory, online=True, banned=False)
sites = websites
descriptions = WebsiteDescription.objects.prefetch_related("about")
descriptions = descriptions.filter(about__in=sites)
descriptions = descriptions.order_by('about', '-updated')
descs = []
last_site = "" # The latest site selected
# Select the first (the latest) from each site group
for desc in descriptions:
if last_site != desc.about.id:
last_site = desc.about.id
desc.url = desc.about.url
desc.hs_id = desc.about.id
desc.banned = desc.about.banned
desc.referral = desc.about.referral
descs.append(desc)
context_dict['descs'] = descs
context_dict['websites'] = websites
context_dict['subcategory'] = subcategory
context_dict['category'] = category
except SubCategory.DoesNotExist:
pass
return render(request, 'category.html', context_dict)
this gives me a list with sites and their latest descriptions, so i have the following in category.html
{% if category %}
<h1>{{ category.name }}</h1>
{% for subcategory in category.subcategory_set.all %}
{{ subcategory.name }} ({{ subcategory.website_set.all|length }})
{% endfor %}
{% if descs %}
{% load endless %}
{% paginate descs %}
{% for desc in descs|dictsortreversed:"description"|dictsortreversed:"officialInfo" %}
<ul id='list' class='linksteps'>
<a href="/{{ desc.about_id }}" rel="nofollow" target="_blank">
<img src="/static/screenshots/{{ desc.about_id }}.png" />
</a>
<li><h3>{{ desc.about_id }}{% if desc.title %} - {{ desc.title }} {% endif %}</h3>
{% if desc.description %}<b>Description: </b>{{ desc.description }}
<br />{% endif %} {% if desc.subject %}<b>Keywords: </b>{{ desc.subject }}
<br />{% endif %} {% if desc.type %}<b>Type: </b>{{ desc.type }}
<br />{% endif %} {% if desc.officialInfo %} {% if desc.language %}<b>Language: </b>{{ desc.language }}
<br />{% endif %} {% if desc.contactInformation %}<b>Contact info: </b>{{ desc.contactInformation }}
<br />{% endif %}
{% else %}
{% endif %}
</li>
</ul>
</div>
{% endfor %}
{% show_pages %}
{% else %}
<strong>No websites currently in category.</strong>
{% endif %}
{% else %}
The specified subcategory {{ category_name }} does not exist!
{% endif %}
Initially i used dictsort
{% for desc in descs|dictsortreversed:"description"|dictsortreversed:"officialInfo"|dictsortreversed:"referral" %}
to give me the list in the desired order, so i was all happy ;)
Then however i decided i needed some pagination because the lists became too long.
django-endless-pagination works fine and does what its supposed too, however it splits up my list before the dictsort kicks in.
is there a way to sort before pagination happens and after i ordered_by at the initial query to have the latest descriptions selected?
much obliged
EDIT:
not getting any answers so my question might not be clear.
as far as i understand i need to sort the values in context_dict at the end in views.py replacing the dictsort as in the template
SOLVED:::
doing this did the trick for me to replace the dictsort.
descs1 = sorted(descs, key=operator.attrgetter('referral', 'officialInfo', 'description'), reverse=True)
context_dict['descs'] = descs1
SOLVED:::
doing this did the trick for me to replace the dictsort.
descs1 = sorted(descs, key=operator.attrgetter('referral', 'officialInfo', 'description'), reverse=True)
context_dict['descs'] = descs1

Categories

Resources