Django: An Error of Getting Templates - python

I am a beginner of Django. Now, I have a problem of getting templates. The context of my webpage contains just messy code...
Here is photo/views.py:
from django.template import loader, Context
from django.http import HttpResponse
from final.photo.models import Image, Audio
def List(request):
posts = Image.objects.all()
t = loader.get_template("list.html")
return HttpResponse(t, { 'posts': posts })
Here is photo/urls.py:
from django.conf.urls.defaults import *
from final.photo.views import List
urlpatterns = patterns('',
url(r'^$', List),
)
Here is list.html: (some of the code cannot be seen on the webpage)
<pre>
<title>So Easy! - Scene List</title>
<h1>So Easy! Learn Chinese</h1>
{% block content %}
{% endblock %}
I hope someone can help me solve it! Thanks!

Try changing your view to the following:
def List(request):
posts = Image.objects.all()
context = RequestContext(request, {
'posts': posts,
})
return render_to_response('list.html', context)
Also, check that your settings.py has the following:
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
Finally, you'll also need to change your list.html template to make use of posts variable you're passing by using {{ posts.some_image_attribute }} in your template.

First of all: which version of django are you using? Django 1.3 added View Classes, which make things a lot easier.
Considering you're still on Django 1.2:
You must set the template folder at settings.py:
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
"/absolute/path/to/your/template/folder",
)
Also you need to add a code snippet inside list.html:
{% block content %}
{% for item in posts %}
{% endfor %}
{% endblock %}
It's advised to create a base.html for your templates. After you do this, add {% extends "base.html" %} as the first line of your list.html
The return line of your view function should be:
return render_to_response('list.html', { 'posts' : posts })

Related

how can I throw all the categories into the header [duplicate]

I'm putting together a project management website for my team using django. My base template includes a sidebar menu which contains a list of all projects and users, linking to a DetailView for that user or project, respectively.
My problem is that I need to provide the User and Project models to every view so that I can render that sidebar. I know how to add extra context; the problem is that I feel like I'm violating DRY by modifying the context at each level. Is it possible to simply redefine the base TemplateClass so that all child classes—ListView, DetailView, etc.—contain the modified context?
On a related note, if this is a terrible way to set up the project, let me know that as well.
You could use the template context processor:
myapp/context_processors.py:
from django.contrib.auth.models import User
from myapp.models import Project
def users_and_projects(request):
return {'all_users': User.objects.all(),
'all_projects': Project.objects.all()}
And then add this processor to the TEMPLATE_CONTEXT_PROCESSORS setting for Django version < 1.8:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'myapp.context_processors.users_and_projects',
)
And for Django version >= 1.8 add it to the context_processors list in the OPTIONS of the TEMPLATES setting:
TEMPLATES = [
{
...
'OPTIONS': {
'context_processors': [
...
'myapp.context_processors.users_and_projects',
],
},
},
]
Context processor will run for ALL your requests. If your want to run these queries only for views which use the base.html rendering then the other possible solution is the custom assignment tag:
#register.assignment_tag
def get_all_users():
return User.objects.all()
#register.assignment_tag
def get_all_projects():
return Project.objects.all()
And the in your base.html template:
{% load mytags %}
{% get_all_users as all_users %}
<ul>
{% for u in all_users %}
<li>{{ u }}</li>
{% endfor %}
</ul>
{% get_all_projects as all_projects %}
<ul>
{% for p in all_projects %}
<li>{{ p }}</li>
{% endfor %}
</ul>

Django Template Not Extending

I'm trying to extend a base template in Django named 'base.html' in my main page 'index.html' and it does not work as expected. Rather than extending the template, the page just displays {% extends 'base.html' %}, plus the HTML in index.html when displaying the index page.
The 'base.html' page sits in the root of my templates folder and my 'index.html' page sits in templates/pages.
In 'base.html':
{% load static %}
...some code...
{% block content %}
{% endblock %}
...some code...
In 'index.html':
{% extends 'base.html' %}
{% load static %}
{% block content %}
...some code...
{% endblock %}
In views.py:
def index(request):
return render(request, 'pages/index.html')
In settings.py:
TEMPLATES = [{'DIRS': [os.path.join(BASE_DIR, 'templates)]
Expected Result:
Navbar
Content
Actual Result:
{% extends 'base.html' %}
{% load static %}
{% block content %}
Content
{% endblock %}
Like others mentioned, you are most likely viewing the html file directly.
You need to go to a view that makes use of the template which will render the final html.
I am not familiar with your project structure, so try doing this first:
in urls.py
from django.urls import path
from django.views.generic import TemplateView
urlpatterns = [
path('', TemplateView.as_view(template_name='index.html'))
]
and copy your index.html to the root of your templates folder.
then browse to http://localhost:63342, once you have it working, then you can work your way out to suit your project structure.
Not opening the base.html template. The view function points to the the child data file. When I remove the extends statement from that, the child block data displays. So it is that Django is not interpreting the extends statement in the data file correctly when it exists. I can find no discussion of what might cause that to happen. And no error messaging. Kind of makes a deal breaker out of django.
You are probably opening the template itself rather than calling the development server. If Django has a problem with any of those things, it throws an error. It does not spit out the template code.

Creating hierarchical urls in Django

I'm dabbling in django for the first time and I'm stuck on one single issue and it's driving me crazy. I'm trying to create a set of pages with a hierarchical url like this www.example.com/{state}/{county}. Basically the problem I'm having is that I can get www.example.com/{state}, but I don't know how to use the url system in django to carry the state over to the state/county page. What I end up getting is www.example.com//{county}
urls.py
app_name = 'main'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<pk>[A-Z]{2})/$', views.StateView.as_view(), name='state'),
url(r'/(?P<pk>[a-zA-Z]*)/$', views.CountyView.as_view(), name='county'),
]
views.py
def index(request):
return render(request, 'main/index.html', {})
class StateView(generic.ListView):
template_name = 'main/state.html'
context_object_name = 'county_list'
def get_queryset(self):
counties = [ // list of a couple counties for testing purposes]
return counties
class CountyView(generic.ListView):
template_name = 'main/county.html'
context_object_name = 'water_list'
def get_queryset(self):
return WaWestern.objects.filter(water_name__contains='Orange') // hard coded for easy testing
index.html
this file is large so I'll just show an example of one of my state links
<a id="s06" href="CA">
state.html
{% if county_list %}
<ul>
{% for county in county_list %}
<li>{{ county }}</li>
{% endfor %}
</ul>
{% else %}
<p>No counties were found.</p>
{% endif %}
I realize this can all be solved by adding a column in my db for the state but I'm 100% sure this can be solved pretty simply, I'm just not sure how
Your url pattern for county is slightly off:
url(r'^(?P<state_pk>[A-Z]{2})/(?P<county_pk>[a-zA-Z]*)/$', views.CountyView.as_view(), name='county')
Hierarchical URL patterns would work with inclusions. Here, it is not a nested URL structure, so it would not match the county, followed by state unless you have a regex pattern to match that.
Also, note the change of the regex pattern name - you might have to tweak your views and templates accordingly

Displaying tables error argument to reversed () must be a sequence [duplicate]

This question already has an answer here:
Django tutorial, Getting: TypeError at /admin/ argument to reversed() must be a sequence
(1 answer)
Closed 6 years ago.
I'm developing a little app where I can display all the tables in my database (sqlite3) and, choosing one of them, visualize the data ( I know I can do that with the admin, but I need to se that in the app)
I have in my model.py different models, something like myModel1, myModel2...
In my views.py
def myhomepage(request):
tables_list = connection.introspection.table_names()
return render(request, 'myhomepage.html', { 'tables_list': tables_list})
def detail_table(request, table):
try:
Table_to_View = ContentType.objects.get(app_label="myapp", model=table)
except Table_to_View.DoesNotExist:
raise Http404 ("La tabella non esiste")
context = {'Table_to_View' : Table_to_View }
return render(request, "detail_table.html", context )
and the template myhomepage.html
{#something#}
<title>Lista delle tabelle</title>
<body>
{% if tables_list %}
<ul>
{%for t in tables_list %}
<li> {{table}}</li>
{% endfor %}
</ul>
{% endif %}
this is the urls.py
from django.conf.urls import url
from . import views
urlpatterns = {
url(r'^$', views.myhomepage, name='myhomepage'),
url(r'^(?P<table>.*)/$', views.detail_table, name='detail_table'),
}
but it highlights this
{% url 'detail_table' t %}"
and gives me this error:
argument to reversed () must be a sequence
How can I resolve this?
Thank you.
ps: if there is any more clever way to do this, I accept advise!
[edit] adding the view detail_table and urls.py
You are using {} instead of [] for your urlpatterns.
urlpatterns = [
url(r'^$', views.myhomepage, name='myhomepage'),
url(r'^(?P<table>.*)/$', views.detail_table, name='detail_table'),
]
Square braces not curly.

Django-cms - Selected templates never displayed

I recently started to work with Django-cms. I just created two templates base.html and home.html (this latter extends base.html), registered them into settings.py like this :
CMS_TEMPLATES = (
('base.html', 'Default'),
('home.html', 'Homepage'),
)
I've created my home page within the admin and selected the Homepage template but the content of this file is never shown.
I have followed the instructions from the documentation, but I don't understand where my mistake.
Anyone has any idea ?
Did you check your urls.py?
You have to make sure that you make a regualr expression that maps your views to your url and in your views you then call/load the template.
https://docs.djangoproject.com/en/dev/intro/tutorial03/
Little example on Kyle Calica's post:
in your urls.py you add something like this: (in your myproject/ folder where also your settings.py file is)
urlpatterns = patterns('',
url(r'^', include('myapp.urls')),
)
then in myapp.urls you need something like:
urlpatterns = patterns('',
url(r'^$', views.myview, name='myview'),
)
and then in your view:
def test(request):
return render(request, "my template.html")
and last in your template extend your base:
{% extends "base.html" %}
edit:
These are simple basics of django. if you dont grasp them i suggest you run the tutorial again and try to understand what they are actually doing.
Hi Hans (and #Kyle Calica-St), Thanks for your answer, but I have a correct urls configuration. I just created a new Blog app and I encountered the same problem. Here is my files :
settings.py
CMS_TEMPLATES = (
('base.html', 'Default'),
('home.html', 'Homepage'),
('news/home_news.html', 'News'),
)
urls.py
urlpatterns = i18n_patterns('',
# Homepage
url(r'^$', home_view),
# News
url(r'^news/', include('apps.news.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('cms.urls')),
)
views.py
def home_view(request):
return render(request, 'home.html')
home.html
{% extends "base.html" %}
{% load cms_tags %}
{% block base_content %}
{% placeholder home_content %}
<p>Hello World !</p>
{% endblock %}
Idem for news app
When I access to the homepage, I don't see the "Hello World !" p HTML tag.
I tried to change the order of the urls matches with no results.

Categories