I am configuring a dynamic url in my django project. I have followed the instructions provided on the net but it is not working.
urls.py in app
urlpatterns = [
url(r'^seci/<int:secn>', views.sect, name = 'sect'),
url('sections/<str:secn>/', views.sections, name = 'sections'),
]
views.py in app
def sect(request,secn):
print("secn:", secn)
return HttpResponse("testing")
def sections(request, secn):
print("secn:", secn)
return HttpResponse(secn)
Django says, url not found. I don’t know what else to do.
from django.urls import path
# here is import of your views
urlpatterns = [
path('seci/<int:secn>', views.sect, name='sect'),
path('sections/<str:secn>', views.sections, name='sections'),
]
Saw this in a video
url(r'^seci/(?P<secn>\w+)', views.sect, name = 'sect'),
url(r'sections/(?P<secn>\w+)/', views.sections, name = 'sections'),
Related
So, I would like top stop ursing urlpatterns and just use router. But instead of using ID of an object I'm using UUID instead and I'm using it with urlpatterns and dont't find some way to use it with routers.
this is my current model:
class Board(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=200, blank=False, null=False)
this is my core app urls.py:
...
router = DefaultRouter()
router.register(r'boards', BoardViewSet)
router.register(r'y', yViewSet)
router.register(r'z', zViewSet, basename='z')
urlpatterns = [
path('', include(router.urls)),
path('board-list/<uuid:pk>/', BoardViewSet.as_view({'get': 'list'}), name='boards'),
]
and this is the project urls.py:
from django.contrib import admin
from django.urls import path, include
from core.urls import router as api_router
routes = []
routes.extend(api_router.urls)
urlpatterns = [
path('api/', include((routes, 'board_microservice'), namespace='v1')),
path('admin/', admin.site.urls),
]
the application usage is ok, but I have some troubles with test.
i.e:
this works well:
url = reverse('v1:board-list')
response = api_client().get(
url
)
and it isn't working:
board = baker.make(Board)
url = reverse('v1:board-list', kwargs={"pk": board.id})
response = api_client().get(url)
I receive
django.urls.exceptions.NoReverseMatch: Reverse for 'board-list' with keyword arguments
and I think I can replace urlpatterns by router to solve it and turns it more simple
There is any way to do it with router?
You haven't shared your view, but it seems you are using a ModelViewSet and you seem to be looking for the retrieve endpoint rather than list (judging from using a pk). If so then you want to use -detail instead of -list:
url = reverse('v1:board-detail', kwargs={"pk": board.id})
Board_list is not what you want to call... Try board_get instead.
Board list takes no argument. But get does.. To get a particular board.
I'm a newbie in web development and I'm learning to use Django. Unfortunately I have been stuck for more than 24 hours trying to figure out how to set the URL of a web page. I keep getting status 404 error displayed on the browser after running python server. I have checked python documentation and other documentations online but I still don't see anywhere I'm getting it wrong.
I have the following files in the main Django follow:
urls.py
from django.contrib import admin
from django.urls import path, include
urlspatterns [
path('qbank', include ('qbank.url')),
path ('admin/', admin.site.urls),
]
settings.py
INSTALLED APPS = [
'qbank'
.....
]
In my project folder(which I named qbank) I have the following files:
urls.py
from django.urls import path
from . import views
urlspatterns = [
path ('qbank'), views.index, name = 'index'
]
view.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse ('Hello from Qbank')
The way you wrote it now, it will require two qbanks, one for the "root" urls.py, and one for the urls.py in the qbanks, hence localhost:8000/qbankqbank. If you only want to access it with qbank, then you remove the qbank for example from the urls.py of the qbanks app. So then the "root" urls.py looks like:
# project_name/urls.py
from django.contrib import admin
from django.urls import path, include
urlspatterns [
path('qbank/', include('qbank.url')),
path ('admin/', admin.site.urls),
]
and the urls.py of your app:
# qbank/urls.py
from django.urls import path
from . import views
urlspatterns = [
path ('', views.index, name='index')
]
Here's my code
from django.urls import path
urlpatterns = [
# /audios/
path('', views.audio ),
# /audios/4344/
path('(<record_id>[0-9]+)/', views.record_detail),
]
Please can someone help out
try this :
path(r'^record/(?P<record_id>[0-9]+)/$', views.record_detail)
Django 2.0 has came with new update of defining a new way for url patterns by path. In new url patterns you don't need to define urls in regex(see 3rd url pattern). Refer
But you can also write url patterns like we define in django < 2. 0 by re_path which is available in django.urls refer
Or you can use old django style of defining url patterns which is defined in django.conf.urls which helps you to define re pattern for urls.
from django.urls import re_path, path
from djnago.conf.urls import url,include
urlpatterns += [
url('(<record_id>[0-9]+)/',views.record_detail),
#or
re_path('(<record_id>[0-9]+)/', views.record_detail),
#or
path('<int:record_id>/', views.record_detail)
]
Just like #Exprator wrote, the path should be:
path('<int:record_id>/', views.record_detail, name='record_detail'),
However, I think maybe there is a problem in view "record_detail", the view should declare like this:
def record_detail(request, record_id):
then, you can refer your record_id in your view body.
Here is my code:
urlpatterns = [
path('', views.index, name='index'),
path('<int:record_id>/', views.record_detail, name='record_detail'),
]
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world.")
def record_detail(request, record_id):
return HttpResponse("Hello, world. You're record is: "+str(record_id))
Here is result:
I want to allow the user to reset password when the user is signed out and cannot remember the password.
I am using the django authentication framework and have created the reset_password and password_reset_done mappers.
Issue : Though I have created the password_reset_done function I continue to get the below error. Is there a step that I missed that is causing this error? I do not know what I have done wrong.
I have posted all the code that I think is relevant to what I attempting to do.
Edit with full TraceBack:
Here is the code :
relative urls.py
from django.conf.urls import url
from . import views
from django.contrib.auth.views import login, logout, password_reset, password_reset_done
urlpatterns = [
url(r'^$', views.vedic_view, name = 'vedic_home_view'),
url(r'^login/$', login, {'template_name' : 'exist/login.html'}, name = 'login'),
url(r'^logout/$', logout, {'template_name' : 'exist/logout.html'}, name = 'logout'),
url(r'^register/$', views.register_view, name = 'register'),
url(r'^profile/$', views.view_profile, name = 'view_profile'),
url(r'^profile/edit/$', views.edit_profile, name = 'edit_profile'),
url(r'^change-password/$', views.change_password, name = 'change_password'),
url(r'^reset-password/$', password_reset, name = 'reset_password'),
url(r'^reset-password/done/$', password_reset_done, name = 'password_reset_done')
]
main urls.py
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
from django.conf.urls import include
from django.views.generic import RedirectView
urlpatterns += [
url(r'^exist/', include('exist.urls', namespace = 'exist')),
url(r'^$', RedirectView.as_view(url='/exist/', permanent=True)),
]
password_reset_done is within the exists namespace. It looks like you are trying to reverse the named URL without including the namespace argument somewhere. We would need to see your full traceback to see exactly where that is happening.
Since you are using the built-in auth views, the easiest fix would probably be to move your password reset handling up to your main urls.py. Notice in your traceback that the built-in password_reset view does this:
post_reset_redirect = reverse('password_reset_done')
The default implementation here is to reverse to password_reset_done without any namespace. Moving the relevant URLs up to your main urls.py will allow them to be accessed via reverse without a namespace argument, making the built-in views happy.
I realize what the issue is.
For the built-in reset view there is a post_reset_redirect variable that uses the default implementation reverse(password_reset_done) to go to the password_reset_done view.
The issue is that in my main urls.py document I created the namespace variable
namespace = exist
However I did not override the default post_reset_redirect implementation
from reverse(password_reset_done) to reverse(exist:password_reset_done).
So my current
url(r'^reset-password/$', password_reset, name = 'reset_password'),
should now look like
url(r'^reset-password/$', { 'post_reset_redirect':
'exist:password_reset_done'}, password_reset, name =
'reset_password')
As I see, you didn't include relative.url in your main urls.
EDIT
in relative urls
app_name='exists' #with this name you can call in main urls
urlpatterns = [
url(r'^$', views.vedic_view, name = 'vedic_home_view'),
#...
In main url:
urlpatterns = [
url(r'^exists/', include('exists.urls')),
#...
EDIT 2
Here'sthe docs on the subject, it explains it better than me with examples.
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(...)