I'm having trouble at having Django urlpatterns catch a variable as an variable and instead take it as a set URL.
urlpatterns:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^about/', views.about),
url(r'^views/available_products/', views.available_products),
url(r'^views/productview/<int:product_id>/', views.productview)
]
When I host the server and go to /about/, /views/available_products/ or /admin/ they work fine, but trying to go to /views/productview/1/ gives a 404 error whereas going to /views/productview// gives a missing argument -error.
I tried to read the documentation and saw no obvious tell as to why my url variable argument wouldn't work, but clearly I'm doing something fundamentally wrong.
Here is an example error message from the debug page:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/views/productview/12/
Using the URLconf defined in firstdjango.urls, Django tried these URL patterns, in this order:
^admin/
^about/
^views/available_products/
^views/productview/<int:product_id>/
The current path, views/productview/12/, didn't match any of these.
And here is the same error message but where the URL I try with is the same as in urlpatterns:
TypeError at /views/productview/<int:product_id>/
productview() missing 1 required positional argument: 'product_id'
Request Method: GET
Request URL: http://localhost:8000/views/productview/%3Cint:product_id%3E/
Django Version: 1.11.8
Exception Type: TypeError
Exception Value:
productview() missing 1 required positional argument: 'product_id'
Server time: Sat, 10 Feb 2018 12:25:21 +0000
views.py:
from django.http import HttpResponse, Http404
from django.shortcuts import render
def starting_instructions(request):
return render(request, "webshop/instructions.html", {})
def about(request):
return HttpResponse("about page")
def productview(request, product_id):
"""
Write your view implementations for exercise 4 here.
Remove the current return line below.
"""
return HttpResponse("product {}".format(product_id))
def available_products(request):
"""
Write your view implementations for exercise 4 here.
Remove the current return line below.
"""
return HttpResponse("View not implemented!")
This url is not translated correctly.
see Request URL: http://localhost:8000/views/productview/%3Cint:product_id%3E/
You can use eighter path or re_path (which is similar to url and you can use regex in it so as you can use in url). So change your urlpatterns to.
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('about/', views.about),
path('views/available_products/', views.available_products),
path('views/productview/<int:product_id>/', views.productview)
]
EDIT
or if you really want to use url, use it like
url('^views/productview/(?P<product_id>\d+)/$', views.productview)
But using path is the Django 2.0+ approach. Also replacing url with re_path which is the same.
Related
I am working on a Django Rest Framework API. I was encountering an issue with my project where I keep getting the following error:
django.urls.exceptions.NoReverseMatch: Reverse for 'login' with no arguments not found. 2 pattern(s) tried: ['(?P<version>[v1]+)/auth/login(?P<format>\\.[a-z0-9]+/?)\\Z', '(?P<version>[v1
]+)/auth/login/\\Z']
This error is very weird because in my urls.py class, I used the following pattern:
re_path(r'(?P<version>[v1]+)/auth/', include('rest_framework.urls'))
I looked at the file rest_framework/urls.py, this is the code inside it:
from django.contrib.auth import views
from django.urls import path
app_name = 'rest_framework'
urlpatterns = [
path('login/', views.LoginView.as_view(template_name='rest_framework/login.html'), name='login'),
path('logout/', views.LogoutView.as_view(), name='logout'),
So, I had no idea why the two patterns tried by the resolver were
'(?P[v1]+)/auth/login(?P\.[a-z0-9]+/?)\Z'
'(?P[v1]+)/auth/login/\Z'
since the path in rest_framework/urls.py is just 'login/', not 'login(?\.[a-z0-9]+/?\z' or the latter.
In order to replicate the error, I created a new simple DRF API:
views.py:
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
#api_view(['GET'])
def root(request, format=None):
return Response({
'/': reverse('root', request=request, format=None),
'login': reverse('rest_framework:login', current_app=request.resolver_match.namespace),
})
urls.py:
from django.urls import re_path, include
from demo.views import root
urlpatterns = [
re_path(r'', root, name='root'),
re_path(r'/auth/', include('rest_framework.urls')),
]
When I sent a GET request to /, I got the following response:
HTTP 200 OK
Allow: GET, OPTIONS
Content-Type: application/json
Vary: Accept
{
"/": "http://18346ef2-eed4-4627-8911-7cd11a88eed2.id.repl.co/",
"login": "/%2Fauth/login/"
}
The response is really weird. The first call to reverse() acted normal, but not the second one. I have no idea why, but I hope knowing why would help me at least figure out the reason behind the issue in my project.
Here is a link for the full demo on replit: https://replit.com/#HadilBader/demo#
your path is
re_path(r'(?P<version>[v1]+)/auth/', include('rest_framework.urls'))
which needs one argument: version. Since you declare this as an argument, you need to pass it everywhere you need to reverse the url, something like:
reverse(
'rest_framework:login',
current_app=request.resolver_match.namespace,
kwargs={'version': 'v1'}
)
I'm just beginning to learn Django.
I've created a simple web sub-app called 'flavo' inside of another one called 'djangoTest'
When I run http://127.0.0.1:8000/flavo
it correctly displays
Hello, World!
then when I run http://127.0.0.1:8000/flavo/a it should show
Hello, a!
But instead I get:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/flavo/a
Using the URLconf defined in testDjango.urls, Django tried these URL patterns, in this order:
admin/
flavo [name='index0']
flavo a [name='a']
The current path, flavo/a, didn’t match any of these.
in testDjango/hello/views.py I have
from django.http import HttpResponse
from django.shortcuts import render
def index0(request):
return HttpResponse("Hello, world!")
def a(request):
return HttpResponse("Hello, a!")
In testDjango/flavo/url/py I have
from django.urls import path
from . import views
urlpatterns = [
path("", views.index0, name="index0"),
path("a", views.a, name="a"),
]
The only other file I've changed is , testDjango/testDjango/urls.py"
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('flavo', include("flavo.urls")),
]
I'm confused why I can't access http://127.0.0.1:8000/flavo/a
Add '/'.
like this.
# testDjango/testDjango/urls.py
path('flavo/', include("flavo.urls"))
I am a total beginner in "django" so I'm following some tutorials currently I' am watching https://youtu.be/JT80XhYJdBw Clever Programmer's tutorial which he follows django tutorial
Everything was cool until making a polls url
Code of views.py:
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
HttpResponse("Hello World.You're at the polls index")
Code of polls\urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
Code of Mypr\urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/',admin.site.urls),
path('polls/',include('polls.urls')),
]
I don't get it I did the same thing but I'm getting error not only polls.In one turtorial he decided to make blog,and again the same error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/
Using the URLconf defined in Mypr.urls, Django tried these URL patterns, in
this order:
admin/
The current path, polls/, didn't match any of these.
Please my seniors help me.
Note:I'm using the latest versions of django,windows and as editor I'm using Pycharm.
Already tried(and did not work):
from django.urls import path
from polls.views import index
urlpatterns = [
path('', index, name='index'),
]
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/
Using the URLconf defined in Mypr.urls, Django tried these URL patterns, in this order:
admin/
The current path, polls/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file.
Change that to False, and Django will display a standard 404 page.
try to access polls/ URL in your browser then you will access the page
Because you have accessed the URL of your project, you have to go to this URL to access your app
try by changing your code like this
from django.urls import path
from polls.views import index
urlpatterns = [
path('', index, name='index'),
]
I was facing the same error. Feel kinda dumb after figuring out how to solve this.
Your urls.py content is all right
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
But it must be included in the mysite\mysite\urls.py and not in mysite\urls.py.
That means the inner mysite/ directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it.
I'm following the djangoforgirls.org tutorial on making my first django site. I'm trying the stage "extending your template" to make a link to an article within my website that uses the general template.
I keep get thrown the error: "NoReverseMatch at /, Reverse for 'post_detail' with arguments '()' and keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P\d+)/$']"
Some variable and file names may seem strange, the use of the website was music sampling but I used the tutorial's names for things in case that was what was wrong.
My urls.py for entire project:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('sample.urls')),
]
My urls.py for the specific app (sample):
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
]
My views.py for the app:
from django.utils import timezone
from .models import AudioSample
from django.shortcuts import render, get_object_or_404
def post_list(request):
samples = AudioSample.objects.order_by('length')
return render(request, 'blog/post_list.html', {'samples': samples})
def post_detail(request, pk):
post = get_object_or_404(AudioSample, pk=pk)
return render(request, 'blog/post.html', {'post': post})
And the line of code from the base template that's the link to another page in the website:
How to sample
I saw another person that asked this question with a similar project here and got it fixed but I dont understand the answer enough to make the change to mine (I dont understand what the namespace is).
If you have more than one urls.py, namespace can tell django how to handle the request. So in normally, namespace is the APP name.
In your project urls.py, try replacing r'' with r'^'. The former matches all urls, while the latter matches the start of the string.
Here is my urls.py
from django.conf.urls import include, url
from django.contrib import admin
from common.views import HomeView, LoadingSchoolView, ProcessSchoolView
urlpatterns = [
url(r'^$', HomeView.as_view(), name='Index'),
url(r'^admin/', include(admin.site.urls)),
url(r'^member/', include('member.urls', namespace='member')),
url(r'^common/', include('common.urls', namespace='common')),
In my common/urls.py
from django.conf.urls import url
from .views import QuerySchoolView
urlpatterns = {
url(r'^querySchool/(?P<q>[a-z]*)$', QuerySchoolView.as_view(), name='querySchool'),
}
Now, when I do
{% url 'common:querySchool' %},
It gives me a TypeError
TypeError at /member/register/learner
argument to reversed() must be a sequence
Request Method: GET
Request URL: http://127.0.0.1:8000/member/register/learner
Django Version: 1.8.2
Exception Type: TypeError
Exception Value:
argument to reversed() must be a sequence
Exception Location: /Users/enzii/python_env/django18/lib/python3.4/site-packages/django/core/urlresolvers.py in _populate, line 285
Python Executable: /Users/enzii/python_env/django18/bin/python3
Python Version: 3.4.3
Here is My View
class QuerySchoolView(View):
def get(self, request, q=""):
universities = University.objects.filter(Q(name__contains=q) |
Q(pinyin__contains=q) |
Q(province__contains=q) |
Q(country__contains=q))[:4]
returnObj = [{'unvis-name': u.name, 'country': u.country, 'province': u.province} for u in universities]
return HttpResponse(returnObj)
What is wrong with my {% url %} ?
You don't have a URL called "index", you have one called "Index".
And in your common/urls, you are using {} instead of [] to wrap the patterns.
In future, please post each question separately.
Query-1 Solution:
You have Index defined as the reverse name for the HomePage view in the urls but you are using index as the reverse name for the url in your template.
Change index to Index and your code will work.
<a class="btn btn-default-ar" href="{% url 'common:Index' %}">
Index will default to application namespace i.e common so accessing the reversed url by common namespace.
You can even do the opposite that is changing the reverse name in your urls to index without any change in the template. It will work.
Query-2 Solution:
Urlpatterns defined in the urls.py file should be a list of patterns. As Gocht mentioned in the comment, try changing the urlpatterns defined in common app urls to a list [].
common/urls.py
from django.conf.urls import url
from .views import QuerySchoolView
urlpatterns = [
url(r'^querySchool/(?P<q>[a-z]*)$', QuerySchoolView.as_view(), name='querySchool'),
]