Django NameError: name 'password_reset_done' is not defined - python

found some topics like this but they are older or not solved.
Well, I'm following a youtube tutorial and I'm stuck in this part of it, I already know it's due the difference of version, I've gone to the docs and got some answers but still can't solve it by myself.
I'll post what I think it's relevant but if you guys want another part of my code ask and I'll get it.
the error as I said (on Traceback) is: NameError: name 'password_reset_done' is not defined
On the tutorial he didn't done anything on views.py about this, he just added some imports on url.py that was deprecated so I fix that but the errors keeps the same...
My accounts/urls.py:
from django.urls import path
from . import views
from django.contrib.auth.views import (
login,
logout,
password_reset,
PasswordResetDoneView,
PasswordResetConfirmView,
)
urlpatterns = [
path('', views.home),
path('login/', login, {'template_name': 'contas/login.html'}),
path('logout/', logout, {'template_name': 'contas/logout.html'}),
path('register/', views.register, name='register'),
path('perfil/', views.view_perfil, name='view_perfil'),
path('perfil/edit/', views.edit_perfil, name='edit_perfil'),
path('trocar-password/', views.trocar_password, name='trocar_password'),
path('reset-password/', password_reset, name='reset_password'),
path('reset-password/done/', password_reset_done, name='password_reset_done'),
path('reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/',
password_reset_confirm, name='password_reset_confirm'),
]
just to add some more code. My views.py:
from django.shortcuts import render, redirect, HttpResponse
from contas.forms import (
RegistrationForm,
EditPerfilForm,
)
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
def home(request):
numbers = [1,2,3,4,5]
name = 'Lucas Cyrne'
args = {'myName': name, 'numbers': numbers}
return render(request, 'contas/home.html', args)
def register(request):
if request.method=='POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/contas')
else:
form = RegistrationForm()
args = {'form':form}
return render(request, 'contas/reg_form.html', args)
def view_perfil(request):
args = {'user': request.user}
return render(request, 'contas/perfil.html', args)
def edit_perfil(request):
if request.method=='POST':
form = EditPerfilForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect('/contas/perfil')
else:
form = EditPerfilForm(instance=request.user)
args = {'form': form}
return render(request, 'contas/edit_perfil.html', args)
def trocar_password(request):
if request.method=='POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
return redirect('/contas/perfil')
else:
return redirect('/contas/trocar_password')
else:
form = PasswordChangeForm(user=request.user)
args = {'form': form}
return render(request, 'contas/trocar_password.html', args)

Django looks for everywhere, and doesn't see password_reset_done
and above your urls patter, there is this:
NOTE: these built-in CBV are available forn Django >= 1.11
from django.contrib.auth.views import (
login,
logout,
password_reset, # suggestion: PasswordResetView
PasswordResetDoneView,
PasswordResetConfirmView,
)
you view is PasswordResetDoneView
instead of:
path('reset-password/done/', password_reset_done, name='password_reset_done'),
it should be:
path('reset-password/done/', PasswordResetDoneView.as_view(), name='password_reset_done'),

Cause you didn't call password_reset_done view, but using it in urls.
path('reset-password/done/', password_reset_done, name='password_reset_done'),
Look this url, you are trying to use view that doesn't exist.
Make your own view inheriting PasswordResetDoneView or, just use it without registering url. (You only can call url using password_reset_done like this
reverse('password_reset_done')
p.s. you have to add django.contrib.auth.urls to your urls.py. like
url('', include('django.contrib.auth.urls')), ( for django =< 1.11 )

You need to add app_name is urls.py
Add views as viewname.as_view() in urls.py

Related

The current path, accounts/<int:id>/, didn’t match any of these ( for django application)

This is a book exchange system I'm trying to create. The challlenge I'm having is trying to redirect the user to a dynamic url consisting of there personal details after log in.
Here is my urs.py for my project
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('exchange/',include('exchange.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('admin/', admin.site.urls),
]
Here is my urs.py for my app
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
path('', views.base, name='base'),
path('register/', views.register_request, name='register'),
path('accounts/<int:id>/', views.user_view, name='userview'),
#path('login/', views.login_request, name='login'),
path('login/', auth_views.LoginView.as_view(template_name='exchange/login.html', redirect_field_name='user_view')),
]
Here is my views.py for my app
from django.shortcuts import render, redirect
from exchange.forms import user_login_form, user_register_form
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib import messages
# Create your views here.
#Base index view
def base(request):
return render(request, 'exchange/base.html',{})
#registration view
def register_request(request):
if request.method=='POST':
form = user_register_form(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = User.objects.create_user(username=username, email=email, password=password)
user.save()
return redirect('login')
else:
messages.error(request, 'Invalid form')
render(request, 'exchange/register.html',{'form':form})
else:
form = user_register_form()
return render(request, 'exchange/register.html',{'form':form})
#login view
def login_request(request):
if request.method=='POST':
form = user_login_form(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('user_view', id=user.id)
else:
messages.error(request, 'Invalid username or password')
render(request, 'exchange/login.html',{'form':form})
else:
messages.error(request, 'Invalid form')
render(request, 'exchange/login.html',{'form':form})
form = user_login_form()
return render(request, 'exchange/login.html',{'form':form})
#userview
def user_view(request, id):
user = User.objects.get(id=id)
return render(request, 'exchange/user_view.html',{'user':user})
I have also added LOGIN_REDIRECT_URL = '/accounts/int:id/' to my settings.py.
I presume your app is called exchange
because you've put this 'accounts/<int:id>' inside your exchange app's urls, it's actually trying to match for 'exchange/accounts/<int:id>'
path('exchange/',include('exchange.urls')),
# Link App's Urls -> 'exchange/{x}'.format(pattern)
# exchange.urls (prepend 'exchange')
# url: exchange
path('', views.base, name='base'),
# url: exchange/register
path('register/', views.register_request, name='register'),
# url: exchange/accounts/<int:id>
path('accounts/<int:id>/', views.user_view, name='userview'),
# etc
There's really no way around this prepending, so i think your best bet would be to put it in the main urls and just explicitly say what app + view
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
from exchange.views import user_view
urlpatterns = [
path('exchange/',include('exchange.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('accounts/<int:id>', user_view, name='userview'),
path('admin/', admin.site.urls),
]
I do not see your models but are you sure that you use user_id like
<int:id>
Normally I use pk like this
<int:pk>
You have the following name in your URLs.py
path('accounts/<int:id>/', views.user_view, ***name='userview'***),
But you are using a different name (with an underscore) in your redirect
return redirect(***'user_view'***, id=user.id)
They will need to match for the redirect to work

Django Login Required Redirect

Im trying to redirect a user when he isn't logged in the my LoginPage.
I Have Tried Many Different solutions - Like #login_required & request.user.is_authenticated - yet nothing worked...
im leaving my views.py & urls.py so someone can see if they can spot the problem
Thanks For Any Help!
Views.Py:
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render,redirect
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
# Create your views here.
#login_required(login_url='/Login')
def Dashboard(request):
if request.user.is_authenticated:
return render(request, 'home/index.html')
else:
return LoginPage(request)
def LoginPage(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request,username=username, password=password)
if user is not None:
request.session.set_expiry(86400)
login(request, user)
return redirect('dashboard')
return render(request,'accounts/login.html')
def registerPage(request):
form = UserCreationForm()
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, "Account Created for " + user + " Succesfully" )
return redirect('login')
context = {'form': form}
return render(request, 'accounts/register.html', context)
def Admin(request):
return HttpResponseRedirect(reverse('admin:index'))
def Logout(request):
authenticate.logout(request)
logout(request)
return LoginPage(request)
Urls.Py:
from django.urls import path
from. import views
from django.contrib import admin
from django.urls import path, reverse_lazy
from django.views.generic.base import RedirectView
urlpatterns = [
path('',views.LoginPage),
path("Login", views.LoginPage, name="login"),
path("Register", views.registerPage,name="register"),
path("admin", views.Admin, name="admin"),
path("dashboard", views.Dashboard, name="dashboard"),
path('', RedirectView.as_view(url=reverse_lazy('admin:index'))),
path('admin/', admin.site.urls),
path("Login", views.logout, name="logout"),
Hlooo
Instead of this
#login_required(login_url='/Login')
Try this
#login_required(login_url='login')
use small 'l' since you used small 'l' in name = 'login'
This worked in my project , if user is not authenticated he will be
redirected to login page
In your settings.py, try add
LOGIN_URL = '/Login/'
also after logout, send them to the login page
LOGOUT_URL = '/Login/'

In django, return redirect not giving me the required output

I am new to django, I have created a page where only authenticated user should be able to view.
Below is my function which i have made in views.py to check and redirect to login page
views.py
def auth_check_manager(request):
if not request.user.is_authenticated:
return redirect('/')
below is the snapshot of url.py
urlpatterns = [
path('', views.login, name='login'),
]
There is a decorator that allows you to do this without reinventing the wheel login_required. Use it as follows:
from django.contrib.auth.decorators import login_required
#login_required(redirect_field_name='my_redirect_field')
def my_view(request):
...

Email form wont display on template

I'm working on a site that would display some data on my database and a form where people can contact me.
views.py
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import ContactForm
from django.utils import timezone
from .models import Logo, SkillLanguages, SkillAPI, SkillFrameworks,
WorkPortfolio, PersonalPortfolio
def index(request):
logo=Logo.objects.all()
skill_languages=SkillLanguages.objects.all()
skill_api=SkillAPI.objects.all()
skill_frameworks=SkillFrameworks.objects.all()
work_portfolio=WorkPortfolio.objects.all()
personal_portfolio=PersonalPortfolio.objects.all()
return render(request, 'johann/index.html', {'logo': logo, 'skill_languages': skill_languages, 'skill_api': skill_api, 'skill_frameworks': skill_frameworks, 'work_portfolio': work_portfolio, 'personal_portfolio': personal_portfolio})
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(name, message, from_email, ['myemail#notsuspiciousmailserver.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "johann/index.html", {'form': form})
def success(request):
return HttpResponse('<script>alert("Success! Thank you for your message."); window.location = "https://pqdrl7qd.apps.lair.io/#contact";</script>')
urls.py
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^$', views.email, name='email'),
url(r'^success/$', views.success, name='success'),
]
I found out that my problem lies in what I did to the first two URLs, if I switched the email URL and the index URL's places my template would then display my form instead of the data stored in my models and vice versa. What can I do about this?
You have two url patterns that are identical
url(r'^$', views.index, name='index'),
url(r'^$', views.email, name='email'),
They will be evaluated in order and the index view will always match first. Once a match is found, the rest of the url patterns are ignored.
You need to come up with a different route for your email view. Might I suggest
url(r'^email/$', views.email, name='email'),
You can use:
url(r'^$', views.index, name='index'),
url(r'^email/$', views.email, name='email'),

regist() got an unexpected keyword argument 'template_name'

i got a error that
TypeError at /accounts/regist/
regist() got an unexpected keyword argument 'template_name' .
i can understand there is no variable in my file.
but,in login,no template_name file can be worked.
So,i cannot know how to fix it.
I wrote in urls.py of accounts,
from django.conf.urls import url
from . import views
from django.contrib.auth.views import login, logout
urlpatterns = [
url(r'^login/$', login,
{'template_name': 'registration/accounts/login.html'},
name='login'),
url(r'^logout/$', logout, name='logout'),
url(r'^regist/$', views.regist,
{'template_name': 'registration/accounts/regist.html'},
name='regist' ),
url(r'^regist_save/$', views.regist_save, name='regist_save'),
]
in views.py
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.decorators.http import require_POST
from .forms import RegisterForm
def index(request):
context = {
'user': request.user,
}
return render(request, 'accounts/index.html', context)
#login_required
def profile(request):
context = {
'user': request.user,
}
return render(request, 'accounts/profile.html', context)
def regist(request):
form = RegisterForm(request.POST or None)
context = {
'form': form,
}
return render(request, 'accounts/regist.html', context)
#require_POST
def regist_save(request):
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
return redirect('main:index')
context = {
'form': form,
}
return render(request, 'accounts/regist.html', context)
if i have to define template_name,which file should i write it and how?
Are there differences to make system login page and regist page?
You don't have to specify a template_name when you are using your own function-based view, so just remove the {'template_name': 'registration/accounts/regist.html'} bit from the registration URL.

Categories