Django template is not displaying - django

Assuming my model contains data, I have myapp/views.py:
from django.template import RequestContext
from django.shortcuts import render
from .models import History
import datetime
def live_view(request):
context = RequestContext(request)
plays_list = History.objects.filter(date=datetime.date(2016,04,22))
context_list = {'plays':plays_list}
return render(request,'live.html',context_list)
myapp/templates/live.html:
{% extends 'base.html' %}
{% block content %}
{% for key, value in context_list.items %}
{{ value }}
{% endfor %}
{% endblock %}
myapp/urls.py:
from myapp.views import live_view
urlpatterns = [url(r'^live/$', live_view, name="live"),]
The output is a page that renders only the base.html template, with no content in the body. What's wrong with my view function or template rendering? Should I be inheriting from TemplateView?

You don't pass anything called context_list to the template. What you pass is the contents of that dict, which in this case is just plays.

Related

How do I trigger a Celery task from Django admin?

I have a model called Publication and I'd like to add a button to the list view in Django Admin which would allow triggering a Celery task.
admin.py:
from django.contrib import admin
from .models import Publication
class PublicationAdmin(admin.ModelAdmin):
change_list_template = "variants/admin_publication_list.html"
def update(self, request):
# trigger task
# redirect to admin list
admin.site.register(Publication, PublicationAdmin)
variants/admin_publication_list.html:
{% extends 'admin/change_list.html' %}
{% block object-tools %}
<li>
<a href="/admin/variants/publication/update/">
Update
</a>
</li>
{{ block.super }}
{% endblock %}
However when I press a button I only get a notice:
Publication with ID “update” doesn’t exist. Perhaps it was deleted?
Method name update or route name update is too generic and sometimes used by frameworks automatically, try naming it to match your functionality. revoke-publications or sync-publications.
admin.py:
from django.contrib import admin
from django.urls import path
from django.http import HttpResponseRedirect
from .models import Publication
from .tasks import your_celery_task
#admin.register(Publication)
class PublicationAdmin(admin.ModelAdmin):
change_list_template = "variants/admin_publication_list.html"
def get_urls(self):
urls = super().get_urls()
my_urls = [
path('update-publications/', self.publication_update),
]
return my_urls + urls
def publication_update(self, request):
result = your_celery_task.delay("some_arg")
self.message_user(
request,
f"Task with the ID: {result.task_id} was added to queue. Last known status: {result.status}"
)
return HttpResponseRedirect("../")
variants/admin_publication_list.html:
{% extends 'admin/change_list.html' %}
{% block object-tools %}
<div>
<form action="update-publications/" method="POST">
{% csrf_token %}
<button type="submit">Run Celery Task</button>
</form>
</div>
<br />
{{ block.super }}
{% endblock %}

Where to import stuff for a template in Django?

Sorry for the dumb question, I'm lost.
I got a template and a templatetags with this :
menu_tags.py
from django import template
from menu.models import Button
register = template.Library()
#register.inclusion_tag('menu/home.html')
def show_menu():
buttons = Button.objects.all()
return {'buttons': buttons}
And this :
home.html
{% for button in buttons %}
{% if user.is_authenticated %}
stuff
{% endif %}
{% endfor %}
I would like to know, how can I make user.is_authenticated work ? I know I have to import something, but where ? Importing it in menu_tags does not seems to work.
Thanks !
As suggested by other users in the comments, try the following:
from django import template
from menu.models import Button
register = template.Library()
#register.inclusion_tag('menu/home.html', takes_context=True)
def show_menu():
request = context['request']
if request.user.is_authenticated: # if Django 1.10+
buttons = Button.objects.all()
else:
buttons = None
return {'buttons': buttons}
And then in your template, make sure you load your new templatetags and try:
{% load menu_tags %}
{% for button in buttons %}
{{ button }}
{% endfor %}

why i am not able to view with classbased (list view )but for function based view it is working fine?

My question: why i am not able to view search only ayan rand's book with classbased list view?
this is my function based view for store list, and i am retrieving all my book objects and rendering in HTML and it is working fine.
But using classbasedview "SearchBookDetail" i am not able to get the specified book details as denoted .
Views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect
from django.views.generic import TemplateView,ListView,DetailView
def store_listView(request,):
queryset=Book.objects.all()
context={
"objects_list":queryset
}
return render(request,'bookstores/store.html',context)
class SearchBookDetail(ListView):
template_name = "bookstores/store.html"
queryset = Book.objects.filter(author__icontains='Ayan Rand')
print("Ayan Rand query set", queryset)
Urls.py:
from django.conf.urls import url
from django.contrib import admin
from django.views.generic import TemplateView
from store.views import (Home,ContactView,LoginView,
store_listView,
SearchBookDetail,
book_createview,
QuoteslistView,
AyanRandBookDetail,
quotesFunctionView)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',Home.as_view()),
url(r'^contact/$',ContactView.as_view()),
url(r'^login/$',LoginView.as_view()),
url(r'^store/$',store_listView),
url(r'^store/AyanRandBookDetail/$',AyanRandBookDetail.as_view()),
url(r'^store/SearchBookDetail/$',SearchBookDetail.as_view()),
url(r'^quotes/$',quotesFunctionView)]
store.html:
{% extends "home.html" %}
{% block head_title %}Store || {{ block.super }} {% endblock head_title %}
{% block content %}
<head>
<meta charset="UTF-8">
<title>Store</title>
</head>
<h6>Books available</h6>
<ul>
{% for obj in objects_list %}
<li>{{obj}}<br>
{{obj.book_image}} <br>
{{obj.description}} <br>
{{obj.author}}<br>
{{obj.genre}}<br>
{{obj.price}}<br>
</li>
{% endfor %}
</ul>
{% endblock content %}
ListView sends its data to the template as object_list, not objects_list.

ListView for Django not Working but function based view is working

When I am using function based view using the following code:
from django.views import View
from django.views.generic import TemplateView, ListView
from .models import Restaurant
def restaurant_listview(request):
template = 'restaurants/restaurants_list.html'
context = {
"queryset" : Restaurant.objects.order_by('-updated')
}
return render (request, template, context)
it is working with the url file kept as follows:
from django.conf.urls import url
from django.contrib import admin
from restaurants import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^restaurants/$', views.restaurant_listview),
]
But when I am trying to do the same thing with class based views it is not working only the following portion doesn't seem to work:
<ul>
{% for obj in queryset %}
<li>{{obj.name}}, {{obj.location}}, {{obj.category}}, {{obj.timestamp}}</li>
{% endfor %}
</ul>
the following part works fine:
{% extends 'base.html' %}
{% block title %}
Restaurants List {{ block.super }}
{% endblock %}
{% block content %}
<h1>Restaurants</h1>
for class based view my views.py is:
class RestaurantListView(ListView):
queryset = Restaurant.objects.all()
template_name = 'restaurants/restaurants_list.html'
and urls.py is:
url(r'^restaurants$', RestaurantListView.as_view(), name='Home')
P.S. I am following this guide : https://www.youtube.com/watch?v=yDv5FIAeyoY&t=25471s
For a list view, you should change the template to:
{% for obj in restaurant_list %}
Or, if you really want to use the variable queryset in the template, then set context_object_name.
class RestaurantListView(ListView):
queryset = Restaurant.objects.all()
template_name = 'restaurants/restaurants_list.html'
context_object_name = 'queryset'

how to get template working in django?

I was on the 3rd tutorial of this https://docs.djangoproject.com/en/1.5/intro/tutorial03/ site. I got stuck where we load template for our views under the section Write views that actually do something.
The first code is working fine ( as there is no template loading):
from django.http import HttpResponse
from polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
output = ', '.join([p.question for p in latest_poll_list])
return HttpResponse(output)
But when I laod the template with code below it shows same result as above( that is
with no template)
from django.http import HttpResponse
from django.template import Context, loader
from polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = Context({
'latest_poll_list': latest_poll_list,
})
return HttpResponse(template.render(context))
The template use is:
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li>{{ poll.question }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
The template is in polls/template/polls/index.html where polls is my app( as used in tutorial)
PS:I have followed everything as it is till this point from tutorial.
As you can see in the Django documentation, django.template.loaders.app_directories.Loader looks for template files in a directory named templates inside the app directory.
You said that your template is in "polls/template/polls/index.html", but it should be in "polls/templates/polls/index.html" (notice the added s to templates).