Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lesson 3 modified and Lesson 4 #4

Open
wants to merge 1 commit into
base: lesson-3
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added geekshop/authapp/__init__.py
Empty file.
6 changes: 6 additions & 0 deletions geekshop/authapp/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.contrib import admin
from authapp.models import User
# Register your models here.


admin.site.register(User)
6 changes: 6 additions & 0 deletions geekshop/authapp/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class AuthappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'authapp'
37 changes: 37 additions & 0 deletions geekshop/authapp/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from authapp.models import User

class UserLoginForm(AuthenticationForm):
class Meta:
model = User
fields = ('username', 'password')


def __init__(self, *args, **kwargs):
super(UserLoginForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['placeholder'] = 'Введите имя пользователя'
self.fields['password'].widget.attrs['placeholder'] = 'Введите пароль'
for field_name, field in self.fields.items():
field.widget.attrs['class'] = 'form-control py-4'


class UserRegisterForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'last_name', 'first_name', 'email')


def __init__(self, *args, **kwargs):
super(UserRegisterForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['placeholder'] = 'Введите имя пользователя'
self.fields['password1'].widget.attrs['placeholder'] = 'Введите пароль'
self.fields['password2'].widget.attrs['placeholder'] = 'Введите пароль повторно'
self.fields['last_name'].widget.attrs['placeholder'] = 'Введите фамилию'
self.fields['first_name'].widget.attrs['placeholder'] = 'Введите имя'
self.fields['email'].widget.attrs['placeholder'] = 'Введите email'
self.fields['email'].required = False

for field_name, field in self.fields.items():
field.widget.attrs['class'] = 'form-control py-4'


46 changes: 46 additions & 0 deletions geekshop/authapp/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Generated by Django 3.2.6 on 2022-04-01 18:19

import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone


class Migration(migrations.Migration):

initial = True

dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]

operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('image', models.ImageField(blank=True, upload_to='user_image')),
('age', models.PositiveIntegerField(default=18)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]
Empty file.
8 changes: 8 additions & 0 deletions geekshop/authapp/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.contrib.auth.models import AbstractUser
from django.db import models

# Create your models here.

class User(AbstractUser):
image = models.ImageField(upload_to='user_image', blank=True)
age = models.PositiveIntegerField(default=18)
34 changes: 34 additions & 0 deletions geekshop/authapp/templates/authapp/base.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
<meta name="description" content=""/>
<meta name="author" content=""/>
{% block title %}
{% endblock %}
<link href="{% static 'css/auth-admin.css' %}" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/js/all.min.js"
crossorigin="anonymous"></script>
</head>
<body class="bg-primary">
<div id="layoutAuthentication">
<div id="layoutAuthentication_content">
<main>
<div class="container">
<div class="row justify-content-center">
{% block form %}
{% endblock %}
</div>
</div>
</main>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
crossorigin="anonymous"></script>
<script src="{% static 'js/auth-admin.js' %}"></script>
</body>
</html>
42 changes: 42 additions & 0 deletions geekshop/authapp/templates/authapp/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{% extends 'authapp/base.html' %}

{% block title %}
<title>GeekShop - Авторизация</title>
{% endblock %}

{% block form %}
<div class="col-lg-5">
<div class="alert alert-warning alert-dismissible fade show" role="alert"
style="margin-top: 50px;">
<strong>Holy guacamole!</strong> You should check in on some of those fields below.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="card shadow-lg border-0 rounded-lg mt-5">
<div class="card-header"><h3 class="text-center font-weight-light my-4">Авторизация</h3>
</div>
<div class="card-body">
<form action="{% url 'authapp:login' %}" method="post">
{% csrf_token %}
<div class="form-group">
<label class="small mb-1" for="{{ form.username.id_for_label }}">Имя пользователя</label>
{{ form.username }}
</div>
<div class="form-group">
<label class="small mb-1" for="{{ form.pasword.id_for_label }}">Пароль</label>
{{ form.password }}
</div>
<!-- {{ form.as_p }} -->
<div class="form-group d-flex align-items-center justify-content-between mt-4 mb-0">
<a class="small" href="#">Забыли пароль?</a>
<input class="btn btn-primary" type="submit" value="Авторизоваться">
</div>
</form>
</div>
<div class="card-footer text-center">
<div class="small"><a href="{% url 'authapp:register' %}">Нужен аккаунт? Зарегистрируйся!</a></div>
</div>
</div>
</div>
{% endblock %}
73 changes: 73 additions & 0 deletions geekshop/authapp/templates/authapp/register.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
{% extends 'authapp/base.html' %}

{% block title %}
<title>GeekShop - Регистрация</title>
{% endblock %}

{% block form %}

<div class="col-lg-7">
<div class="alert alert-warning alert-dismissible fade show" role="alert"
style="margin-top: 50px;">
<strong>Holy guacamole!</strong> You should check in on some of those fields below.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="card shadow-lg border-0 rounded-lg mt-5">
<div class="card-header"><h3 class="text-center font-weight-light my-4">Создать аккаунт</h3>
</div>
<div class="card-body">
<form action="{% url 'authapp:register' %}" method="post">
{% csrf_token %}
<div class="form-row">
<div class="col-md-6">
<div class="form-group">
<label class="small mb-1" for="{{ form.first_name.id_for_label }}">Имя</label>
{{ form.first_name }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="small mb-1" for="{{ form.last_name.id_for_label }}">Фамилия</label>
{{ form.last_name }}
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-6">
<label class="small mb-1" for="{{ form.username.id_for_label }}">Имя пользователя</label>
{{ form.username }}
</div>
<div class="col-md-6">
<label class="small mb-1" for="{{ form.email.id_for_label }}">Адрес электронной
почты</label>
{{ form.email }}
</div>
</div>
<div class="form-row">
<div class="col-md-6">
<div class="form-group">
<label class="small mb-1" for="{{ form.password1.id_for_label }}">Пароль</label>
{{ form.password1 }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="small mb-1" for="{{ form.password2.id_for_label }}">Подтверждение
пароля</label>
{{ form.password2 }}
</div>
</div>
</div>
<div class="form-group mt-4 mb-0">
<input class="btn btn-primary btn-block" type="submit" value="Создать аккаунт">
</div>
</form>
</div>
<div class="card-footer text-center">
<div class="small"><a href="{% url 'authapp:login'%}">Уже есть аккаунт? Авторизоваться</a></div>
</div>
</div>
</div>
{% endblock %}
3 changes: 3 additions & 0 deletions geekshop/authapp/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
9 changes: 9 additions & 0 deletions geekshop/authapp/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.urls import path
from authapp.views import login, register, logout

app_name = 'authapp'
urlpatterns = [
path('login/', login, name='login'),
path('register/', register, name='register'),
path('logout/', logout, name='logout')
]
52 changes: 52 additions & 0 deletions geekshop/authapp/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from django.shortcuts import render
from django.contrib import auth
from django.http import HttpResponseRedirect
from authapp.forms import UserLoginForm, UserRegisterForm
from django.urls import reverse
# Create your views here.

def login(request):
if request.method == 'POST':
form = UserLoginForm(data=request.POST)
if form.is_valid():
username = request.POST.get('username')
password = request.POST.get('password')
user = auth.authenticate(username=username, password=password)
if user.is_active:
auth.login(request, user)
return HttpResponseRedirect(reverse('index'))
else:
print('Юзер не активный')
else:
print(form.errors)
else:
form = UserLoginForm

context = {
'title' : 'Geekshop | Авторизациия',
'form' : form
}
return render(request, 'authapp/login.html', context)


def register(request):
if request.method == 'POST':
form = UserRegisterForm(data=request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('authapp:login'))
else:
print(form.errors)
else:
form = UserRegisterForm()

context = {
'title': 'Geekshop | Регистрация',
'form' : form
}
return render(request, 'authapp/register.html', context)


def logout(request):
auth.logout(request)
return render(request, 'mainapp/index.html')
Binary file modified geekshop/geekshop/__pycache__/settings.cpython-38.pyc
Binary file not shown.
Binary file modified geekshop/geekshop/__pycache__/urls.cpython-38.pyc
Binary file not shown.
5 changes: 4 additions & 1 deletion geekshop/geekshop/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
'django.contrib.messages',
'django.contrib.staticfiles',
'mainapp',
'authapp'
]

MIDDLEWARE = [
Expand Down Expand Up @@ -129,4 +130,6 @@


MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_ROOT = BASE_DIR / 'media'

AUTH_USER_MODEL = 'authapp.User'
3 changes: 2 additions & 1 deletion geekshop/geekshop/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
urlpatterns = [
path('admin/', admin.site.urls),
path('', mainapp.index, name='index'),
path('products/', include('mainapp.urls', namespace='mainapp'))
path('products/', include('mainapp.urls', namespace='mainapp')),
path('user/', include('authapp.urls', namespace='authapp'))
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Binary file modified geekshop/mainapp/__pycache__/models.cpython-38.pyc
Binary file not shown.
Binary file modified geekshop/mainapp/__pycache__/views.cpython-38.pyc
Binary file not shown.
2 changes: 1 addition & 1 deletion geekshop/mainapp/fixtures/category.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
[{"model": "mainapp.productcategories", "pk": 1, "fields": {"name": "�������", "description": ""}}, {"model": "mainapp.productcategories", "pk": 2, "fields": {"name": "������", "description": ""}}, {"model": "mainapp.productcategories", "pk": 3, "fields": {"name": "�����", "description": ""}}, {"model": "mainapp.productcategories", "pk": 4, "fields": {"name": "����������", "description": ""}}, {"model": "mainapp.productcategories", "pk": 5, "fields": {"name": "�������", "description": ""}}]
[{"model": "mainapp.productcategories", "pk": 1, "fields": {"name": "Новинки", "description": ""}}, {"model": "mainapp.productcategories", "pk": 2, "fields": {"name": "Одежда", "description": ""}}, {"model": "mainapp.productcategories", "pk": 3, "fields": {"name": "Обувь", "description": ""}}, {"model": "mainapp.productcategories", "pk": 4, "fields": {"name": "Аксессуары", "description": ""}}, {"model": "mainapp.productcategories", "pk": 5, "fields": {"name": "Подарки", "description": ""}}]
2 changes: 1 addition & 1 deletion geekshop/mainapp/fixtures/product.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
[{"model": "mainapp.product", "pk": 1, "fields": {"name": "���� ������� ����� � ������������ adidas Originals", "image": "products_images/Adidas-hoodie.png", "description": "������ ����� ��� ���������. ����� � ������� � ��� ����� �����.", "price": "6090.00", "quantity": 12, "category": 2}}, {"model": "mainapp.product", "pk": 2, "fields": {"name": "����� ������ The North Face", "image": "products_images/Blue-jacket-The-North-Face.png", "description": "������� �����. ����������������� ��������. ������ � ������ ������� �����������.", "price": "23725.00", "quantity": 7, "category": 2}}, {"model": "mainapp.product", "pk": 3, "fields": {"name": "���������� ���������� oversized-��� ASOS DESIGN", "image": "products_images/Brown-sports-oversized-top-ASOS-DESIGN.png", "description": "�������� � �������� ���������. ������� � ������.", "price": "3390.00", "quantity": 11, "category": 1}}, {"model": "mainapp.product", "pk": 4, "fields": {"name": "������ ������ Nike Heritage", "image": "products_images/Black-Nike-Heritage-backpack.png", "description": "������� �����. ������ ��������.", "price": "2340.00", "quantity": 14, "category": 4}}, {"model": "mainapp.product", "pk": 5, "fields": {"name": "������ ����� �� ��������� � 3 ������ �������� Dr Martens 1461 Bex", "image": "products_images/Black-Dr-Martens-shoes.png", "description": "������� ������� ����. ����������� ��������.", "price": "13590.00", "quantity": 9, "category": 3}}, {"model": "mainapp.product", "pk": 6, "fields": {"name": "�����-����� ������� ������� ����� ASOS DESIGN", "image": "products_images/Dark-blue-wide-leg-ASOs-DESIGN-trousers.png", "description": "������ ���������� ����� �������� ��������� �����.", "price": "2890.00", "quantity": 15, "category": 2}}]
[{"model": "mainapp.product", "pk": 1, "fields": {"name": "Худи черного цвета с монограммами adidas Originals", "image": "products_images/Adidas-hoodie.png", "description": "Мягкая ткань для свитшотов. Стиль и комфорт – это образ жизни.", "price": "6090.00", "quantity": 12, "category": 2}}, {"model": "mainapp.product", "pk": 2, "fields": {"name": "Синяя куртка The North Face", "image": "products_images/Blue-jacket-The-North-Face.png", "description": "Гладкая ткань. Водонепроницаемое покрытие. Легкий и теплый пуховый наполнитель.", "price": "23725.00", "quantity": 7, "category": 2}}, {"model": "mainapp.product", "pk": 3, "fields": {"name": "Коричневый спортивный oversized-топ ASOS DESIGN", "image": "products_images/Brown-sports-oversized-top-ASOS-DESIGN.png", "description": "Материал с плюшевой текстурой. Удобный и мягкий.", "price": "3390.00", "quantity": 11, "category": 1}}, {"model": "mainapp.product", "pk": 4, "fields": {"name": "Черный рюкзак Nike Heritage", "image": "products_images/Black-Nike-Heritage-backpack.png", "description": "Плотная ткань. Легкий материал.", "price": "2340.00", "quantity": 14, "category": 4}}, {"model": "mainapp.product", "pk": 5, "fields": {"name": "Черные туфли на платформе с 3 парами люверсов Dr Martens 1461 Bex", "image": "products_images/Black-Dr-Martens-shoes.png", "description": "Гладкий кожаный верх. Натуральный материал.", "price": "13590.00", "quantity": 9, "category": 3}}, {"model": "mainapp.product", "pk": 6, "fields": {"name": "Темно-синие широкие строгие брюки ASOS DESIGN", "image": "products_images/Dark-blue-wide-leg-ASOs-DESIGN-trousers.png", "description": "Легкая эластичная ткань сирсакер Фактурная ткань.", "price": "2890.00", "quantity": 15, "category": 2}}]
Loading