---
# System prepended metadata

title: Тема 7. Пользовательская модель
tags: [Python Web]

---

---
tags: Python Web
source: Django 2.0 для начинающих, Глава 8-9, с.184
---

# Тема 7. Пользовательская модель

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

## Создание проекта сайта новостей

```shell
pipenv install Django==2.2.16
pipenv shell
django-admin startproject news_project .
python manage.py startapp users
python manage.py runserver
```

## Custom User Model

### `news_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',
    'users' # new
]
```

```python=123
AUTH_USER_MODEL = 'users.CustomUser'
```

### `users\models.py`

```python=
from django.contrib.auth.models import AbstractUser
from django.db import models


class CustomUser(AbstractUser):
    age = models.PositiveIntegerField(default=0)
```

## Формы

```shell
touch users/forms.py
```

### `users\forms.py`

```python=
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser



class CustomUserCreationForm(UserCreationForm):


    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = UserCreationForm.Meta.fields



class CustomUserChangeForm(UserChangeForm):


    class Meta(UserChangeForm.Meta):
        model = CustomUser
        fields = UserChangeForm.Meta.fields
```

### `users\admin.py`

```python=
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser


class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    list_display = ['email', 'username', 'age']
    model = CustomUser

admin.site.register(CustomUser, CustomUserAdmin)
```

```shell
python manage.py makemigrations
python manage.py migrate
```

## Superuser

```shell
python manage.py createsuperuser
python manage.py runserver
```

## Шаблоны

```shell
mkdir templates
mkdir templates/registration
```

### `news_project\settings.py`

```python=55
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')], # change
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
```

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

```shell=
touch templates/registration/login.html
touch templates/base.html
touch templates/home.html
touch templates/signup.html
```

### `templates\base.html`

```htmlmixed=
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Newspaper App</title>
</head>
<body>
<main>
  {% block content %}
  {% endblock %}
</main>
</body>
</html>

```

### `templates\home.html`

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

{% block title %}Home{% endblock %}

{% block content %}
{% if user.is_authenticated %}
  Hi {{ user.username }}!
  <p><a href="{% url 'logout' %}">logout</a></p>
{% else %}
  <p>You are not logged in</p>
  <a href="{% url 'login' %}">login</a> |
  <a href="{% url 'signup' %}">signup</a>
{% endif %}
{% endblock %}
```

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

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

{% block title %}Login{% endblock %}

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

```

### `templates\signup.html`

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

{% block title %}Sign Up{% endblock %}

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

## URLs

### `news_project\urls.py`

```python=16
from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView

urlpatterns = [
    path('', TemplateView.as_view(template_name='home.html'), name='home'),
    path('admin/', admin.site.urls),
    path('users/', include('users.urls')),
    path('users/', include('django.contrib.auth.urls')),
]
```

```shell
touch users/urls.py
```

### `users\urls.py`

```python=
from django.urls import path

from . import views

urlpatterns = [
    path('signup/', views.SignUp.as_view(), name='signup'),
]
```

### `users\views.py`

```python=
from django.urls import reverse_lazy
from django.views import generic

from .forms import CustomUserCreationForm


class SignUp(generic.CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'
```

```shell
python manage.py runserver
```

### `users\forms.py`

```python=8
class CustomUserCreationForm(UserCreationForm):


    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = ('username', 'email', ) # update



class CustomUserChangeForm(UserChangeForm):


    class Meta:
        model = CustomUser
        fields = ('username', 'email', ) # update
```

---

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

[Учебный центр компьютерных технологий "Кит"](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;">
