how to solve ViewDoesNotExist - python

I'm new to Django 1.4 and try my first project. It's OK to create the app:
./manage.py startapp APP_NAME
and recognized by Django in urls.py as following:
(r'^home/$', 'APP_NAME.views.home'),
but when I only create a APP_NAME.py files in root directory of projects,and change the urls.py file as following:
(r'^home/$', 'APP_NAME.home'),
the debug page tell me ViewDoesNotExist. Even if I change the urls.py file to (with from...import and without single quotes):
from APP_NAME import home
(r'^home/$', home),
It also doesn't work.
How to solve it? It intricate to create APP for every view file.

Have you actually implemented your home function in 'APP_NAME.__init__.py'; if not, your code will not work, because there is nothing that can be called

python manage.py startapp news
In your created news directory there is a views.py. Now lets add something:
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello")
now in your urls.py you add this:
(r'^news/$', 'news.index'),
Just start the devserver python manage.py runserver and point your browser to http://localhost:8000/news/
You should see "Hello".
Now you could add in your news/views.py some more stuff - like details, archive and so on.
Also be sure to have an empty __init__.py file in every directory you'd like to import.
from app.views import something will not work if there's no init-file within the app-directory.

Related

RedirectView.as_view not working at the root

In a django 1.8 project, I am attempting to redirect http://myProject/ads.txt to an external url http://a.location.that.has.the.ads.txt.file and thus serve the ads.txt file without using ftp to simply place the ads.txt in the root.
Given this minimal directory structure:
django projects
myProject
myapp
urls.py
views.py
someotherapp
yetanotherapp
myProject
settings.py
urls.py (this is the top urls.py)
views.py
in myProject/myProject/urls.py, (the “top” urls.py) I have as the first entry in the urlpatterns list, the lines:
urlpatterns = patterns('',
(r'^ads\.txt', RedirectView.as_view(url='http://a.location.that.has.the.ads.txt.file', permanent=False)),
followed by many more pattern matching regex’s. This does not work and fails with a 404. What does work is
urlpatterns = patterns('',
(r'^foo/ads\.txt', RedirectView.as_view(url='http://a.location.that.has.the.ads.txt.file', permanent=False)),
and then calling http://myProject/foo/ads.txt
Unfortunately, ads.txt files must be placed at the site root. I have tried many different regex’s that test fine in a regex validator, but just don’t work (returns 404). How do I do this without the extra dir “foo”? Any thoughts appreciated. Thank you.
Turns out you cannot redirect with the top level urls.py "routing table" to above the Django project root. A nginx server level redirect did the trick.

Django TemplateDoesNotExist, but traceback reaches views.py

I have a begin.html file that I'm trying to access at localhost:8000/begin, but I get the DjangoTemplateDoesNotExist error when trying to access it.
The only thing in that template is
<h1>welcome to my app !</h1>
and it's in the app/template directory.
In the same app directory is my views.py file, which contains
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
# Create your views here.
def begin(request):
print("DEBUG STATEMENT")
return render(request, "template/begin.html", {})
The return statement in begin is reached, as both the print statement and the traceback tell me, but Django can't find the template after.
If it's relevant, my urls.py file is
from django.conf.urls import url
from django.contrib import admin
from app.views import begin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^begin/$', begin, name = 'begin')
]
in the project directory.
Since you have not provided the information, i take it as you mean urls.py inside your app. If you have two urls.py you need to redirect from the first urls where django looks to the other one.
from django.conf.urls import include
urlpatterns = [
url(r'^', include('YOURAPPNAME.urls'))
]
In your appdirectory in urls.py write
from . import views //importing views from current directory
urlpatterns = [
url(r'^begin/$' views.begin, name=begin)
]
Another tip, consider using render_to_response when you are using a http response, i know render is newer but since you're using a response i would go with render_to_response in your case, and skip the context.
return render_to_response('YOURAPPNAME'/begin.html)
Check if your template structure like this,
your_app_name
--> **templates**
--> **your_app_name**
--> **'begin.html'**
--> static
--> models.py
--> ........
Then, change your views, like this,
return render(request, "your_app_name/begin.html", {})
Django as default check for the directory under the name "templates", in your app_directory.
When accommodating multiple apps, for easiness ​templates are kept under the directory with app_name.
From the docs,
It’s possible – and preferable – to organize templates in subdirectories inside each directory containing templates. The convention is to make a subdirectory for each Django app, with subdirectories within those subdirectories as needed.
Do this for your own sanity. Storing all templates in the root level of a single directory gets messy.
When APP_DIRS is True, DjangoTemplates engines look for templates in the templates subdirectory of installed applications. This generic name was kept for backwards-compatibility.

Can you name a Django app: urls

I'm trying to use this line in urls.py:
from mysite.urls.views import Index
However, Django is saying
ImportError at /
No module named views
I think that is because it's going into /mysite/mysite/urls.py and not /mysite/urls/views.py
The structure is like this (omitted the uninvolved files):
mysite/
templates/
mysite/
settings.py
urls.py
urls/
views.py
manage.py
I found out that was my problem. I followed How to change the name of a Django app? and my problems went away. Long story short, don't name your app: urls.
Add an empty __init__.py inside your urls folder. Why that should work? Take a look here and here
Absolute imports may be what you need:
from __future__ import absolute_import
Credits to this answer: https://stackoverflow.com/a/4931577/1028012

Create a view in django

Very new to django. I'm using version 1.5.2 and I just did a fresh install. I'm using the django development server; I'll be moving to Apache down the road, but I want to understand the django's particular flavor of MVC methodology before doing taking that step.
So I start up the django server with `python manage.py runserver 0.0.0.0:8000' through the terminal in my project directory (django_books). I get this error:
ViewDoesNotExist at /
Could not import django_books.views.home. Parent module django_books.views does not exist.
So my view doesn't exist. My view.py file is empty because the tutorial I was following did not include one. I'm not sure if this is the problem. If it is, how do I create this file (what goes in it)?
Directory Structure:
django_books
beer (from the tutorial lol)
migrations
__init__.py
models.py
views.py
random_book
(same as beer above)
django_books (this is my actual django project, beer and random_book are apps)
__init__.py
settings.py
urls.py
wsgi.py
media
.gitignore
manage.py
requirements.txt (output from pip freeze command)
urls.py
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'django_books.views.home', name='home'),
# url(r'^django_books/', include('django_books.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)),
)
If you keep your urls.py the way it is, that means you need to create views.py within /django_books/django_books/
Within that file, create a new function called home.
Alternately, if you have any functions inside of /django_books/beer/, you could reference them from urls.py.
All urls.py does is expose a python path to a function and route a URL there. So you can see that you don't have a module or file called views within django_books/django_books, which is why you get the failure.
View is basically a python function that receives HTTP Request and returns HTTP Response.
Quote from docs:
A view function, or view for short, is simply a Python function that
takes a Web request and returns a Web response. This response can be
the HTML contents of a Web page, or a redirect, or a 404 error, or an
XML document, or an image . . . or anything, really. The view itself
contains whatever arbitrary logic is necessary to return that
response. This code can live anywhere you want, as long as it’s on
your Python path. There’s no other requirement–no “magic,” so to
speak. For the sake of putting the code somewhere, the convention is
to put views in a file called views.py, placed in your project or
application directory.
This line url(r'^$', 'django_books.views.home', name='home'), in urls.py points the index / of your site to the home view - you should create it.
Create a python function called home in views.py:
from django.http import HttpResponse
import datetime
def home(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
Restart your development server and visit http://127.0.0.1:8000.
FYI, read the tutorial more carefully, part 3 is about dealing with urls and views.

No Module named Contact Error-Chapter 7 Exercise in Django Book

I've received the following error when trying to set up a contact subdirectory inside the mysite directory.
Here is how I structured the urls.py script:
from mysite.contact import views as contact_views
(r'^contact/$', contact_views.contact),
Do I need to change anything in the settings.py TEMPLATE_DIRS, so, I can call the contact_form.html template correctly?
Yes, template_dirs needs to contain the path to the templates folder.

Categories

Resources