asdfasdf

parent d4212e20
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm, UsernameField
from django.contrib.auth.models import User
from django.forms import ModelForm
from accounts.models import Profile
class RegisterForm(ModelForm):
password = forms.CharField(
......@@ -52,3 +55,46 @@ class MyRegisterForm(UserCreationForm):
'first_name',
'last_name', 'email']
field_classes = {'username': UsernameField}
class UserChangeForm(forms.ModelForm):
class Meta:
model = get_user_model()
fields = ['first_name', 'last_name', 'email']
labels = {'first_name': 'Имя', 'last_name': 'Фамилия', 'email': 'Почта'}
class ProfileChangeForm(forms.ModelForm):
class Meta:
model = Profile
exclude = ['user', ]
class PasswordChangeForm(forms.ModelForm):
password = forms.CharField(label='Новый пароль', strip=False, widget=forms.PasswordInput)
password_confirm = forms.CharField(label='Подтвердите пароль', strip=False, widget=forms.PasswordInput)
old_password = forms.CharField(label='Старый пароль', strip=False, widget=forms.PasswordInput)
def clean_password_confirm(self):
password = self.cleaned_data.get("password")
password_confirm = self.cleaned_data.get("password_confirm")
if password and password_confirm and password != password_confirm:
raise forms.ValidationError("Пароли не совпадают")
return password_confirm
def clean_old_password(self):
old_password = self.cleaned_data.get("old_password")
if not self.instance.check_password(old_password):
raise forms.ValidationError("Старый пароль неправильный!!!")
return old_password
def save(self, commit=True):
user = self.instance
user.set_password(self.cleaned_data.get('password'))
if commit:
user.save()
return user
class Meta:
model = get_user_model()
fields = ['password', 'password_confirm', 'old_password']
......@@ -15,7 +15,7 @@
<body>
<div class="container">
<form action="{% url 'login' %}?next={{ request.GET.next }}" method="post">
<form action="{% url 'user-login' %}?next={{ request.GET.next }}" method="post">
{% csrf_token %}
<label for="username">Логин:</label>
<input id="username" type="text" name="username">
......
{% extends 'base.html' %}
{% block title %} Редактировать пользователя {% endblock %}
{% block menu_links %}
<li><a href="{% url 'user-detail' user_obj.pk %}">Назад</a></li>
<li><a href="{% url 'user-change-password' user_obj.pk %}">Смена пароля</a></li>
{% endblock %}
{% block content %}
<div class="container">
<h1>Изменить личные данные:</h1>
<form
action="{% url 'user-change' user_obj.pk %}"
method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% include 'partial/form.html' with form=form fields_only=True %}
{% include 'partial/form.html' with form=profile_form fields_only=True %}
<br>
<input type="submit" value="Сохранить">
</form>
</div>
{% endblock %}
\ No newline at end of file
......@@ -3,8 +3,8 @@
{% block title %}Пользователь{% endblock %}
{% block menu_links %}
<li><a href="#">Редактировать</a></li>
<li><a href="#">Смена пароля</a></li>
<li><a href="{% url 'user-change' user_obj.pk %}">Редактировать</a></li>
<li><a href="{% url 'user-change-password' user_obj.pk %}">Смена пароля</a></li>
{% endblock %}
{% block content %}
......
{% extends 'base.html' %}
{% block title %} Смена пароля {% endblock %}
{% block menu_links %}
<li><a href="{% url 'user-detail' user_obj.pk %}">Назад</a></li>
<li><a href="{% url 'user-change' user_obj.pk %}">Редактирование</a></li>
{% endblock %}
{% block content %}
<div class="container">
<h1>Смена пароля</h1>
{% url 'user-password-change' user_obj.pk as action_url %}
{% include 'partial/form.html' with action_url=action_url form_method='POST' %}
</div>
{% endblock %}
\ No newline at end of file
from django.urls import path
from .views import LoginView, LogoutView, RegisterView, UserDetailView
from .views import LoginView, LogoutView, RegisterView, UserDetailView, UserChangeView, UserPasswordChangeView
urlpatterns = [
path('accounts/login', LoginView.as_view(), name='login'),
path('accounts/logout', LogoutView.as_view(), name='logout'),
path('accounts/create/', RegisterView.as_view(), name="register"),
path('<int:pk>/', UserDetailView.as_view(), name='user-detail')
path('accounts/login', LoginView.as_view(), name='user-login'),
path('accounts/logout', LogoutView.as_view(), name='user-logout'),
path('accounts/create/', RegisterView.as_view(), name="user-register"),
path('accounts/<int:pk>/', UserDetailView.as_view(), name='user-detail'),
path('accounts/<int:pk>/change', UserChangeView.as_view(), name='user-change'),
path('accounts/<int:pk>/change-password', UserPasswordChangeView.as_view(), name='user-change-password')
]
\ No newline at end of file
from django.contrib.auth import (
authenticate, login, logout, get_user_model
authenticate, login, logout, get_user_model, update_session_auth_hash
)
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import Group
from django.core.exceptions import ValidationError
from django.core.paginator import Paginator
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django.views.generic import DetailView
from django.views.generic import DetailView, UpdateView
from .forms import RegisterForm, MyRegisterForm
from .forms import RegisterForm, MyRegisterForm, UserChangeForm, ProfileChangeForm, PasswordChangeForm
from .models import Profile
......@@ -19,7 +21,7 @@ class LogoutView(View):
next = request.GET.get('next')
if next:
return redirect(next)
return redirect('login')
return redirect('user-login')
class LoginView(View):
......@@ -95,3 +97,66 @@ class UserDetailView(LoginRequiredMixin, DetailView):
kwargs['articles'] = page.object_list
kwargs['is_paginated'] = page.has_other_pages()
return super(UserDetailView, self).get_context_data(**kwargs)
class UserChangeView(UserPassesTestMixin, UpdateView):
model = get_user_model()
form_class = UserChangeForm
template_name = 'user_change.html'
context_object_name = 'user_obj'
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
profile_form = self.get_profile_form()
if form.is_valid() and profile_form.is_valid():
return self.form_valid(form, profile_form)
else:
return self.form_invalid(form, profile_form)
def form_valid(self, form, profile_form):
response = super(UserChangeView, self).form_valid(form=form)
profile_form.save()
return response
def form_invalid(self, form, profile_form):
context = self.get_context_data(form=form, profile_form=profile_form)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
if 'profile_form' not in kwargs:
kwargs['profile_form'] = self.get_profile_form()
return super().get_context_data(**kwargs)
def get_profile_form(self):
form_kwargs = {'instance': self.object.profile}
if self.request.method == "POST":
form_kwargs['data'] = self.request.POST
form_kwargs['files'] = self.request.FILES
return ProfileChangeForm(**form_kwargs)
def get_success_url(self):
return reverse('user-detail', kwargs={
'pk': self.object.pk
})
def test_func(self):
return self.request.user == self.get_object()
class UserPasswordChangeView(UserPassesTestMixin, UpdateView):
model = get_user_model()
template_name = 'user_password_change.html'
form_class = PasswordChangeForm
context_object_name = 'user_obj'
def form_valid(self, form):
user = form.save()
update_session_auth_hash(self.request, user)
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
return reverse('user-detail', kwargs={'pk': self.object.pk})
def test_func(self):
return self.request.user == self.get_object()
......@@ -12,6 +12,15 @@
</head>
<body>
{% include 'partial/navbar.html' %}
<div class="container">
{% block title %}{% endblock %}
<ul>
{% block menu_links %}
{% endblock %}
</ul>
</div>
{% block content %}
{% endblock %}
......
{% if not fields_only %}
<form
action="{{ action_url }}"
method="{{ form_method }}"
enctype="multipart/form-data"
>
{% csrf_token %}
{% endif %}
{% for error in form.non_field_errors %}
<p class="error">{{ error }}</p>
{% endfor %}
{% for field in form %}
{{ field.error }}
{{ field.label }}
{{ field }}<br>
{% endfor %}
{% if not fields_only %}
<input type="submit" value="{{ button_text|default:"Submit" }}">
</form>
{% endif %}
......@@ -11,11 +11,11 @@
</li>
</ul>
{% if not user.is_authenticated %}
<a class="btn btn-success" href="{% url 'login' %}?next={{ request.get_full_path }}">Войти</a>
<a class="btn btn-success" href="{% url 'register' %}?next={{ request.get_full_path }}">Регистрация</a>
<a class="btn btn-success" href="{% url 'user-login' %}?next={{ request.get_full_path }}">Войти</a>
<a class="btn btn-success" href="{% url 'user-register' %}?next={{ request.get_full_path }}">Регистрация</a>
{% else %}
<li class="menu-right">Привет, <a href="{% url 'user-detail' user.pk %}">{{ user.username }}</a>!</li>
<a class="btn btn-danger" href="{% url 'logout' %}?next={{ request.get_full_path }}">Выйти</a>
<a class="btn btn-danger" href="{% url 'user-logout' %}?next={{ request.get_full_path }}">Выйти</a>
{% endif %}
</div>
</div>
......
from urllib.parse import urlencode
import P as P
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
......@@ -96,7 +95,7 @@ class ArticleDeleteView(DeleteView):
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return redirect('login')
return redirect('user-login')
return super().dispatch(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment