Page not found error happens-Can <str:id> be used? - django

Page not found error happens-Can be used?
I wrote in urls.py
from django.conf.urls import url
from app import views
urlpatterns = [
url('^data/<str:id>', views.data, name='data'),
]
in views.py
def data(id):
・
・
・
return None
For example, when I access http://127.0.0.1:8000/data/AD04958 ,
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/data/AD04958
error happens.
I think I can write this url http://127.0.0.1:8000/data/AD04958 into '^data/' in urls.py,so I really cannot understand why this error happens. id is not save in Database,does it cause this error?
What is wrong in my codes?How should I fix this?

For Django<=1.11.x
urlpatterns = [
url(r'^data/(?P<id>[\w.-]+)/$', views.data, name='data'),
]
For Django>=2
urlpatterns = [
path('^data/<str:id>', views.data, name='data'),
]

Related

url is showing in page not found error in django?

I created an endpoint and registered it in urls.py. When I try to hit the endpoint I get a 404 error but on the 404 page the url is shown as one of the patterns django tried to match. Stumped.
api.py
class UpdateLast(viewsets.GenericViewSet, UpdateModelMixin):
def get(self):
return XYZModel.objects.all()
def partial_update(self, request, *args, **kwargs):
if request.user.is_superuser:
with transaction.atomic():
for key, value in request.data:
if key == 'tic':
XYZModel.objects.filter(ticker=request.data['tic']).filter(trail=True).update(
last_high=Case(
When(
LessThan(F('last_high'),
request.data['high']),
then=Value(request.data['high'])),
default=F('last_high')
)
)
urls.py (this is inside the app)
router = routers.DefaultRouter()
router.register('api/dsetting', DViewSet, 'dsetting')
router.register('api/update-last-high', UpdateLast, 'update-last-high')
urlpatterns = [
path('', include(router.urls))
]
urls.py (main)
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('my_app.urls')),
When I hit the end-point api/update-last-high I get a 404 page.
On that page the exact end-point is shown as a pattern that django tried to match.
^api/update-last-high/(?P[^/.]+)/$ [name='update-last-high-detail']
^api/update-last-high/(?P[^/.]+).(?P[a-z0-9]+)/?$ [name='update-last-high-detail']
from rest_framework import routers
from . import views
from django.urls import path, include
router = routers.DefaultRouter()
router.register('api/dsetting', DViewSet, 'dsetting')
router.register('api/update-last-high', UpdateLast, 'update-last-high')
# you forgot to include the router.urls
urlpatterns = [
path('', include(router.urls))
]

Django -Page not found (404) Request Method: GET Method

I am very new to Django ,I am trying to run a URL ,however I get this error of page not found.I went through almost 90% of the posts here but nothing worked for me.
Here are three .py files
views.py.....
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse('Hello world....')
**products\urls.py****
from django.urls import path
from . import views #.means current folder ,we are importing a module
urlpatterns=[
path(' ', views.index),
]
pyshop\urls.py.......
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('products/',include('products.urls'))
]
Error I get.....
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/products/
Using the URLconf defined in pyshop.urls, Django tried these URL patterns, in this order:
admin/
products/
The current path, products/, didn't match any of these.
I think you have to delete the space on the path :
urlpatterns=[
path(' ', views.index),
]
Like :
urlpatterns=[
path('', views.index),
]

Invalid syntax when trying to create custom http errors

I'm trying to make custom http error pages. And as usual the django docs are really hard to understand.
I'm trying my best to follow this doc: https://docs.djangoproject.com/en/2.1/topics/http/views/#customizing-error-views
So I have set DEBUG = False
I have set ALLOWED_HOSTS = ['*']
In my views.py (not inside an app)
def server_error(request, exception):
return render(request, 'mysite/errors/500.html')
And in my urls.py (not inside an app), after all paths.
urlpatterns = [
path('', views.index, name='index'),
.......etc
handler500 = 'mysite.views.server_error'
]
When I run my server, I get instant error on handler500 in urls.py.
handler500 = 'mysite.views.server_error'
^
SyntaxError: invalid syntax
I also made a simple '500.html' under 'templates/errors'.
I have tried with importing handler, even though I read that I should not.
I tried with removing 'mysite' in location for view etc.
I can't seem to find anything about this SyntaxError on my handler?
Put handler500 = 'mysite.views.server_error' outside of urlpatterns at file level.
urlpatterns = [
path('', views.index, name='index'),
.......
]
handler500 = 'mysite.views.server_error'
Also add 500 response status in the error view
def server_error(request):
return render(request, 'mysite/errors/500.html', status=500)

Django url/route order not maintained

I have the following in my root URLconf module (there's more, but not important, so left out):
urlpatterns = [
re_path(r'^password-reset-redirect-view/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
password_reset_redirect,
name = 'password_reset_confirm'),
path('', include('search.urls')),
path('', include('customer_portal.urls')),
path('rest-auth/', include('rest_auth.urls')),
path('rest-auth/registration/', include('rest_auth.registration.urls')),
Here's the customer_portal.urls:
urlpatterns = [
path('customer/contact/', views.contact),
path('', views.home),
re_path(r"^confirm-email/(?P<key>[-:\w]+)/$", views.email_verification,
name="account_confirm_email"),
]
Here's the rest_auth.registration.urls:
urlpatterns = [
url(r'^$', RegisterView.as_view(), name='rest_register'),
url(r'^verify-email/$', VerifyEmailView.as_view(), name='rest_verify_email'),
url(r'^account-confirm-email/(?P<key>[-:\w]+)/$', TemplateView.as_view(),
name='account_confirm_email'),
]
As you can see both included urls.py urlpatterns have a view named 'account_confirm_email'.
Somewhere in the code this is ran:
url = reverse(
"account_confirm_email",
args=[emailconfirmation.key])
Since customer_portal.urls is included before rest_auth.registration.urls, I expect the route account_confirm_email in customer_portal.urls to be returned by the above reverse method. But instead I get the rest_auth.registration.urls route URL.
Just to be sure I commented out the route in rest_auth.registration.urls, and then I did get the correct URL (customer_portal URL) returned.
It is filled into an email, I check that email and see that I have the wanted url: http://127.0.0.1:8000/confirm-email/......./, instead of: http://127.0.0.1:8000/rest-auth/registration/account-confirm-email/...../
Can anyone tell me why the customer_portal URL isn't the one being reversed in both cases?
Django docs say:
Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.

How do I add two applications/pages onto my Django-site?

I have been trying twice now to add a second application onto my Django-site, whereas it results in some kind of errors.
I have followed instructions from youtube which has been of great help but now I am stuck at adding a second page. My first one is working just fine.
This is my main url.py:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^table/', include('table.urls')),
url(r'^', include('login.urls')),
]
This is my main settings.py:
INSTALLED_APPS = [
'login',
'table',
....
TEMPLATES = [
{
'BACKEND': 'django.templates.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.templates.context_processors.debug',
'django.templates.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
This is my working page url.py:
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
This is my working page view.py:
from django.shortcuts import render
def index(request):
return render(request,'login/login.html', {'content': ['username',
'password']} )
This is my non-working page url.py:
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^$', views.index, name = 'index'),
]
This is my non-working page view.py:
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request,'table/table.html')
Thus far I have thought of the index(request) being an issue since they are both having the name "view" and same function name...?
And I have no idea where to look on the "error-page" nor what to show you guys, I'm sorry. And I appreciate any help. Thank you.
"During handling of the above exception ('django'), another exception occurred:
C:\python36\lib\site-packages\django\core\handlers\exception.py in inner
response = get_response(request) ...
▼ Local vars
Variable Value
exc
ModuleNotFoundError("No module named 'django.templates'",)
get_response
>>>
>
request
"
EDIT: I have named all my template-folders templates, always. Though I mistakenly named it without an s while creating it inside the second application but it is changed by refactoring.
I think this is my error now:
Exception Type: ModuleNotFoundError at /
Exception Value: No module named 'django.templates'
The error message is stating you are referring to django.templates somewhere. This module does not exist in django, but django.template does. You can find several django.template.x statements in your settings.py file.
Replace django.templates.x with django.template.x and you are good to go!
In your urls.py, specify the app_name like this:
# ...imports...
app_name = 'tables'
urlpatterns = [
#...
]
The name of the url can then be accessed by your template by tables:index