django url not working except admin - django

hi guys my django app urls are not working
below is my project urls.py
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('recipe.urls', namespace="recipe")),
)
and here is my app urls.py
from django.conf.urls import patterns,url
urlpatterns = patterns('recipe.views',
url(r'^$', 'index', name='index'),
url(r'^create/recipe/$', 'create_recipe', name='create_recipe'),
url(r'^create/ingredients/(?P<recipe_id>\d+)/$', 'create_ingredients',
name="create_ingredients"),
url(r'^create/steps/(?P<recipe_id>\d+)/$', 'create_steps',
name="create_steps"),
url(r'^view/recipe/(?P<recipe_id>\d+)/$', 'view_recipe',
name="view_recipe"),
)
I am not able to get the index page and other urls except admin is working fine. Please help me

From the question comments it seems you are having issues with Django's templates instead of urlconfig. Here is how Django templates work. In your settings.py you define a variable TEMPLATES_DIRS where you specify a tuple of all directories where Django will look for templates.
Assume you have the following TEMPLATES_DIRS:
TEMPLATES_DIRS = (
'/absolute/path/to/foo',
'/absolute/path/to/bar',
)
Then if you look for a template base.html, Django will look for it in the following places and will use the first location if it finds one:
/absolute/path/to/foo/base.html
/absolute/path/to/bar/base.html
In your case you mentioned that you store your templates in both the Django's project folder as well as the app's folder. In that case you have to make sure that both folders are defined in TEMPLATES_DIRS like:
TEMPLATES_DIRS = (
'/absolute/path/to/project/templates',
'/absolute/path/to/app/templates',
)
Then in your case Django will be able to find both base.html and index.html. Now to make things simpler you can define PROJECT_PATH in your settings.py which will store the absolute path to your project path so that you can easily move your project to a different location. I think this is where your issue might be. In Django >= 1.4, you have the following project structure:
/project <= this should be your PROJECT_PATH
/project <= instead of this
templates/
base.html
settings.py
/recipe
templates/
index.html
models.py
With that in mind try using something like this:
PROJECT_PATH = os.path.abspath(os.path.join(__file__, '..', '..'))
PROJECT_NAME = os.path.basename(PROJECT_PATH)
TEMPLATES_DIRS = (
os.path.join(PROJECT_PATH, PROJECT_NAME, 'templates'),
os.path.join(PROJECT_PATH, 'recipe', 'templates')
)
In the above PROJECT_PATH calculates the absolute path of the project. Imagine that your settings.py is located at /some/path/project/project/settings.py. Then you compute the project path as follows:
>>> # settings.py
>>> print __file__
/some/path/project/project/settings.py
>>> print os.path.join(__file__, '..', '..')
/some/path/project/project/settings.py/../../
>>> # now abspath normalizes the path two levels up
>>> print os.path.abspath(os.path.join(__file__, '..', '..'))
/some/path/project
>>> # now you figure out the project name so that you can get the project templates folder
>>> print os.path.basename(os.path.abspath(os.path.join(__file__, '..', '..')))
project
>>> print os.path.join(PROJECT_PATH, PROJECT_NAME, 'templates')
/some/path/project/project/templates
>>> print os.path.join(PROJECT_PATH, 'recipe', 'templates')
/some/path/project/recipe/templates

In your settings.py, find and edit this -
TEMPLATE_DIRS = (
os.path.join(os.path.abspath(os.path.dirname(__file__)), "templates"),
)

Related

MEDIA_URL Page 404 Error Django

I am running on a local server and when I go to http://127.0.0.1:8000/media/ in my browser it says page not found.
Settings:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
Root URL:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^polls/', include('mysite.polls.urls')),
url(r'^admin/', admin.site.urls),
url(r'^submit/', include('mysite.uploads.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Model for User Upload:
from django.db import models
class Document(models.Model):
description = models.CharField(max_length=255, blank=True)
document = models.FileField(upload_to='documents/')
uploaded_at = models.DateTimeField(auto_now_add=True)
Following the Django documentation:
Serving files uploaded by a user during development
During development, you can serve user-uploaded media files from MEDIA_ROOT using the django.contrib.staticfiles.views.serve() view.
This is not suitable for production use! For some common deployment strategies, see Deploying static files.
For example, if your MEDIA_URL is defined as /media/, you can do this by adding the following snippet to your urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
https://docs.djangoproject.com/en/1.10/howto/static-files/
As pointed above in the comments by Alasdair, This is the normal behaviour of Django. If you visit the full file path like 127.0.0.1/media/file.jpg, Django will render the file instead of raising a 404 error.
Why is this happening?
If you look at the source of the view that serves the media/static files, you'll find these lines:
if os.path.isdir(fullpath):
if show_indexes:
return directory_index(newpath, fullpath)
raise Http404(_("Directory indexes are not allowed here."))
What it does is, it checks if the path requested is a directory or not. If yes, then it checks if the variable show_indexes is True, then it will return the index of the files inside the media directory. Since, show_indexes is False by default, it raises 404.
To set show_indexes to True, you can do this:
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT, show_indexes=True)
This won't raise the 404 and will display a list of files inside media dir.
P.S.: I don't think displaying file indices is a good idea, unless, of course, that's something you really want. It puts server under extra load to generate the indices. And someone can download the files recursively using a program like wget etc. Even those files that are meant to be private.

Django v1.5, TemplateDoesNotExist error

In settings.py I've chosen to run with sqlite3 and name this database database.db.
from blog_app.views import oneView, anotherView
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^one/$', oneView),
url(r'^another/$', anotherView),
# Examples:
# url(r'^$', 'django_project.views.home', name='home'),
# url(r'^django_project/', include('django_project.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
and my views.py looks like this
# -*- coding:UTF-8 -*-
from django.shortcuts import render_to_response
def oneView(request):
return render_to_response("index.html", {"content":"Hello World, from oneView"})
def anotherView(request):
return render_to_response("index.html", {"content":"Hello Again, from anotherView"})
my dir to the index.html is blog/blog_app/templates/index.html. since by standard the settings.py file says this:
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
I think it's weird that it says that my index.html file cannot be found. isn't it looking in the correct directory?
nonetheless, I only get a "TemplateDoesNotExist at /one/" error when I try to go to
127.0.0.1:8000/one/ or 127.0.0.1:8000/another/
any ideas?
Try doing something like this in your settings.py
SETTINGS_PATH = os.path.dirname(__file__)
PROJECT PATH = os.path.join(SETTINGS_PATH, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
BLOG_PATH = os.path.join(PROJECT_PATH, "blog_app)
TEMPLATES_PATH = os.path.join(BLOG_PATH, "templates")
TEMPLATE_DIRS = (
TEMPLATES_PATH,
)
The error usually is due to incorrectly configured templates directory
What is your exact error message? (debug informations)
I use this kind of configuration for templates:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates')
)
They are accessible in the templates folder of your django application (aside manage.py), in a sub-folder named following the application used if set (it's not your case for the urls you provided us with).

TemplateDoesNotExist Django Error

I am trying to build a login page form. In my urls.py, I have linked the file to the built in Django login view, and pass in the path to a template directory. I have login folder inside the template and login.html file inside the login folder.
(r'^login/$', 'django.contrib.auth.views.login', {
'template_name': 'login/login.html'
}),
In settings.py, I have provided the directory where my templates are being stored.
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__),'templates'),
)
When I run the runserver command, it shows TemplateDoesNotExist
Exception Type: TemplateDoesNotExist
Exception Value:login/login.html
For anyone experiencing the same problem, it turns out the template path was incorrect. I needed to use '../templates', instead of 'templates' in settings.py:
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__),'../templates'),
)
A better approach would be define your Directories in another settings file, to alleviate the need to use ugly relative path in your template dirs:
// _paths.py
SETTINGS_DIR = os.path.dirname(__file__)
// _templates.py
from settings/_paths.py import SETTINGS_DIR
TEMPLATE_DIRS = (
os.path.join(SETTINGS_DIR, 'templates'),
)
Adjust accordingly based on your folder structure.

Loading images in a static file

So I have completed the Django tutorial, play around with it some, and feel that I have a good understanding of Django. The only problem I am facing is that when I try to display a static page for a landing page, I cannot seem to get any images to load.
First off I have tried two different methods of displaying a static landing page.
First:
# main app urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name="landing/index.html")),
url(r'^polls/', include('polls.urls', namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
)
This is the main app's urls.py and I use the TemplateView to display the static index.html which is located at 'my_app/templates/landing/index.html'.
This is all and well until I try to add a static image into the index.html file. No matter where I put the image file I cannot seem to get it to display. In the index.html template I have tried different methods of using static as well as trying different direct paths without the need for the embedded python code. How am I supposed to display images and where should they be located?
The second method I found that worked for just displaying the static page (not the image) was to create a new app called landing and have that simply display a static page from the urls.py in the same manner(using TemplateView). Is this method better? I still had the same problems in displaying an image within the static page as the first method, which makes me think it has something to do with the TemplateView.
Am I doing this completely wrong? What are my options? I am using Django 1.5.1.
Thanks in advance!
It is a bit awkward to serve statics files with Django. This is because they have the conception that static files such as images must be in another domain or server for performance/security reasons.
To serve static content with django do this:
# urls.py
# add this lines at the end
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Then in settings.py define the directory where the images/css/js and similar static contents are:
# settings.py
import os
settings_dir = os.path.dirname(__file__)
PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir))
STATIC_URL = '/static/'
STATICFILES_DIRS = (
# this assumes your static contents is in <your_project>/static/
os.path.join(PROJECT_ROOT, 'static/'),
)
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media/')
MEDIA_URL = '/media/'
Note: You may also consider images as media and place them in your media/ folder.
That should get static files served with your app. Just reference them like this href="/static/xxxx.jpg" or href="/media/xxxx.jpg".
Hope it helps!
This blog explains serving static file and might help:
http://agiliq.com/blog/2013/03/serving-static-files-in-django/

Django App URL model not importing

Im certain that this is something simply that Im overlooking but Im too irritated to figure it out alone so thanks in advance.
Project Directory Structure
*UPDATED*
myproject/
manage.py
myproject/
apps/
geo/
urls.py
settings.py
urls.py
urls.py
from django.conf import settings
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.contrib.gis import admin
admin.autodiscover()
from pinax.apps.account.openid_consumer import PinaxConsumer
handler500 = "pinax.views.server_error"
urlpatterns = patterns("",
url(r"^$", direct_to_template, {'template' : 'home.html' }, name="home"),
url(r"^admin/invite_user/$", "pinax.apps.signup_codes.views.admin_invite_user", name="admin_invite_user"),
url(r"^admin/", include(admin.site.urls)),
url(r"^about/", include("apps.about.urls")),
url(r"^account/", include("pinax.apps.account.urls")),
url(r"^openid/", include(PinaxConsumer().urls)),
url(r"^profiles/", include("idios.urls")),
url(r"^notices/", include("notification.urls")),
url(r"^announcements/", include("announcements.urls")),
url(r"^products/", include("products.urls")),
url(r"^locate/", include("geo.urls")),
url(r"^sectors/", include("sectors.urls")),
)
if settings.SERVE_MEDIA:
urlpatterns += patterns("",
url(r"", include("staticfiles.urls")),
)
settings.py
INSTALLED_APPS = [
# project
"tulsa-site.apps.about",
"tulsa-site.apps.profiles",
"tulsa-site.apps.geo",
"tulsa-site.apps.sectors",
]
When I go to the url path "http://127.0.0.1:8000/locate/" is receive the error message: I recieve the exception value "No module named geo.urls." What am I missing?
include("geo.urls") tells Django to look for geo.urls relative to the manage.py file. So its essentially looking for this file:
myproject/
manage.py
myproject/
apps/
settings.py
urls.py
geo/
urls.py <- this file
That is sort of the new directory structure starting with Django 1.4 which encourages to have apps independent of the Django project. However if you still follow the old layout where the apps folders are within the project folder, then you have to change your imports to reflect that:
include("myproject.geo.urls")
EDIT
Following your updated layout:
include("myproject.apps.geo.urls")
url(r"^locate/", include("tulsa-site.apps.geo.urls"))