I am trying to print a response from the view.. but django shows the page not found error(404)
My main project.urls are:-
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from . import views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'ultimatefinalblog.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$',views.siteindex,name="siteindex"),
url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^markdown/', include('django_markdown.urls')),
)
my blog's urls.py are:-
from django.conf.urls import patterns, url
from blog import views
urlpatterns = patterns('',
#url(r'^$', views.BlogIndex.as_view(), name="index"),
#url(r'^(?P<slug>\S+)$', views.BlogDetail.as_view(), name="entry_detail"),
#url(r'^$', views.testview, name="testview"),
url(r'^$', views.index, name="index"),
url(r'^(?P<slug>\S+)$', views.detail, name="entry_detail"),
url(r'^testingpage/', views.testview, name='testview'),
)
I have defined the testview function in my views.py
def testview(request):
return HttpResponse("testing our view!")
When i try to run the url 127.0.0.1:8000/blog/testingpage in my development server it shows the page not found error...can somebody help me solve this problem?
Here is your issue:
In your URL patterns,
url(r'^(?P<slug>\S+)$', views.detail, name="entry_detail"),
url(r'^testingpage/', views.testview, name='testview'),
The testingpage is being matched with ?P<slug>\S+ (for views.detail), before views.testview, and you probably have a raise 404 or something similar line of code to match slug.
So, Change the order:
url(r'^testingpage/', views.testview, name='testview'),
url(r'^(?P<slug>\S+)$', views.detail, name="entry_detail"),
And it should work for you.
Also, Slug is generally matched with (?P<slug>[\w-]+) and not \S+
So!
I succeded to make your code work.
I'll organize this answer in three parts (beware : It will be exhaustive!) :
First :
I'll copy the code I made (almost the same as yours, plus the parts you didn't provide and I had to recode - these are very basic, just to fill the missing parts). I hope it will help you to find how to fix your problem by comparing. I'll also give an hypothesis about your problem.
Second :
I'll talk about your code. There are good habits that could help you to build your django projects (but you don't seem to use these). Please note that your code can work without using these. But it may be more difficult without these habits.
Third :
I will suggest a corrected version of your code with comments to illustrate the second part.
First - The code that works on my computer :
I make my own version of your project with django 1.7.5.
I organized the project like this :
.
├── blog
│ ├── __init__.py
│ ├── admin.py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── main
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── views.py
│ └── wsgi.py
└── manage.py
Where "main" is the project name and "blog" an app.
From a fresh project, the files I had to modify/add are :
blog/urls.py :
from django.conf.urls import patterns, url
from blog import views
urlpatterns = patterns('',
#url(r'^$', views.BlogIndex.as_view(), name="index"),
#url(r'^(?P<slug>\S+)$', views.BlogDetail.as_view(), name="entry_detail"),
#url(r'^$', views.testview, name="testview"),
url(r'^$', views.index, name="index"),
url(r'^(?P<slug>\S+)$', views.detail, name="entry_detail"),
url(r'^testingpage/', views.testview, name='testview'),
)
blog/views.py :
from django.shortcuts import render, HttpResponse
# Create your views here.
def testview(request):
return HttpResponse("testing our view!")
def index(request):
return HttpResponse("Index.")
def detail(request, slug="test"):
return HttpResponse("Detail : " + slug)
main/urls.py :
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from . import views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'main.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$',views.siteindex,name="siteindex"),
url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^markdown/', include('django_markdown.urls')),
)
main/views.py :
from django.shortcuts import render, HttpResponse
# Create your views here.
def siteindex(request):
return HttpResponse("site index!")
Then I just do :
>>>python manage.py migrate
>>>python manage.py runserver
And I can access to http://127.0.0.1:8000/blog/testingpage/ and to other pages. I have no problem this way.
But I you do so, you will see that this URL matches with the r'^(?P<slug>\S+)$' pattern. And therefore /blog/testingpage does not trigger the view testview but the view detail.
So I think your problem may come from the detail view, could you add it to your question to check?
Second - How you could improve your code :
apps and views imports
The way you imports your views is functionnal, but it could be impractible
You could add the app ("blog") containing your views to INSTALLED_APPS in your main/settings.py. And you will be able to use your views just by entering their names as strings.
edit :
This changed with the 1.8 release, now it's recommended to do like you did. My bad.
Your project isn't an app.
Your /main/urls.py suggests that you've a views.py in your /main directory.
Using this directory this way isn't explicitly forbidden, but it's an app's purpose. the /main directory is meant to contain general settings.
I think you should make a second app for your views.py (and probably some url patterns) if you don't want to insert it in the "blog" app.
urlpatterns order
With your blog/urls.py file, your app will "works". But /blog/testingpage/ will trigger the detail view and not the testview view, I'm not sure that is what you want to do. Beware the patterns order!
Third - An other way to do this :
Here is my version of the code.
I have organized the project like this :
.
├── blog
│ ├── __init__.py
│ ├── admin.py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── main
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
└── website
├── __init__.py
├── admin.py
├── models.py
├── tests.py
├── urls.py
└── views.py
The new files are :
blog/urls.py
from django.conf.urls import patterns, url
# You don't need this anymore
# from blog import views
urlpatterns = patterns('blog.views', # this first argument will be used as a prefix to locate your views.
url(r'^$', 'index' , name="index"),
# beware the order!
# url(r'^(?P<slug>\S+)$', views.detail, name="entry_detail"),
url(r'^testingpage/', 'testview', name='testview'),
url(r'^(?P<slug>\S+)$', 'detail', name="entry_detail"),
)
blog/views.py
from django.shortcuts import render, HttpResponse
# Create your views here.
def testview(request):
return HttpResponse("testing our view!")
def index(request):
return HttpResponse("Index.")
def detail(request, slug="test"):
return HttpResponse("Detail : " + slug)
INSTALLED_APP in main/settings.py (/!\ Important /!\)
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'website',
)
main/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'main.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/', include('blog.urls')),
url(r'^markdown/', include('django_markdown.urls')),
url(r'^$', include('website.urls')),
)
website/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
# If you add the app name to INSTALLED_APP you don't need this anymore.
# from . import views
urlpatterns = patterns('website.views', # This first argument will be used as a prefix to locate your views.
url(r'^$', 'siteindex', name="siteindex"),
)
website/views.py
from django.shortcuts import render, HttpResponse
# Create your views here.
def siteindex(request):
return HttpResponse("site index!")
I hope all of this will help.
Related
My diretory looks something like this:
project
|_app
|_ media
|_ profile_pics
|_ 1x1.jpg
|_ templates
|_ urls.py
...
I already specified the MEDIA settings on the settings.py:
# This part is right below the BASE_DIR
MEDIA_DIR = os.path.join(BASE_DIR, 'media')
# This part is right at the end of the file
# Media
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
On my urls.py:
from django.conf.urls.static import static
from pro_five import settings
from . import views
app_name = 'my_app'
urlpatterns = [
url('^$', views.index, name='index'),
url(r'^registration/', views.register, name='register'),
url(r'^login/', views.user_login, name='user_login'),
url(r'^logout/', views.user_logout, name='logout'),
url(r'^profile/', views.profile, name='profile')
]
urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)
And finally on my template:
<img src="media/profile_pics/1x1.jpg" alt="asdasdasd"><br>
I don't know why but it just doesn't show up. I followed a lot of solutions only but seems nothing to work for me. I'm relatively new to Django so please forgive my naiveness.
Any advices? Thanks a ton!
My bad.
I misplaced the codes that was supposed to go to the project's urls.py not to the app's urls.py.
Also it's this:
from django.conf import settings
from django.conf.urls.static import static
Not:
from django.conf.urls.static import static
from myproject import settings
I was just checking out django, and was trying a view to list the books by passing id as an argument to the URL books/urls.py. But getting 404 page not found error. I'm not getting whats wrong in the url when I typed this url in the browser:
http://192.168.0.106:8000/books/list/21/
bookstore/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('books/', include("books.urls"))
]
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'books'
]
...
...
...
ROOT_URLCONF = 'bookstore.urls'
books/urls.py
urlpatterns = [
path('home/', create),
path('list/(?P<id>\d+)', list_view),
]
books/views.py
def create(request):
form = CreateForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request, "Book Created")
return redirect('/books/list', kwargs={"id":instance.id})
return render(request, "home.html", {"form":form})
def list_view(request, id=None):
books = Book.objects.filter(id=id)
return render(request, "list.html", {"books": books})
Project Structure:
├── books
│ ├── admin.py
│ ├── forms.py
│ ├── __init__.py
│ ├── models.py
│ ├── urls.py
│ └── views.py
├── bookstore
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
Here is the screenshot -
EDIT - As addressed in the comments - Tried by appending / in the url expression of thebooks.urls but no luck :(
You are using the new path from Django 2.0 incorrectly. You shouldn't use a regex like \d+. Try changing it to:
path('list/<int:id>/', list_view, name='list_view'),
The name is required if you want to reverse the URL.
If you want to stick with regexes, then use re_path (or url() still works if you want to be compatible with older versions of Django). See the URL dispatcher docs for more info.
Note the trailing slash as well - otherwise your path matches http://192.168.0.106:8000/books/list/21 but not http://192.168.0.106:8000/books/list/21/.
The structure of my project is this:
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
Home/
templates/
Home/
Home.html
Login/
templates/
Login/
Login.html
Application/
templates/
Application/
Application.html
Details.html
mysite/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('Home.urls', namespace="Home")),
url(r'^Application', include('Application.urls',
namespace="Application")),
url(r'^Login', include('Login.urls', namespace="Login")),
url(r'^User', include('User.urls', namespace="User")),
]
Home/urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^', views.Home, name = 'Home'),
]
Application/urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'Application', views.Application, name = 'Application'),
]
The structure for the views.py(s) is the same for each app (with changes in names, of course).
Home/views.py
from django.shortcuts import render
def Login(request):
return render(request, 'Login/Login.html')
I have two links in my Home.html. One is supposed to direct a user to Application.html and the other, to Login.html. I tried to do the followings:
templates/Home/Home.html
Apply Now!
Apply Now!
Login
None of them work. No errors, no redirections, nothing.
What is weird about this whole thing is that url changes for Login and Application look different, even though the structure of both apps are the same:
The url changes to:
http://localhost:8000/ApplicationApplication.html
vs
http://localhost:8000/Login/Login.html.
Would greatly appreciate any help!
mysite / urls.py
url(r'^Application', include('Application.urls',
namespace="app")),
Application/Application.urls
urlpatterns = [
url(r'Application', views.Application, name = 'application'),
]
home.html
Apply Now!
Please change to retry
I'm new in Django and use this tutorial for learning https://docs.djangoproject.com/en/1.6/intro/tutorial03/
Have a little problem with routing in.
View code:
def index(request):
return HttpResponse(r'<h3 style="font-style: bold;">Index</h3>')
URL config code:
1. blog/urls
urlpatterns = patterns('',
url(r'^$', views.index, name='index')
)
2.project/urls
urlpatterns = patterns('',
url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
When i come for 127.0.0.1:8080/index that
Page not found (404)
Using the URLconf defined in les1.urls, Django tried these URL patterns, in this order:
^blog/
^admin/
The current URL, index, didn't match any of these.
Struct of project
blog/
templates
__init__.py
admin.py
models.py
tests.py
urls.py
views.py
les1/
__init__.py
settings.py
urls.py
wsgi.py
db.sqlite3
manage.py
Can't find error:(
What is the actual url you enter in your browser ? is it 127.0.0.1:8000 or 127.0.0.1:8000/index ? From your post, I assume it is the second:
The current URL, index, didn't match any of these.
What if you enter 127.0.0.1:8000/blog ?
index is the name of your route, used only on server-side. It's a shortcut used for quick reversing and displaying of URL:
from django.core.urlresolvers import reverse
print(reverse('index'))
# will output "/blog", which is the actual URL
Remove r from view code.
def index(request):
return HttpResponse('<h3 style="font-style: bold;">Index</h3>')
There are many similar questions posted already, but I've already tried those solutions to no avail. I'm working through a basic Django tutorial, and here is my code:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'tango_with_django_project.views.home', name='home'),
# url(r'^tango_with_django_project/', include('tango_with_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)),
url(r'^rango/', include('rango.urls')), # ADD THIS NEW TUPLE!
)
views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Rango says hello world!")
From the settings.py file
ROOT_URLCONF = 'tango_with_django_project.urls'
Hope you all can help get me started
Let's say I have a Django project called FailBook, with two apps, posts and links. If I look into FailBook/urls.py, I will find something like
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^posts/', include('posts.urls')), ## Custom url include
url(r'^links/', include('links.urls')), ## Custom url include
)
So then, when you look into the directory structure, you will notice that there are extra two urls.py files
FailBook
|-- posts
|-- models.py
|-- urls.py
|-- views.py
|-- etc.
|-- links
|-- models.py
|-- urls.py
|-- views.py
|-- etc.
# urls.py file in the posts folder
from django.conf.urls import patterns, include, url
from .views import PostListView, PostDetailView
urlpatterns = patterns('',
url(r'^posts/', PostListView.as_view()),
url(r'^posts/(?P<post_id>\d+)', PostDetailView.as_view()),
)
# where both views are class based views, hence the as_view function call
I know this was already solved, but the solutions provided did not help me. When I had this error it was as simple as checking all of the directories that should have had urls.py files.What I discovered was that the urls.py had not been added to the SVN repository that our Django app was pulled from.
I recommend looking in the projectname->projectname->urls.py for all references to app specific urls, and verifying that the urls.py file exists for each of them.
I had this issue while doing a Pluralsight Django tutorial. Two things I noticed:
1) I was using Django 2.0, and the command url() from Django 1.11 has been replaced with re_path() in 2.0, obtained by importing as follows:
from django.urls import path, include, re_path
This replaces,
from django.conf.urls import url, include
see this: Django 2.0 release notes
and,
2) I accidentally called the file to be imported from the subfolder, url.py, not urls.py
e.g. rango/url.py not rango/urls.py.
This was probably the main issue, and all flowed smoothly after that fix.