I have an app called API where I want to create a "Forgot Password" button for the user to insert their email, and a password reset is sent to them.
In the same Django project, I have an application called users which implements this process in the backend.
How can Django Rest Framework be used to reset the password? Do I link the URLs of the users app or create new URLs in API app
Here is the users app urls.py
app_name = 'users'
urlpatterns = [
path('password/', user_views.change_password, name='change_password'),
path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html', success_url=reverse_lazy('users:password_reset_done')), name='password_reset'),
path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'),name='password_reset_done'),
path('password-reset-confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html',success_url=reverse_lazy('users:password_reset_complete')),name='password_reset_confirm'),
path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'),name='password_reset_complete'),
]
here is the main urls.py
urlpatterns = [
path('', include('django.contrib.auth.urls')),
path('admin/', admin.site.urls),
path('api/', include('api.urls'), ),
path('users/', include('users.urls'), ),
here is the api app urls.py
app_name = 'api'
router = routers.DefaultRouter()
router.register(r'users', UserViewSet, basename='user')
urlpatterns = [
path('', include(router.urls)),
path('dj-rest-auth/', include('dj_rest_auth.urls')),
path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')),
path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]
Dj Rest Auth already provide endpoint for reseting password, you have to use them.
You can find all endpoint in the documentation : https://dj-rest-auth.readthedocs.io/en/latest/api_endpoints.html
In you case, dj-rest-auth/password/reset/ in POST request with email as data will make what you want to
Related
I am new to Django. I'm trying to implement jet authentication along with social authentication.
I'm following this tutorial https://jkaylight.medium.com/django-rest-framework-authentication-with-dj-rest-auth-4d5e606cde4d
I tried to implement the same but its not working.
I'm getting this error:
django.urls.exceptions.NoReverseMatch: Reverse for 'account_confirm_email' not found. 'account_confirm_email' is not a valid view function or pattern name.
My project level urls.py
from drf_spectacular.views import (
SpectacularAPIView,
SpectacularSwaggerView
)
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
# path('account/', include('allauth.urls')),
path('admin/', admin.site.urls),
path('api/user/', include('user.urls')),
path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'),
path(
'api/docs/',
SpectacularSwaggerView.as_view(url_name='api-schema'),
name='api-docs'
),
]
My App level urls.py
from django.urls import path, re_path
from dj_rest_auth.registration.views import RegisterView, VerifyEmailView, ConfirmEmailView
from dj_rest_auth.views import LoginView, LogoutView
from user import views
app_name = 'user'
urlpatterns = [
path('account-confirm-email/<str:key>/', ConfirmEmailView.as_view()),
path('register/', RegisterView.as_view()),
path('login/', LoginView.as_view()),
path('logout/', LogoutView.as_view()),
path('verify-email/',
VerifyEmailView.as_view(), name='rest_verify_email'),
path('account-confirm-email/',
VerifyEmailView.as_view(), name='account_email_verification_sent'),
re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$',
VerifyEmailView.as_view(), name='account_confirm_email'),
path('listusers/', views.ListUsers.as_view(), name='list-users'),
]
When I try to register a user. It causes this error.
I'm using dj-rest-auth package to implement authentication.
If I replace the email verification related urls from app level to project level. Then everything is working fine.
What is causing this error ?
For the registration part, you have to use allauth which has some baked-in integrations with dj-rest-auth
also, you would have to add some things in your settings.py:
INSTALLED_APPS = [
"dj_rest_auth.registration",
"allauth",
"allauth.account"
]
AUTHENTICATION_BACKENDS = [
"allauth.account.auth_backends.AuthenticationBackend",
"django.contrib.auth.backends.ModelBackend",
]
add these URLs to the urls.py:
urlpatterns = [
path("signup/", include("dj_rest_auth.registration.urls"))
path("verify-email/", VerifyEmailView.as_view(), name="rest_verify_email"),
path(
"account-confirm-email/",
VerifyEmailView.as_view(),
name="account_confirm_email_sent",
),
path(
"account-confirm-email/<key>/",
VerifyEmailView.as_view(),
name="account_confirm_email",
),
]
The request is not getting <str:key>. Please check where you are supplying. It can be from view or template.
I followed the simple quickstart tutorial in the official documentation of django rest framework.
https://www.django-rest-framework.org/tutorial/quickstart/
The tutorial works fine. The URL of the browsable API is at 127.0.0.1:8000. How do I change it to 127.0.0.1:8000/api?
The code for urls.py;
from django.urls import include, path
from rest_framework import routers
from tutorial.quickstart import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
I am using django v4, python v3.9
Just change the prefix via path(), like you've done for api-auth/.
(This is not DRF-specific; it's just the regular path() function you use to mount views onto URLs.)
path('', include(router.urls)),
->
path('api/', include(router.urls)),
I am using Django 2.1 and getting an error during password reset authentication right at the end.
my urls
from django.conf.urls import url
from django.contrib import admin
from . import views
from django.contrib.auth import views as auth_views
from django.urls import reverse, reverse_lazy, resolve
app_name = 'partners'
urlpatterns = [
url(r'^$', views.home, name='partner_home'),
url(r'^(?P<partner_id>[0-9]+)/$', views.detail, name='detail'),
url(r'^login/$',auth_views.LoginView.as_view(template_name="partners/registration/login.html"), name="login"),
url(r'^logout/$',auth_views.LogoutView.as_view(template_name="partners/registration/logout.html"), name="logout"),
url(r'^register/$', views.register, name='register'),
url(r'^profile/$', views.view_profile, name='view_profile'),
url(r'^profile/edit/$', views.edit_profile, name='edit_profile'),
# Password URL's ###################################################################################################
url(r'^change-password/$', views.change_password, name='change_password'),
url(
r'^password_reset/$',
auth_views.PasswordResetView.as_view(
template_name="partners/registration/password_reset.html",
email_template_name="partners/registration/password_reset_email.html",
success_url=reverse_lazy("partners:password_reset_done"), # might be required
),
name='password_reset'
),
url(r'^password_reset_done/',
auth_views.PasswordResetDoneView.as_view(
template_name="registration/password_reset_done.html",
),
name='password_reset_done'
),
url(r'^password_reset_confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$',
# r'(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
auth_views.PasswordResetConfirmView.as_view(
template_name="registration/password_reset_confirm.html",
),
name='password_reset_confirm',
),
url(r'^password_reset_complete/$',
auth_views.PasswordResetCompleteView.as_view(
template_name="partners/registration/password_reset_complete.html",
),
name="password_reset_complete"
),
]
I am able to login, then go to the password reset view. An email is sent using the development server and I am able to use the link to create a new password. Once I enter the new password I get an error (but the password in the background is changed). I am not sure why this is the case at the moment .
I am not using my custom password_reset_xxx html file instead I am using the builtin views
My URLS and structure
The Error Message
You have put your password reset urls in the partners app, therefore you need to override the code wherever it reverses urls so that it uses the partners namespace.
In this case, you need to override success_url in PasswordResetConfirmView.
auth_views.PasswordResetConfirmView.as_view(
template_name="registration/password_reset_confirm.html",
success_url = reverse_lazy('partners:password_reset_complete')
),
However, you may find there are other places that you need to override to get the password reset working. As I suggested on your other question, it would be simpler to move the password reset URLs out of the partners app.
I have a blog made in django in a VPS. The blog is working fine but to access it I have to write the url example.com/blog/
What I'm trying is to make an automatic redirection so when a user enters example.com/ it automatically redirects to example.com/blog/
The project is set under apache.
This is my the configuration in myproject/urls.py:
urlpatterns = [
url(r'^blog/', include('blog.urls', namespace="blog")),
url(r'^admin/', include(admin.site.urls)),
]
This is the configuration of myproject/blog/urls.py that right now is formed by a post list and a post detail:
urlpatterns = patterns('',
# Index
url(r'^(?P<page>\d+)?/?$', ListView.as_view(
model=Post,
paginate_by=5,
),
name='index'
),
# Individual posts
url(r'^(?P<pub_date__year>\d{4})/(?P<slug>[a-zA-Z0-9-]+)/?$', DetailView.as_view(
model=Post,
),
name='post'
),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I already tried to add a .htaccess with different configurations but it's not working.
Is there a way to redirect from django?
If you're sure that you want that / to redirect to /blog/ for that you can create a temporary index view and redirect the response to /blog/
url(r'^', temp_index, name='index'),
def temp_index(request):
return HttpResponseRedirect('/blog/')
If you want that / must show /blog then replace
url(r'^blog/', include('blog.urls', namespace="blog")), with
url(r'^', include('blog.urls', namespace="blog")),
I am working on django project. I am kinda learning it. So my project has user login logout functionality and I wanna add profile based user management system too. So what I wanna do is if someone is trying to access this link, I wanna show user profile
siteURL/username
so my project's urls.py file has these codes,
urlpatterns = [
# url(r'^admin/', include(admin.site.urls)),
# Robots.txt request
url(r'^robots.txt', TemplateView.as_view(template_name="robots.txt", content_type="text/plain")),
# Profile related requests
url(r'^$', include('UserProfile.urls')),
# Home page request
url(r'^$', include('Homepage.urls')),
# Accounts related requests
url(r'^accounts/', include('Accounts.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
# handling error requests for 403, 404, 500 etc
handler404 = 'errorPages.views.error404'
handler500 = 'errorPages.views.error500'
and my UserProfile app has url.py file and codes are,
urlpatterns = [
# User Profile related requests
url(r'^(?P<uname>.+?)/update$', User_Profile_Update.as_view()),
]
and my class file's codes are,
class HC_User_Profile_Update(TemplateView):
def get(self, request, *args, **kwargs):
return render(request, "user_profile/profile_update.html"),
My homepage app has urls.py file and codes are,
urlpatterns = [
#Home page request
url(r'^$', HomePage.as_view()),
]
and homepage class file,
class HomePage(TemplateView):
def get(self, request):
if request.user.is_authenticated():
return render(request, "homepage/home.html", {'uname': request.user.uname})
else:
return render(request, "homepage/home.html")
I am getting 404 error that Url not found. So can anyone tell me what is wrong in my urls? For now, I just wanna check that the url is rendering the html page or not. And url I am trying to access right now is
sitename/username/update
Thank you for your time.
Try to remove $ from your project's urls.py file. Update your urls.py file as
urlpatterns = [
# url(r'^admin/', include(admin.site.urls)),
# Robots.txt request
url(r'^robots.txt', TemplateView.as_view(template_name="robots.txt", content_type="text/plain")),
# Profile related requests
url(r'^', include('UserProfile.urls')),
# Home page request
url(r'^$', include('Homepage.urls')),
# Accounts related requests
url(r'^accounts/', include('Accounts.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
# handling error requests for 403, 404, 500 etc
handler404 = 'errorPages.views.error404'
handler500 = 'errorPages.views.error500'
Hope it will work.