I'm having trouble extracting a string from my URL. Here's what I've got.. it keeps 404ing.
urls.py:
urlpatterns = patterns('',
(r'^user/(?P<username>\w{0,50})/$', profile,),
)
views.py:
def profile(request, username):
...
return ...
See anything obvious? Need more? Any help is appreciated.
I usually a /?$ at end of url pattern.
It is a common mistake and some browser add or not a trailing '/'.
Have you imported your views module at the top of your URL file?
from views import profile
urlpatterns = patterns('',
(r'^user/(?P<username>\w{0,50})/$', profile),
# also removed trailing comma after profile
)
# alternative
urlpatterns = patterns('',
(r'^user/(?P<username>\w{0,50})/$', 'views.profile'),
)
Have you got DEBUG = True in your settings file? That'll help find errors with a stacktrace that you should show us.
Related
New to Django and im trying to simply get to my products detail page using the following code in my URLs.py:
urls.py:
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from products import views
import carts
from carts.views import CartView
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('products/', views.all, name='products'),
path('s/', views.search, name='search'),
path('products/<slug:slug>', views.single, name='single_product'), <----This is the page I want to get to
path('cart/', carts.views.CartView, name='cart'),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
If its any help, this is the link I use in my template to get to the product display page View
And here is my view:
def single(request, slug):
try:
product = Product.objects.get(slug=slug)
images = ProductImage.objects.filter(product=product)
context = {'product': product, "images": images}
template = 'products/single.html'
return render(request, template, context)
except:
raise Http404
But when trying to access this page I get the following 404 Error:
Maybe a fresh pair of eyes can help me spot the mistake I'm making?
If any additional info is needed please let me know, I'll be happy to provide. Thanks a million in advance!
First try replacing:
path('products/<slug:slug>', views.single, name='single_product'),
with
path('products/<slug:slug>/', views.single, name='single_product'),
Django automatically appends a slash (/) to the end of urls by default and the image you showed us shows an url ending on a slash while your defined path does not contain one. I just tried to reproduce it, and this made it work.
And then if it still doesn't work, double check if you are using the correct slug to find your Product using the shell as you are raising a 404 whenever an exception occurs. You might even consider removing the try/except to check if it's actually raising a different exception.
Maybe the last slash ('/') is the problem, try the url without it:
http://127.0.0.1/products/product-one
I'm developing a webpage with Django.
I want to add/define an url for the application.
At this moment the url (dsvd/) doen't work properly. It shows only table data but no css and background.
here is the code for the main urls.py file.
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'kleedkamer_overview.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('kleedkamer_overview.urls')),
url(r'^dsvd/', 'kleedkamer_overview.views.indeling'),
)
and here the code inside the application urls.py file
from django.conf.urls import patterns, url
from kleedkamer_overview import views
urlpatterns = patterns ('',
url(r'^$',views.indeling, name='indeling'),
)
Is there anyone who can help me find the problem?
Greetz.
It looks like line is giving you trouble:
url(r'^dsvd/', 'kleedkamer_overview.views.indeling')
It seems like you are trying to map this URL to kleedkamer_overview.views.indeling but the URL regrex does not end with a '$'. Urls.py files that are mapped to other apps look like this:
url(r'^admin/', include(admin.site.urls))
Notice the include function call and that the regrex expression r'^admin/' does not end with a $
However mapping to a specific view is a bit different and it looks like this:
url(r'^$', 'kleedkamer_overview.views.home', name='home')
Notice that this time, where the include() function call would go you are instead telling Django which specific view you want to use and that the site regrex is r'^$' ending with a $.
Try changing this:
url(r'^dsvd/', 'kleedkamer_overview.views.indeling')
to this:
url(r'^dsvd/$', 'kleedkamer_overview.views.indeling')
Edit:
I saw your comments and while the urls.py is not the source of your problem, what I said is still valid because the urls.py was malformed. You should not even have the offending line there at all because you have already included the urls.py from kleedkamer_overview , there is no need to include it twice. It isn't DRY and it is just bad practice in general. This is why this still works despite being malformed because sites are looked for in order, in this case first it looks for /admin then / and does not reach /dsvd because it was already caught by / and your malformed url mapping is NEVER reached.
I have a few URLs that I want to exclude from my REST API documentation. I'm using Django REST Swagger and the only documentation I can find (https://github.com/marcgibbons/django-rest-swagger) doesn't really tell me much. There is the "exclude_namespaces" part of SWAGGER_SETTINGS in settings.py, but there is no real explanation or example of how to use this.
Simply put, I want to exclude any URLs from the docs that start with the following:
/api/jobs/status/
/api/jobs/parameters/
How could I go about doing this?
Thanks in advance for any help offered :P
the namespaces to exclude are the one defined in your urls.py.
So for example, in your case:
urls.py:
internal_apis = patterns('',
url(r'^/api/jobs/status/',...),
url(r'^/api/jobs/parameters/',...),
)
urlpatterns = urlpatterns + patterns('',
url(r'^', include(internal_apis, namespace="internal_apis")),
...
)
and in your settings.py:
SWAGGER_SETTINGS = {
"exclude_namespaces": ["internal_apis"], # List URL namespaces to ignore
}
This is well described in there
For all of those who found the above answer not helpful:
I guess that "exclude_namespaces" doesn't work anymore in new versions of django swagger. I had almost the same problem (I didnt't want to show my internal apis in documentation) and the above solution didn't work for me. I've been searching for like an hour for a solution and finally found something helpful.
There are some attributes that you can pass to SchemaGenerator. One of them is urlconf. You can set it to be "yourproject.api.urls" and it will get only urls defined there! Of course, you have to make sure that all the urls that you want to exclude from your api documentation are not included there.
I hope that at least one person found my answer helpful ;).
A problem comes when you want to have many urls.py included in your api documentation. I don't know what should be done then. If anyone comes up with an answer to this new problem - feel free to comment my answer. thanks!
With new version of django swagger, we don't need to create view to exclude some urls. Below code will disable test2 url.
from rest_framework_swagger.views import get_swagger_view
urlpatterns1 = [
url(r'^', include(router.urls)),
url(r'^test/', include('test.urls')),
url(r'^test1/', Test2.as_view()),
]
schema_view = get_swagger_view(title='API Documentation', patterns=urlpatterns1)
urlpatterns = urlpatterns1 + [
url(r'^docs/', schema_view),
url(r'^test2/', Test2.as_view()),
]
Ola's answer is correct. exclude_namespaces is no longer supported.
For finer control of the documentation, create your own schema view by using a function-based or class-based view. This can be useful if you want to produce documentation for specific URL patterns, or URL confs.
In your views.py, you can do the following:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.schemas import SchemaGenerator
from rest_framework_swagger import renderers
class SwaggerSchemaView(APIView):
renderer_classes = [
renderers.OpenAPIRenderer,
renderers.SwaggerUIRenderer
]
def get(self, request):
generator = SchemaGenerator(title='Your API Documentation', urlconf='your_app.urls')
schema = generator.get_schema(request=request)
return Response(schema)
The above will only render documentation for the URLs that are specified in the urlconf argument of the SchemaGenerator. Also, don't forget to set up your urls.py as well:
from django.conf.urls import url
from views import SwaggerSchemaView
urlpatterns = [
url(r'^api/v1/docs/$', SwaggerSchemaView.as_view(), name='docs'),
]
For the newest version of drf-swagger you can defile url patterns in the schema generator.
For example:
url_patterns = (
url(r'^api/v1/', include(router.urls, namespace='api')),
)
generator = schemas.SchemaGenerator(title='Core API', patterns=url_patterns)
A more flexible solution would be:
from django.contrib import admin
from django.urls import include, path
from rest_framework_swagger.views import get_swagger_view
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('user.urls', namespace="user")),
path('locations/', include('location.urls')),
path('departments/', include('department.urls', namespace="department")),
path('my_secret_api/', include('secret.urls', namespace="secret_api")),
]
to_exclude = ['secret_api',] # some more namespaces here
swagger_urls = [item for item in urlpatterns if hasattr(item,"namespace") and item.namespace not in to_exclude]
schema_view = get_swagger_view(title='Highky', patterns=swagger_urls)
urlpatterns += [
path('api/docs/', schema_view),
]
urlpatterns will have all five paths, but swagger_urls will have four paths excluding secret_api.
All of your URLs and includes will continue to work as they were, except we are now passing our modified urlpatterns that we want to show in the Swagger docs. The checks will also cover the include where you don't specify a namespace (like in our case, where the namespace is not defined in the location).
views.py
any view class
class ...ViewSet(viewsets.ModelViewSet):
queryset = ....objects.all().order_by('-id')
serializer_class = ...Serializer
http_method_names = ['get', 'post', 'patch', 'delete'] # add or exclude
any function-based view
#api_view(['get']) # target field
def function(request):
...
return Response(...)
I'm having some weird issues with class-based-views and reverse_lazy.
Following error shows up when calling the website:
ImproperlyConfigured at /dashboard/student/
The included urlconf core.urls doesn't have any patterns in it
My views.py:
class DashStudentMain(TemplateView):
model_class = None
template_name = 'learn/dashboard/snip_student_1.html'
tab_list = {
("Main", reverse_lazy('dash_student_main_url')),
#("History", reverse_lazy('dash_student_main_url'))
}
active_tab = "Main"
My core.urls:
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.views.generic import RedirectView
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', 'core.views.home', name='home_url'),
url(r'^home', 'core.views.home'),
url(r'^dashboard/', include('tc_learn.dashboard.urls')),
...
)
My tc_learn.dashboard.urls:
from django.conf.urls.defaults import patterns, url
from .views import DashStudentMain, DashStudentHistory
urlpatterns = patterns(
# Student + Tabs
url(r"^", DashStudentMain.as_view()),
url(r"^student/$", DashStudentMain.as_view(), name="dash_student_main_url"),
url(r"^student/history/$", DashStudentHistory.as_view(), name="dash_student_history_url"),
I've
restarted the server, to make sure urls were loaded properly
commented out ("Main", reverse_lazy('dash_student_main_url')) to make sure that the urls.py syntax is fine
deleted the line url(r"^", DashStudentMain.as_view()), since it's not used anyway, but without it /dashboard/student doesn't work at all..
Any idea what I might be missing? Thanks!
EDIT:
It looks like the issue is coming from the tab_list object.
When I directly assign the object via tab_list = reverse_lazy('dash_student_main_url'), the code works fine. When I use it inside a list, it's showing that error. Does anyone know of work-around for this scenario?
Change this code:
tab_list = {
("Main", reverse_lazy('dash_student_main_url')),
#("History", reverse_lazy('dash_student_main_url'))
}
to:
tab_list = [
("Main", reverse_lazy('dash_student_main_url')),
#("History", reverse_lazy('dash_student_main_url'))
]
Contrary to a name you gave the variable, you were not creating a list, but a set. Elements were evaluated immediately at the time of set creation, because sets need to know more about values they contain. Changing it to a proper list will allow the elements to be evaluated lazily, as intended.
In tc_learn.dashboard.urls: you are missing the first argument (empty prefix in your case). Change it to:
urlpatterns = patterns(
'',
url(r"^", DashStudentMain.as_view()),
url(r"^student/$", DashStudentMain.as_view(), name="dash_student_main_url"),
url(r"^student/history/$", DashStudentHistory.as_view(), name="dash_student_history_url"),
)
Also, the first regex should be r"^$" if you want it to represent an empty one
And see if it works. Let me know!
I have a root urls.py and an app urls.py. In my root I have this:
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', include('realestate.properties.urls')),
(r'^admin/', include(admin.site.urls)),
)
In my app urls I have the following
from django.conf.urls.defaults import *
urlpatterns = patterns('realestate.properties.views',
url(r'^$', 'property_list', {'template_name': 'properties/property_list.html'}, name='property_list'),
url(r'^(?P<slug>[-\w]+)/$', 'property_detail', { 'template': 'property_detail.html' }, name='property_details'),
)
now in my template I have a link to the details view, which looks like this:
{% url property_details property.slug %}
Everytime I render this page i get the error:
*Caught NoReverseMatch while rendering: Reverse for 'property_details' with arguments '(u'111-front-st',)' and keyword arguments '{}' not found.*
No matter what I do, I get that error. I tried capturing just the id and nothing is working, i am not sure why, I have used url's many times before so I am really confused if I am missing something obvious. Any see anything wrong here?
Thanks
Jeff
I think you need to drop the $ from your urlconf, where you include the app's urls. Probably you can remove the ^ too.
urlpatterns = patterns('',
(r'^', include('realestate.properties.urls')),
(r'^admin/', include(admin.site.urls)),
)
http://docs.djangoproject.com/en/1.2/topics/http/urls/#including-other-urlconfs
Note that the regular expressions in
this example don't have a $
(end-of-string match character) but do
include a trailing slash. Whenever
Django encounters include(), it chops
off whatever part of the URL matched
up to that point and sends the
remaining string to the included
URLconf for further processing.
Do something like this:
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'realestate.properties.views.property_list'),
(r'^properties/', include('realestate.properties.urls')),
(r'^admin/', include(admin.site.urls)),
)
Otherwise (like sugested by Reiners post) you will make the first regular expression a "catch all" and /admin will never match.
You can also place the admin regular expression before your "catch all" re, but what happens if you have a slug like 'admin'? That is why I would advice against a url scheme with /<slug>/ at the first level. Instead, use /<object-type>/<slug>/, that will make room for other things in the future.