사용자가 Django에서 자신의 비밀번호를 변경하도록 허용하는 방법은 무엇입니까?
사용자가 Django에서 자신의 암호를 변경할 수있는 코드를 알려줄 수 있습니까?
Django는 사용자 인증 시스템과 함께 제공됩니다. 사용자 계정, 그룹, 권한 및 쿠키 기반 사용자 세션을 처리합니다. 이 문서는 작동 방식을 설명합니다.
암호 변경 섹션을 참조하십시오.
manage.py파일이있는 프로젝트로 이동$ python manage.py shell아래 스크립트를 입력하십시오.
django.contrib.auth.models에서 사용자 가져 오기 u = User.objects.get (username__exact = 'john') u.set_password ( '새 비밀번호') u.save ()
간단한 manage.py명령을 사용할 수도 있습니다 .
manage.py changepassword *username*
새 비밀번호를 두 번 입력하면됩니다.
로부터 암호 변경의 워드 프로세서 섹션을 참조하십시오.
당신이있는 경우 django.contrib.admin당신의 INSTALLED_APPS, 당신은 방문 할 수 있습니다 : example.com/path-to-admin/password_change/이전 암호를 확인하고 새 암호를 두 번 입력 할 수있는 형태를 가질 것이다.
django.contrib.auth.views.password_changeURLconf 에서 보기를 사용할 수도 있습니다 . 기본 양식과 템플릿을 사용합니다. 자신을 제공하는 것은 선택 사항입니다.
쉘로 이동할 필요없이 passwd를 입력하고 passwd를 다시 입력합니다.
python manage.py changepassword <username>
or
/manage.py changepassword <username>
쉘 사용
python manage.py shell
from django.contrib.auth.models import User
users=User.objects.filter(email='<user_email>')
#you can user username or etc to get users query set
#you can also use get method to get users
user=users[0]
user.set_password('__enter passwd__')
user.save()
exit()
urls.py:
urlpatterns = [
url(r'^accounts/', include('django.contrib.auth.urls')),
주형:
<a href="{% url 'password_change' %}">{% trans "Change password" %}</a>
문서화 : https://docs.djangoproject.com/en/1.9/topics/auth/default/#using-the-views
이것은 내가 사용한 명령 AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.User'입니다.
python manage.py shell -c "from django.contrib.auth import get_user_model;
User = get_user_model();
u = User.objects.get(username='admin');
u.set_password('password123');
u.save()"
이 튜토리얼 에서는 함수 기반 뷰로 수행하는 방법을 보여줍니다.
파일보기:
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
from django.shortcuts import render, redirect
def change_password(request):
if request.method == 'POST':
form = PasswordChangeForm(request.user, request.POST)
if form.is_valid():
user = form.save()
update_session_auth_hash(request, user) # Important!
messages.success(request, 'Your password was successfully updated!')
return redirect('change_password')
else:
messages.error(request, 'Please correct the error below.')
else:
form = PasswordChangeForm(request.user)
return render(request, 'accounts/change_password.html', {
'form': form
})
URL 파일 :
from django.conf.urls import url
from myproject.accounts import views
urlpatterns = [
url(r'^password/$', views.change_password, name='change_password'),
]
마지막으로 템플릿 :
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Save changes</button>
</form>
@Ciro의 답변과 매우 유사하지만 원래 질문에 더 구체적입니다 (모든 인증보기를 추가하지 않음).
just add to urlpatterns in urls.py:
url('^change-password/$', auth_views.password_change, {'post_change_redirect': 'next_page'}, name='password_change'),
Note that post_change_redirect specifies the url to redirect after the password is changed.
Then, just add to your template:
<a href="{% url 'password_change' %}">Change Password</a>
Once the url pattern is added as shown in Ciro Santilli's answer, a quick way to allow users to change passwords is to give them "staff access" for the admin functions. If you don't add them to any groups or give them special permissions, they can still change their password by going to the example.com/admin page. The staff access lets them go to the page even if it is blank; in the upper right corner they can click "change password" and use the admin funtionality.
'program story' 카테고리의 다른 글
| 열 3으로 awk 정렬을 사용하는 방법 (0) | 2020.10.16 |
|---|---|
| 다른 열 pandas 데이터 프레임을 기반으로 열 값 추출 (0) | 2020.10.16 |
| REST API 모범 사례 : 쿼리 문자열의 인수와 요청 본문의 인수 (0) | 2020.10.15 |
| SEHException 오류를 진단하는 방법-외부 구성 요소에서 예외가 발생했습니다. (0) | 2020.10.15 |
| SSL 오류 : 로컬 발급자 인증서를 가져올 수 없습니다. (0) | 2020.10.15 |