---
# System prepended metadata

title: Тема 6. Регистрация и аутентификация пользователя
tags: [Python Web]

---

---
tags: Python Web
source: https://python-scripts.com/user-accounts-django
---

# Тема 6. Регистрация и аутентификация пользователя

https://github.com/roman-yatsenko/django-topics/tree/main/django-users

## Приложение auth

При создании любого нового проекта, Django по умолчанию устанавливает приложение `auth`. В нем есть [*объект User*](https://docs.djangoproject.com/en/2.2/ref/contrib/auth/#django.contrib.auth.models.User), содержащий такие поля как:

* username
* password
* email
* first_name
* last_name

## Аутентификация пользователя

### `blog_project\urls.py`

```python=19
urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('django.contrib.auth.urls')), # new
    path('', include('blog.urls')), 
]
```

```shell
mkdir templates/registration
touch templates/registration/login.html
```

### `templates\registration\login.html`

```htmlmixed=
{% extends 'base.html' %} 

{% block content %}
<h2>Log In</h2>
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Log In</button>
</form>
{% endblock content %}
```

### `blog_project\settings.py`

```python=124
LOGIN_REDIRECT_URL = 'home'
```

```shell=
python manage.py runserver 
# http://127.0.0.1:8000/accounts/login/
```

## Данные пользователя на главной странице

### `templates\base.html`

```htmlmixed=16
    </header>
    <div>
      {% if user.is_authenticated %}
        <p>Hi {{ user.username }}!</p>
      {% else %}
        <p>You are not logged in.</p>
        <a href="{% url 'login' %}">Log In</a>
      {% endif %}
    </div>
    <div>
      {% block content %}
```

## Выход пользователя из профиля

### `templates\base.html`

```htmlmixed=18
      {% if user.is_authenticated %}
        <p>Hi {{ user.username }}!</p>
        <p><a href="{% url 'logout' %}">Log out</a></p>
      {% else %}
```

### `blog_project\settings.py`

```python=125
LOGOUT_REDIRECT_URL = 'home'
```

## Регистрация нового пользователя

```shell
python manage.py startapp accounts
```

### `blog_project\settings.py`

```python=33
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
    'accounts' # new
]
```

### `blog_project\urls.py`

```python=19
urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('django.contrib.auth.urls')), 
    path('accounts/', include('accounts.urls')), # new
    path('', include('blog.urls')), 
]
```

```shell
touch accounts/urls.py
```

### `accounts\urls.py`

```python=
from django.urls import path
 
from .views import SignUpView
 
urlpatterns = [
    path('signup/', SignUpView.as_view(), name='signup'),
]
```

### `accounts\views.py`

```python=
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
 
 
class SignUpView(generic.CreateView):
    form_class = UserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'
```

```shell
touch templates/signup.html
```

### `templates\signup.html`

```htmlmixed=
{% extends 'base.html' %}
 
{% block content %}
<h2>Sign up</h2>
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Sign up</button>
</form>
{% endblock content %}
```

```shell=
python manage.py runserver 
# http://127.0.0.1:8000/accounts/signup/
```

---

(c) Яценко Р.Н., 2020

[Учебный центр компьютерных технологий "Кит"](http://kit.kh.ua/)

<img src="https://i.imgur.com/Kh901c1.png" style="width: 150px; position: fixed; top: 100px; right: 10px; border: 0; box-shadow: none;">
