Trouble setting up django settings - django

I'm just learning Django and trying to setup the View and URLconfs (http://djangobook.com/en/2.0/chapter03/).
Inside my project folder "mysite" (/Users/NAME/Desktop/development/Python/djcode/mysite), I have the following two files:
views.py
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello world")
and urls.py
from django.conf.urls.defaults import *
from mysite.views import hello
urlpatterns = patterns('',
(r'^hello/$', hello),
)
However, when I run the test server, it shows a 404 page saying:
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^hello/$
The current URL, , didn't match any of these.
I think this has to do with my settings.py not being correct. What do I need to change in the settings.py file to point it to the correct destination?

You have no urlconf pattern corresponding to the root of your webserver. Add ^$ and make it go somewhere.

Looks like the URL you entered when testing it was "http://localhost:8000/". You should enter "http://localhost:8000/hello/" to see the output of the function you made.

Related

Django: URL Path not found jumps into next app

I have two apps:
backend
shop
I my urls in main app dir:
path('backend/', include('backend.urls')),
path('', include('shop.urls')),
the problem is if I write in my url: localhost:8000/backend/abc which not exist Django jumps over to shop.urls and the app is crashing because it can not find the slug and the query goes in fail.
How can I prevent if I go to the url /backend/somethingwhichnotexist is returning an 404 and not search in other app urls for this folder? I have thought that this is one of the main reason for split the urls in app folders.
Here are some urls from backend/urls.py:
from django.urls import path, re_path
from . import views as backend_views
from django.contrib.auth import views as auth_views
from froala_editor import views
from django.conf.urls import include
urlpatterns = [
path('stamdata/', backend_views.edit_masterdata),
path('praefikser/', backend_views.edit_prefixes),
path('leverandorer/', backend_views.suppliers_view),
path('leverandorer/add', backend_views.add_supplier),
]
handler404 = 'backend.views.page_not_found_view'
shop/urls.py
here the url stops:
path('<slug:category_slug>/<slug:slug_subcategory>/', butik_views.cat_or_article),
normally I don't want that a backend urls switches to frontend view
regards
Christopher.
You you said Django run through all of the URL patterns and stops till it finds its matching URL. SO, what has happen here is that when you type a URL with localhost:8000/backend/abc/ it runs through all the URLS before returning 404 to the client. So, it stops at the URL that support any string with 2 parameters in your case below URL.
path('<slug:category_slug>/<slug:slug_subcategory>/', butik_views.cat_or_article),
To get a 404 by adding a static word in you URL.
path('shop/<slug:category_slug>/<slug:slug_subcategory>/', butik_views.cat_or_article),
or
path('backend/', include('backend.urls')),
path('shop/', include('shop.urls')),
For now I fixed it with
shop/views.py
if category_slug == 'backend':
response = render(
request,
'backend/404.html',
)
response.status_code = 404
return response
else:
until I found another solution. It looks like that the URL dispatcher is working like this:
Django runs through each URL pattern, in order, and stops at the first
one that matches the requested URL, matching against path_info.
So for now I did not found another way.
Edit:
I added this in the end of backend/urls.py:
re_path(r'^.*/$', backend_views.page_not_found_view)
so after all working urls it goes to all other to the 404 view.

Page not found after trying to add a new path to the urlpatterns of main urls.py file? (Mosh Python Tutorial)

I'm following Mosh's tutorial video on Python. He begins the django section (https://youtu.be/_uQrJ0TkZlc?t=18085) by installing django 2.1. I am able to open a development server the first time as he does:
pip install django==2.1
django-admin startproject pyshop .
python manage.py runserver #server works
Here are the steps he goes through to add a "products" app/path:
python manage.py startapp products
Opens views.py from this new products folder and modifies code to this:
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return HttpResponse('Hello World')
Creates urls.py inside the products app/folder and adds this code:
from django.urls import path
from . import views
urlpatterns = [
path(' ', views.index) # Here should have been '' and now fixed
]
Opens the main urls.py in the pyshop folder and adds/modifies the end of the file like this:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('products/', include('products.urls'))
]
Mosh goes back to the server and adds /python to the url to get a page with "Hello World"
(https://youtu.be/_uQrJ0TkZlc?t=19220)
Upon trying to run the server again, I get Page not found error. Is there something I'm missing? I didn't figure it'd be a version issue since I made sure and installed the same 2.1 version.
As Jeffery and Daniel mentioned, I had an incorrect space and it needed to be an empty string in the products urls.py path. However, I'm still getting page not found error. Here's the exact error message if that helps:
Using the URLconf defined in pyshop.urls, Django tried these URL patterns, in this order:
admin/
products/
The empty path didn't match any of these.
Modify your url path in the products app/folder like this
urlpatterns = [
path('', views.index)]
Remove the space in between

django urls: "Django tried these URL patterns"

I am trying a tutorial on Django called blog. I have the following structure:
FirstBlog|FirstBlog
settings
urls
__init__
etc
blog
templates | index.html
migrations
views.py
manage.py
The view.py has
from django.shortcuts import render
from django.shortcuts import render_to_response
from blog.models import posts
def home(request):
return render('index.html')
The urls.py has
from django.conf.urls import url
from django.conf.urls import include
from django.contrib import admin
urlpatterns = [
url(r'^blog', 'FirstBlog.blog.views.home',name='home'),
]
and I get this error:
Using the URLconf defined in FirstBlog.urls, Django tried these URL patterns, in this order: ^blog [name='home']
The current URL, , didn't match any of these.
I can't seem to get it right..
Any help would be appreciated.
Thank you,
You are requesting for / url and you have not saved any such mapping. Current mapping is for /blog . So it will work for the same url.
i.e goto the browser and request /blog
If you need it to work for / then change the urls appropriately.
within your blog app, create a urls.py file and add the following code which calls the home view.
blog/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'^',views.home, name='home'),
]
then in your root urls file which can be found at FirstBlog/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^blog/',include('blog.urls')), #when you visit this url, it will go into the blog application and visit the internal urls in the app
]
PS:
your templates should be in blog/templates/blog/index.html
Read this docs on templates to understand how django locates templates.
This one is to understand how urls work Urls dispatcher
You are doing this in the wrong way! Try doing that using TemplateView from class-based views, which are the current standard from django views.
Check the django documentation: https://docs.djangoproject.com/en/1.9/topics/class-based-views/
Use this at the urls.py:
from django.conf.urls import url
from django.views.generic import TemplateView
urlpatterns = [
url(r'^blog/', TemplateView.as_view(template_name="index.html")),
]
And then, create a folder called templates in the project root ( like this: https://docs.djangoproject.com/en/1.9/intro/tutorial03/#write-views-that-actually-do-something ) named index.html
Simply go to file then select Save all your project instead of save. Or use shortcut Ctrl +k s on windows. Project should be able to sync and display the code on Django interface

Django 404.html for mobile site

My django site is having web & mobile versions. I have enabled debug setting false which returns templates 404.html whenever the requested page is not found. I would like to modify the view function to return 2 different 404 html pages like 404.html/404mobile.html based on platform.
Detecting user browser through JavaScript in 404.html page did not help as my 404.html page has header and footer extends from base html file.
Modifying views will solve this? If so where is the debug setting class file residing in Django package?
Here is the function using user_agent ..
from user_agents import parse
def idfy(request):
user_agent = parse(ua_string)
if user_agent.is_mobile:
return HttpResponse('I m n mobile')
else:
return HttpResponse('I m n pc')
from django.conf.urls import patterns, include, url
from django.views.static import *
from django.conf import settings
from django.conf.urls.defaults import handler404
from app.views import error
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'app.views.home', name='home'),
)
handler404 = error.error_handler
overriding handler404 method resolves this issue

Why are the Django project URLs not all available to the Django test client?

I've been trying to add the django-lean app to my project.
The django-lean app is not located in the project I'm working on, it is on the PYTHONPATH.
I have not been able to get the django-lean tests to pass.
It seems the issue is that the TestCase defines a value for urls:
urls = 'django_lean.experiments.tests.urls'
As best as I can tell, the tests are only getting the urls located # 'django_lean.experiments.tests.urls', but not
the urls from the rest of the project.
This is causing error messages like:
NoReverseMatch: Reverse for 'index' with arguments '()' and keyword arguments '{}' not found.
These are triggered by {% url %} template tags in the project.
How can I make sure that the all the urls of the project are available for the tests?
EDIT:
Someone showed me a script to print the visible URLs:
import urls
def show_urls(urllist, depth=0):
for entry in urllist:
print " " * depth, entry.regex.pattern
if hasattr(entry, 'url_patterns'):
show_urls(entry.url_patterns, depth + 1)
I called this script from ipdb, this was the output:
ipdb> import urls
ipdb> show_urls(urls.urlpatterns)
^test-experiment/(?P<experiment_name>.*)$
^test-clientsideexperiment/(?P<experiment_name>.*)$
^admin/
^(?P<experiment_name>.+)/$
^$
^main-app/
^goal/(?P<goal_name>.*)$
^confirm_human/$
This corresponds to the urls located # 'django_lean.experiments.tests.urls'
urlpatterns = patterns('django_lean.experiments.tests.views',
url(r'^test-experiment/(?P<experiment_name>.*)$', 'experiment_test'),
url(r'^test-clientsideexperiment/(?P<experiment_name>.*)$', 'clientsideexperiment_test'))
urlpatterns += patterns('',
url(r'^admin/', include('django_lean.experiments.admin_urls')),
url(r'^main-app/', include('django_lean.experiments.urls')),
The issue that I'm having is that my tests all fail because of the named urls from other apps in the project are called by URL template tags are not accessible to the tests.
I'm running Python 2.7 with Django 1.2.1
The solution was pretty simple. Just import the URLs from the main project into the urls.py for the app.
from forum.urls import urlpatterns
or for a more generic solution:
from settings import ROOT_URLCONF as project_urls
urlpatterns = __import__('forum.urls').urls.urlpatterns
To list all the url patterns your django knows you can use the answer suggested here.
Run this from your tests and print/log the output.
Just note that its better to explicitly state where to import the urls from like
from myproject import urls
because you probably have some other modules containing urls files.