How to route specific urls in a django app? - python

I would like to know if there is a way to include only specific url endpoints in my Django urls.py.
Lets say i have a app called auth with this auth/urls.py
urlpatterns = [
url(r'^password/reset/$', PasswordResetView.as_view(),
name='rest_password_reset'),
url(r'^password/reset/confirm/$', PasswordResetConfirmView.as_view(),
name='rest_password_reset_confirm'),
url(r'^login/$', LoginView.as_view(), name='rest_login'),
url(r'^logout/$', LogoutView.as_view(), name='rest_logout'),
url(r'^user/$', UserDetailsView.as_view(), name='rest_user_details'),
url(r'^password/change/$', PasswordChangeView.as_view(),
name='rest_password_change'),
]
Now I have a urls.py like that:
urlpatterns = [
path('/', include('dj_rest_auth.urls'))
]
this includes all endpoints from auth/urls.py.
Is there a way to select (in urls.py) which URL to include? Lets say I only want login and logout to be included on my urls.py.
urlpatterns = [
path('/', include('dj_rest_auth.urls.rest_login')),
path('/', include('dj_rest_auth.urls.rest_logout'))
]
Something like that, how can I make it work?

I did this long before.
# inside view.py just create your own custom view
# rest and rest_auth import
from rest_auth.views import LoginView, LogoutView
class CustomLogoutView(LogoutView):
# yes u can keep it blank.
# over-riding just to distinguish from library views.
pass
Then inside any app's urls.py import required views and and pass then into path.
this way only required url will be exposed.
from .views import CustomLoginView
urlpatterns = [
path('login/', CustomLoginView.as_view(), name='login'),
]
Also you can directly import that views (not urls) which are included in library. and then create urls (path) from them.

Related

Api root on django rest framework

I am newbie on DRF so I wonder if there a "elegant" way to add more endpoints to API Root. I have an endpoint to manage my users and another to manage their posts, but on http://localhost:8000/api/ only profiles appears. I search for some solutions that implies change the URL but I don't want that. For example my current endpoint to get all posts is localhost:8000/api/posts that looks fine. I don't want something like api/posts/posts or similar. Is there any alternative?
{
"profiles": "http://localhost:8000/api/profiles/"
}
main urls.py
urlpatterns = [
path('docs/', schema_view.with_ui('swagger',
cache_timeout=0), name='schema-swagger-ui'),
path('admin/', admin.site.urls),
path('api/', include('profiles.urls')),
path('api/', include('posts.urls')),
path('api/', include('comments.urls')),
path('api/', include('private_messages.urls')),
]
userprofile urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from rest_framework_simplejwt import views as jwt_views
from .views import UserProfileViewSet
router = DefaultRouter()
router.register('profiles', UserProfileViewSet)
urlpatterns = [
path('', include(router.urls)),
path('auth/login', jwt_views.TokenObtainPairView.as_view()),
path('auth/refresh', jwt_views.TokenRefreshView.as_view()),
]
posts urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import PostViewSet, PostByAuthorViewSet
router = DefaultRouter()
router.register('posts', PostViewSet)
urlpatterns = [
path('posts-by-author/<author_id>', PostByAuthorViewSet.as_view()),
path('', include(router.urls))
]
but on http://localhost:8000/api/ only profiles appears
This is the expected behavior. Django is returning the first matching path from your URL configuration file, which is the profiles module in your case. Your duplicate api/ paths are ignored.
If you really want everything to be in /api, you'd have to define all your URLs in the base urls.py file. However, I would highly recommend you keep your current structure and add the module name to your endpoints:
urlpatterns = [
path('docs/', schema_view.with_ui('swagger',
cache_timeout=0), name='schema-swagger-ui'),
path('admin/', admin.site.urls),
path('api/profiles/', include('profiles.urls')),
path('api/posts/', include('posts.urls')),
path('api/comments/', include('comments.urls')),
path('api/private_messages/', include('private_messages.urls')),
]
Otherwise your urls.py file can get messy very quickly as your project grows.
If a route like localhost:8000/api/posts/posts is bothering you, you should modify the URL configuration in your posts app. Something like this would probably work better for you:
from django.urls import path
from .views import PostViewSet, PostByAuthorViewSet
urlpatterns = [
path('by-author/<author_id>', PostByAuthorViewSet.as_view()),
path('', PostViewSet.as_view())
]
This way you'd have the routes localhost:8000/api/posts/and localhost:8000/api/posts/by-author/1. As a side note, you should probably look into filters, since posts-by-authors sounds like a viewset that can easily be included in your PostViewSet with a query parameter.

Django - importing view from Dependency

I'm trying to use this library since i want to add 2FA Auth to my project. In order to integrate the module in my project, i need to import their views to my urls.py file, right?
I tried to import SetupView, but i'm getting this error: module 'allauth_2fa.views' has no attribute 'homepage'. Here is what i understood: it looks like if i import a view from the dependency, it will only read those views from the dependency but not my own views declared on views.py.
from django.urls import path
from . import views
from django.conf.urls import url, include
from django.conf.urls import url
from allauth_2fa import views
app_name = "main"
urlpatterns = [
path("setup/", views.TwoFactorSetup.as_view(), name="setup"),
path("", views.homepage, name="homepage"),
path("register/", views.register, name="register"),
path("logout/", views.logout_request, name="logout"),
path("login/", views.login_request, name="login"),
]
Extra: SetupView will generate the page required to enable the 2FA authentication, that's why i need it. Later i will also import the other views required to have my two factor authentication fully running
At first you imported
from . import views
And then:
from allauth_2fa import views
And after that you tried to do:
path("", views.homepage, name="homepage"),
And views is allauth_2fa.views not from your project
So you just need to do like this:
from allauth_2fa import views as allauth_2fa_views
And then use it when you need

Django V2.1 reverse is not a valid view function or pattern name

I am very new to Django and I have created two apps in my project one is login & server_status. I have used the namespace method to access my login and server_status across both apps. It is working fine when I tried to access index but when I tried to access dashboard in server_status it is not working.
Reverse for 'server_status' not found. 'server_status' is not a valid view function or pattern name
# server_status URL
from django.urls import path
from . import views
urlpatterns = [
path('', include('server_status.urls', namespace='server_status')),
path('', include('login.urls', namespace='login')),
path('admin/', admin.site.urls),
]
# login app URL
app_name = 'login'
urlpatterns = [
path('login', views.index, name='index')
]
# project URL
from django.contrib import admin
from django.urls import include, path
app_name = 'server_status'
urlpatterns = [
path('', views.index, name='index'),
path('dashboard/', views.dashboard, name='dashboard'),
path('server_status/', views.server_status, name='server_status'),
path('request_access/', views.request_access, name='request_access'),
]
In server_status/templates/server_status/index.html
Login
I know this is very simple one, but it makes me very complicated.
In the posted code, you define urlpatterns twice, so the first set of urlpatterns is overridden by the second. Since server_status is defined in the first set, it is not present in memory, since you obliterate it in the second definition. index is the only pattern that survives. I think what you meant to do in the second stanza was to add to the urlpatterns with:
urlpatterns += [...]
To declare namespace you should do something like this:
# project URL
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('', include('server_status.urls', namespace='server_status')),
path('', include('login.urls', namespace='login')),
path('admin/', admin.site.urls),
]
then you can use
Login
or
Server status index

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order

I have a problem with Django. Actually I want to create a login panel in my new site but when I try to write address the debugger respond me a error:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/account/login
Using the URLconf defined in firmowa.urls, Django tried these URL patterns, in this order:
admin/
^account/
The current path, account/login, didn't match any of these.
My firmowa.urls is
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path(r'^account/', include('account.urls')),
]
And the project urls.py is:
from django.urls import path
from . import views
urlpatterns = [
path(r'^login/$', views.user_login, name='login'),
]
I'm looking a solution from few hours but still nothing.
path is a new feature in Django 2.0 and works different than the old url. Don't use regex in path. If you need regex, use re_path instead, but in your case there's no need for that.
Change your code to:
urlpatterns = [
path('login/', views.user_login, name='login'),
]
etc. and it should work.
More on the topic here and here.
from django.urls import path
from . import views
from django.conf.urls import url
urlpatterns = [
url( r'^$', views.index , name='index') ,
]

Change template name for Django's auth views

Ì'm using django.contrib.auth.views.login and django.contrib.auth.views.logout directly in my urls.py with
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^login/$', auth_views.login, name='login'),
url(r'^logout/$', auth_views.logout, name='logout'),
]
These built-in auth views are using templates in directory registration/.
How can I change template name for these views? Normally, I can use ...as_view(template_name='...').
The documentation explains this fully:
The views have optional arguments you can use to alter the behavior of the view. For example, if you want to change the template name a view uses, you can provide the template_name argument. A way to do this is to provide keyword arguments in the URLconf, these will be passed on to the view. For example:
urlpatterns = [
url(
'^change-password/',
'django.contrib.auth.views.password_change',
{'template_name': 'change-password.html'}
)
]

Categories

Resources