Nikita 1 éve
commit
3580fa43f3

+ 3 - 0
.idea/.gitignore

@@ -0,0 +1,3 @@
+# Default ignored files
+/shelf/
+/workspace.xml

+ 8 - 0
.idea/django_gr421_mn.iml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="PYTHON_MODULE" version="4">
+  <component name="NewModuleRootManager">
+    <content url="file://$MODULE_DIR$" />
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+</module>

+ 18 - 0
.idea/inspectionProfiles/Project_Default.xml

@@ -0,0 +1,18 @@
+<component name="InspectionProjectProfileManager">
+  <profile version="1.0">
+    <option name="myName" value="Project Default" />
+    <inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
+      <option name="ignoredPackages">
+        <value>
+          <list size="5">
+            <item index="0" class="java.lang.String" itemvalue="Django" />
+            <item index="1" class="java.lang.String" itemvalue="Python" />
+            <item index="2" class="java.lang.String" itemvalue="Pillow" />
+            <item index="3" class="java.lang.String" itemvalue="bootstrap4" />
+            <item index="4" class="java.lang.String" itemvalue="django-bootstrap4" />
+          </list>
+        </value>
+      </option>
+    </inspection_tool>
+  </profile>
+</component>

+ 6 - 0
.idea/inspectionProfiles/profiles_settings.xml

@@ -0,0 +1,6 @@
+<component name="InspectionProjectProfileManager">
+  <settings>
+    <option name="USE_PROJECT_PROFILE" value="false" />
+    <version value="1.0" />
+  </settings>
+</component>

+ 7 - 0
.idea/misc.xml

@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11" project-jdk-type="Python SDK" />
+  <component name="PyCharmProfessionalAdvertiser">
+    <option name="shown" value="true" />
+  </component>
+</project>

+ 8 - 0
.idea/modules.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectModuleManager">
+    <modules>
+      <module fileurl="file://$PROJECT_DIR$/.idea/django_gr421_mn.iml" filepath="$PROJECT_DIR$/.idea/django_gr421_mn.iml" />
+    </modules>
+  </component>
+</project>

+ 6 - 0
.idea/vcs.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="" vcs="Git" />
+  </component>
+</project>

BIN
shop/db.sqlite3


+ 22 - 0
shop/manage.py

@@ -0,0 +1,22 @@
+#!/usr/bin/env python
+"""Django's command-line utility for administrative tasks."""
+import os
+import sys
+
+
+def main():
+    """Run administrative tasks."""
+    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shop.settings')
+    try:
+        from django.core.management import execute_from_command_line
+    except ImportError as exc:
+        raise ImportError(
+            "Couldn't import Django. Are you sure it's installed and "
+            "available on your PYTHONPATH environment variable? Did you "
+            "forget to activate a virtual environment?"
+        ) from exc
+    execute_from_command_line(sys.argv)
+
+
+if __name__ == '__main__':
+    main()

BIN
shop/media/image/P19C-MTK3282-PJY002N_01_sf.jpg


BIN
shop/media/image/T-ajpW9AFQE.jpg


+ 0 - 0
shop/shop/__init__.py


+ 16 - 0
shop/shop/asgi.py

@@ -0,0 +1,16 @@
+"""
+ASGI config for shop project.
+
+It exposes the ASGI callable as a module-level variable named ``application``.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
+"""
+
+import os
+
+from django.core.asgi import get_asgi_application
+
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shop.settings')
+
+application = get_asgi_application()

+ 136 - 0
shop/shop/settings.py

@@ -0,0 +1,136 @@
+"""
+Django settings for shop project.
+
+Generated by 'django-admin startproject' using Django 4.2.6.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/4.2/topics/settings/
+
+For the full list of settings and their values, see
+https://docs.djangoproject.com/en/4.2/ref/settings/
+"""
+
+from pathlib import Path
+import os
+
+AUTH_USER_MODEL = 'site_shop.AdvUser'
+
+# Build paths inside the project like this: BASE_DIR / 'subdir'.
+BASE_DIR = Path(__file__).resolve().parent.parent
+
+
+# Quick-start development settings - unsuitable for production
+# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
+
+# SECURITY WARNING: keep the secret key used in production secret!
+SECRET_KEY = 'django-insecure-pgxz$n5tqh_4)%ok^oq^of7_@m8^7w37g_p&a7&(nqai+xm_-r'
+
+# SECURITY WARNING: don't run with debug turned on in production!
+DEBUG = True
+
+ALLOWED_HOSTS = []
+
+
+# Application definition
+
+INSTALLED_APPS = [
+    'bootstrap4',
+    'site_shop',
+    'django.contrib.admin',
+    'django.contrib.auth',
+    'django.contrib.contenttypes',
+    'django.contrib.sessions',
+    'django.contrib.messages',
+    'django.contrib.staticfiles',
+]
+
+MIDDLEWARE = [
+    'django.middleware.security.SecurityMiddleware',
+    'django.contrib.sessions.middleware.SessionMiddleware',
+    'django.middleware.common.CommonMiddleware',
+    'django.middleware.csrf.CsrfViewMiddleware',
+    'django.contrib.auth.middleware.AuthenticationMiddleware',
+    'django.contrib.messages.middleware.MessageMiddleware',
+    'django.middleware.clickjacking.XFrameOptionsMiddleware',
+]
+
+ROOT_URLCONF = 'shop.urls'
+
+TEMPLATES = [
+    {
+        'BACKEND': 'django.template.backends.django.DjangoTemplates',
+        'DIRS': [],
+        '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',
+            ],
+        },
+    },
+]
+
+WSGI_APPLICATION = 'shop.wsgi.application'
+
+
+# Database
+# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
+
+DATABASES = {
+    'default': {
+        'ENGINE': 'django.db.backends.sqlite3',
+        'NAME': BASE_DIR / 'db.sqlite3',
+    }
+}
+
+
+# Password validation
+# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
+
+AUTH_PASSWORD_VALIDATORS = [
+    {
+        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
+    },
+    {
+        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
+    },
+    {
+        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
+    },
+    {
+        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
+    },
+]
+
+
+# Internationalization
+# https://docs.djangoproject.com/en/4.2/topics/i18n/
+
+LANGUAGE_CODE = 'en-us'
+
+TIME_ZONE = 'UTC'
+
+USE_I18N = True
+
+USE_TZ = True
+
+
+# Static files (CSS, JavaScript, Images)
+# https://docs.djangoproject.com/en/4.2/howto/static-files/
+
+STATIC_URL = 'static/'
+
+# Default primary key field type
+# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
+
+DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
+
+MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
+MEDIA_URL = '/media/'
+
+LOGIN_URL = '/login'
+LOGIN_REDIRECT_URL = '/profile'
+
+LOGOUT_REDIRECT_URL = '/'

+ 9 - 0
shop/shop/urls.py

@@ -0,0 +1,9 @@
+from django.contrib import admin
+from django.urls import path, include
+from django.conf import settings
+from django.conf.urls.static import static
+
+urlpatterns = [
+    path('admin/', admin.site.urls),
+    path('', include('site_shop.urls')),
+] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

+ 16 - 0
shop/shop/wsgi.py

@@ -0,0 +1,16 @@
+"""
+WSGI config for shop project.
+
+It exposes the WSGI callable as a module-level variable named ``application``.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
+"""
+
+import os
+
+from django.core.wsgi import get_wsgi_application
+
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shop.settings')
+
+application = get_wsgi_application()

+ 0 - 0
shop/site_shop/__init__.py


+ 4 - 0
shop/site_shop/admin.py

@@ -0,0 +1,4 @@
+from django.contrib import admin
+from .models import Service
+
+admin.site.register(Service)

+ 6 - 0
shop/site_shop/apps.py

@@ -0,0 +1,6 @@
+from django.apps import AppConfig
+
+
+class SiteShopConfig(AppConfig):
+    default_auto_field = 'django.db.models.BigAutoField'
+    name = 'site_shop'

+ 14 - 0
shop/site_shop/forms.py

@@ -0,0 +1,14 @@
+from django import forms
+from .models import AdvUser, Service
+
+class RegistrationForm(forms.ModelForm):
+    class Meta:
+        model = AdvUser
+        fields = ('username', 'password')
+
+class ServiceForm(forms.ModelForm):
+    class Meta:
+        model = Service
+        fields = ('__all__')
+
+

+ 49 - 0
shop/site_shop/migrations/0001_initial.py

@@ -0,0 +1,49 @@
+# Generated by Django 4.2.6 on 2023-12-26 05:06
+
+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='Service',
+            fields=[
+                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('name', models.CharField(max_length=80, verbose_name='Заголовок')),
+                ('desc', models.CharField(max_length=250, verbose_name='Краткое описание')),
+                ('description', models.TextField(verbose_name='Полное описание')),
+                ('image', models.ImageField(upload_to='image/', verbose_name='Изображение')),
+            ],
+        ),
+        migrations.CreateModel(
+            name='AdvUser',
+            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')),
+                ('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')),
+            ],
+            managers=[
+                ('objects', django.contrib.auth.models.UserManager()),
+            ],
+        ),
+    ]

+ 0 - 0
shop/site_shop/migrations/__init__.py


+ 12 - 0
shop/site_shop/models.py

@@ -0,0 +1,12 @@
+from django.db import models
+from django.contrib.auth.models import AbstractUser
+
+class Service(models.Model):
+    name = models.CharField('Заголовок',max_length=80)
+    desc = models.CharField('Краткое описание',max_length=250)
+    description = models.TextField('Полное описание')
+    image = models.ImageField('Изображение',upload_to='image/')
+
+class AdvUser(AbstractUser):
+    class Meta:
+        pass

+ 14 - 0
shop/site_shop/templates/accounts/profile.html

@@ -0,0 +1,14 @@
+{% extends 'base.html' %}
+
+{% block title %}Профиль{% endblock %}
+
+
+
+{% block content %}
+{% if user.is_authenticated %}
+<h1>Профиль</h1>
+    <p>{{user.email}}</p>
+{% else %}
+<p>Вы не вошли в систему!</p>
+{% endif %}
+{% endblock %}

+ 16 - 0
shop/site_shop/templates/add.html

@@ -0,0 +1,16 @@
+{% extends "base.html" %}
+
+{% block title %} Добавление товара {% endblock %}
+
+{% block content %}
+    {% if user.is_authenticated %}
+
+    <h3>Добавление товара</h3>
+    <form method="post" action="{% url 'add' %}" enctype="multipart/form-data">
+        {% csrf_token %}
+        {{ form.as_p }}
+        <button type="submit">Добавить товар</button>
+    </form>
+    {% endif %}
+
+{% endblock %}

+ 30 - 0
shop/site_shop/templates/base.html

@@ -0,0 +1,30 @@
+{% load static%}
+{% load bootstrap4 %}
+<!doctype html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport"
+          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
+    <meta http-equiv="X-UA-Compatible" content="ie=edge">
+    <title>{% block title %} {% endblock %}</title>
+</head>
+<body>
+    <header>
+        <a href="{% url 'index' %}">Главная страница</a>
+        <a href="{% url 'services' %}">Товары</a>
+        {% if user.is_authenticated %}
+        <a href="{% url 'profile' %}">Профиль</a>
+        <a href="{% url 'logout' %}">Выход</a>
+        {% else %}
+        <a href="{% url 'register' %}">Регистрация</a>
+        <a href="{% url 'login' %}">Вход</a>
+        {% endif %}
+    </header>
+
+
+    <main>
+        {% block content %} {% endblock %}
+    </main>
+</body>
+</html>

+ 13 - 0
shop/site_shop/templates/detail.html

@@ -0,0 +1,13 @@
+{% extends "base.html" %}
+
+{% block title %}{{ service.name }}{% endblock %}
+
+{% block content %}
+    <div>
+
+        <h3>{{ service.name }}</h3>
+        <img src="{{service.image.url}}" width="350px" height="250px">
+        <p>{{ service.description }}</p>
+
+    </div>
+{% endblock %}

+ 15 - 0
shop/site_shop/templates/index.html

@@ -0,0 +1,15 @@
+{% extends 'base.html' %}
+
+{% block title %}Главная{% endblock %}
+
+{% block content %}
+<h1>Главная страница</h1>
+    {% for service in service_list%}
+        <div>
+            <h5 class="index-title">{{service.title}}</h5>
+            <p>{{service.desc}}</p>
+            <img src="{{service.image.url}}" width="350px" height="250px">
+            <a href="{% url 'detail' service.id %}" class="btn btn-warning">Узнать подробнее</a>
+        </div>
+    {% endfor %}
+{% endblock %}

+ 14 - 0
shop/site_shop/templates/login.html

@@ -0,0 +1,14 @@
+{% extends "base.html" %}
+
+{% block title %} Авторизация {% endblock %}
+
+{% block content %}
+
+    <h3>Вход</h3>
+    <form method="post" action="{% url 'login' %}">
+        {% csrf_token %}
+        {{ form.as_p }}
+        <button type="submit">Войти</button>
+    </form>
+
+{% endblock %}

+ 15 - 0
shop/site_shop/templates/registration.html

@@ -0,0 +1,15 @@
+{% extends 'base.html' %}
+
+{% block title %} Регистрация {% endblock %}
+
+{% block content %}
+<h1>Регистрация</h1>
+
+<form method="post">
+    {% csrf_token %}
+    <input type="hidden" name="next" value="{{ next }}" />
+    {{ form.as_p }}
+    <p ><button type="submit">Зарегистрироваться</button></p>
+</form>
+
+{% endblock %}

+ 18 - 0
shop/site_shop/templates/services.html

@@ -0,0 +1,18 @@
+{% extends 'base.html' %}
+
+{% block title %}Товары{% endblock %}
+
+{% block content %}
+    <h1>Все товары</h1>
+    {% if user.is_staff %}
+    <a href="{% url 'add' %}">Добавить товар</a>
+    {% endif %}
+    {% for service in service_list%}
+        <div>
+            <h5 class="index-title">{{service.name}}</h5>
+            <p>{{service.desc}}</p>
+            <img src="{{service.image.url}}" width="350px" height="250px">
+            <a href="" class="btn btn-warning">Узнать подробнее</a>
+        </div>
+    {% endfor %}
+{% endblock %}

+ 3 - 0
shop/site_shop/tests.py

@@ -0,0 +1,3 @@
+from django.test import TestCase
+
+# Create your tests here.

+ 14 - 0
shop/site_shop/urls.py

@@ -0,0 +1,14 @@
+from django.urls import path
+from .views import index, login_view, services, profile, logout_view, register, add, DetailRequest
+
+urlpatterns = [
+    path('', index.as_view(), name = 'index'),
+    path('login/', login_view, name = 'login'),
+    path('services/', services.as_view(), name = 'services'),
+    path('profile/', profile, name = 'profile'),
+    path('register/', register, name = 'register'),
+    path('logout/', logout_view, name = 'logout'),
+    path('add/', add, name = 'add'),
+    path('detail/<int:pk>', DetailRequest.as_view(), name = 'detail'),
+
+]

+ 60 - 0
shop/site_shop/views.py

@@ -0,0 +1,60 @@
+from django.shortcuts import render, redirect
+from .models import Service
+from django.views.generic.base import View
+from django.contrib.auth import logout
+from django.contrib.auth.views import LoginView
+from .forms import RegistrationForm, ServiceForm
+from django.views.generic import DetailView
+
+class index(View):
+    def get(self, request):
+        services = Service.objects.all()
+        return render(request, 'index.html', {'service_list': services})
+
+def profile(request):
+    return render(request, 'accounts/profile.html')
+
+
+class services(View):
+    def get(self, request):
+        services = Service.objects.all()
+        return render(request, 'services.html', {'service_list': services})
+
+
+
+
+
+
+login_view = LoginView.as_view(template_name='login.html')
+
+def register(request):
+    if request.method == "POST":
+        form = RegistrationForm(request.POST)
+        if form.is_valid():
+            user = form.save(commit=True)
+            user.set_password(form.cleaned_data['password'])
+            user.save()
+            return render(request, 'login.html')
+    else:
+        form = RegistrationForm()
+    return render(request, 'registration.html', {'form': form})
+
+def logout_view(request):
+    logout(request)
+    return redirect('index')
+
+def add(request):
+    if request.method == "POST":
+        form = ServiceForm(request.POST, request.FILES)
+        if form.is_valid():
+            form.save()
+            return redirect('index')
+    else:
+        form = ServiceForm()
+    return render(request, 'add.html', {'form': form})
+
+class DetailRequest(DetailView):
+    model = Service
+    template_name = 'detail.html'
+    context_object_name = 'service'
+