Skip to content
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
15 changes: 11 additions & 4 deletions 1.1-first-project/first_project/app/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from datetime import datetime
from os import listdir

from django.http import HttpResponse
from django.shortcuts import render, reverse

Expand All @@ -8,8 +11,8 @@ def home_view(request):
# функцию `reverse`
pages = {
'Главная страница': reverse('home'),
'Показать текущее время': '',
'Показать содержимое рабочей директории': ''
'Показать текущее время': reverse('time'),
'Показать содержимое рабочей директории': reverse('workdir')
}

# context и параметры render менять не нужно
Expand All @@ -23,7 +26,7 @@ def home_view(request):
def time_view(request):
# обратите внимание – здесь HTML шаблона нет,
# возвращается просто текст
current_time = None
current_time = datetime.now().strftime("%Y.%m.%d %H:%M:%S")
msg = f'Текущее время: {current_time}'
return HttpResponse(msg)

Expand All @@ -32,4 +35,8 @@ def workdir_view(request):
# по аналогии с `time_view`, напишите код,
# который возвращает список файлов в рабочей
# директории
raise NotImplemented
list_dir = listdir()
msg = ''
for item in list_dir:
msg = msg + '<p>' + item + '</p>'
return HttpResponse(msg)
7 changes: 3 additions & 4 deletions 1.1-first-project/first_project/first_project/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,13 @@
from django.contrib import admin
from django.urls import path, include

from app.views import home_view

from app.views import home_view, workdir_view, time_view

urlpatterns = [
path('', home_view, name='home'),
# Раскомментируйте код, чтобы данные урлы
# обрабатывались Django
# path('current_time/', time_view, name='time'),
# path('workdir/', workdir_view, name='workdir'),
path('current_time/', time_view, name='time'),
path('workdir/', workdir_view, name='workdir'),
path('admin/', admin.site.urls),
]
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@
<title>Рецепты</title>
</head>
<body>
{% load extras %}
{% for ingredient, amount in recipe.items %}
<p>{{ ingredient }}: {{ amount }}</p>
<p>{{ ingredient }}: {% multiply amount servings %}</p>
{% empty %}
<p>Такого рецепта не знаю :(</p>
{% endfor %}


</body>
</html>
Empty file.
12 changes: 12 additions & 0 deletions 1.2-requests-templates/recipes/calculator/templatetags/extras.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from django import template

register = template.Library()


@register.simple_tag()
def multiply(x, y):
z = x * y
if type(x) == int:
return round(z)
else:
return round(z, 2)
13 changes: 13 additions & 0 deletions 1.2-requests-templates/recipes/calculator/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
# можете добавить свои рецепты ;)
}


# Напишите ваш обработчик. Используйте DATA как источник данных
# Результат - render(request, 'calculator/index.html', context)
# В качестве контекста должен быть передан словарь с рецептом:
Expand All @@ -28,3 +29,15 @@
# 'ингредиент2': количество2,
# }
# }

def calculator(request, recipe):
context = {
'recipe': {
},
'servings': 1,
}
servings = float(request.GET.get('servings', 1))
context['servings'] = servings
context['recipe'] = DATA[recipe]

return render(request, 'calculator/index.html', context)
1 change: 1 addition & 0 deletions 1.2-requests-templates/recipes/recipes/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
'django.contrib.staticfiles',

'calculator',

]

MIDDLEWARE = [
Expand Down
3 changes: 3 additions & 0 deletions 1.2-requests-templates/recipes/recipes/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@

from django.urls import path

from calculator.views import calculator

urlpatterns = [
# здесь зарегистрируйте вашу view-функцию
path('calculator/<recipe>/', calculator, name='calculator'),
]
10 changes: 6 additions & 4 deletions 2.1-databases/work_with_database/main/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,12 @@

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'netology_import_phones',
'HOST': '127.0.0.1',
'PORT': '5432',
#'ENGINE': 'django.db.backends.postgresql',
#'NAME': 'netology_import_phones',
#'HOST': '127.0.0.1',
#'PORT': '5432',
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

Expand Down
1 change: 1 addition & 0 deletions 2.1-databases/work_with_database/main/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@
path('', phones.views.index),
path('catalog/', phones.views.show_catalog, name='catalog'),
path('catalog/<slug:slug>/', phones.views.show_product, name='phone'),
path('show_db/', phones.views.show_db, name='show_db'),
]
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import csv

from django.core.management.base import BaseCommand
#from django.utils.text import slugify

from phones.models import Phone


Expand All @@ -13,5 +15,9 @@ def handle(self, *args, **options):
phones = list(csv.DictReader(file, delimiter=';'))

for phone in phones:
# TODO: Добавьте сохранение модели
pass
print(phone)
Phone.objects.create(name=phone['name'], image=phone['image'], price=phone['price'],
release_date=phone['release_date'], lte_exists=phone['lte_exists'])
#slug = slugify(phone['name']),
#id = phone['id'],
#, slug = phone['name']
15 changes: 14 additions & 1 deletion 2.1-databases/work_with_database/phones/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
from django.db import models
from django.utils.text import slugify


class Phone(models.Model):
# TODO: Добавьте требуемые поля
pass
#id = models.CharField(max_length=10, primary_key=True)
name = models.CharField(max_length=50)
#slug = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True)
image = models.CharField(max_length=100)
price = models.CharField(max_length=20)
release_date = models.CharField(max_length=50)
lte_exists = models.CharField(max_length=20)
#

def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Phone, self).save(*args, **kwargs)
27 changes: 25 additions & 2 deletions 2.1-databases/work_with_database/phones/views.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,40 @@
from django.http import HttpResponse
from django.shortcuts import render, redirect

from phones.models import Phone


def index(request):
return redirect('catalog')


def show_catalog(request):
phones = Phone.objects.all()
sort = request.GET.get('sort')
if sort == 'name':
phones = phones.order_by("name")
elif sort == 'min_price':
phones = phones.order_by("price")
elif sort == 'max_price':
phones = phones.order_by("-price")

data = [phone.__dict__ for phone in phones]

template = 'catalog.html'
context = {}
context = {'phones': data}
return render(request, template, context)


def show_product(request, slug):
phone_objects = Phone.objects.filter(slug=slug)
# print(phone_objects[0].__dict__)
template = 'product.html'
context = {}
context = {'phone': phone_objects[0].__dict__}
return render(request, template, context)


def show_db(request):
phone_objects = Phone.objects.all()
phones = [f'{p.id}: {p.name}, {p.slug}, {p.image}, {p.price}, {p.release_date}, {p.lte_exists}' for p in
phone_objects]
return HttpResponse('<br>'.join(phones))
33 changes: 31 additions & 2 deletions 2.2-databases-2/m2m-relations/articles/admin.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,37 @@
from django.contrib import admin

from .models import Article
from django.core.exceptions import ValidationError
from django.forms import BaseInlineFormSet
from .models import Tag, Article, Scope


admin.site.register(Tag)


class ScopeInlineFormset(BaseInlineFormSet):
def clean(self):
form_not_del = [f for f in self.forms if not f.cleaned_data['DELETE']]
tag_ids = set(form.cleaned_data['tag'].id for form in form_not_del)
if len(tag_ids) != len(form_not_del):
raise ValidationError('Найдены дубликаты разделов!')

is_mains = [form.cleaned_data['is_main'] for form in form_not_del if form.cleaned_data['is_main']]
print(is_mains)
if len(is_mains) == 0:
raise ValidationError('Укажите основной раздел!')

if len(is_mains) > 1:
raise ValidationError('Основным может быть только один раздел!')

return super().clean() # вызываем базовый код переопределяемого метода


class ScopeInline(admin.TabularInline):
model = Scope
extra = 0
formset = ScopeInlineFormset


@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
pass
inlines = [ScopeInline]
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Generated by Django 2.0.5 on 2018-09-30 20:46
# Generated by Django 4.0.3 on 2022-04-06 06:48

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):
Expand All @@ -25,4 +26,25 @@ class Migration(migrations.Migration):
'verbose_name_plural': 'Статьи',
},
),
migrations.CreateModel(
name='Scope',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('article', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='articles.article')),
],
),
migrations.CreateModel(
name='Tag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='Тэг')),
('is_main', models.BooleanField(default=False)),
('articles', models.ManyToManyField(related_name='scopes', through='articles.Scope', to='articles.article')),
],
),
migrations.AddField(
model_name='scope',
name='tag',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='articles.tag'),
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Generated by Django 4.0.3 on 2022-04-06 09:07

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('articles', '0001_initial'),
]

operations = [
migrations.RemoveField(
model_name='tag',
name='is_main',
),
migrations.AddField(
model_name='scope',
name='is_main',
field=models.BooleanField(default=False),
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated by Django 4.0.3 on 2022-04-06 11:08

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('articles', '0002_remove_tag_is_main_scope_is_main'),
]

operations = [
migrations.AlterField(
model_name='scope',
name='article',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scopes', to='articles.article'),
),
migrations.AlterField(
model_name='tag',
name='articles',
field=models.ManyToManyField(through='articles.Scope', to='articles.article'),
),
]
25 changes: 23 additions & 2 deletions 2.2-databases-2/m2m-relations/articles/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,36 @@


class Article(models.Model):

title = models.CharField(max_length=256, verbose_name='Название')
text = models.TextField(verbose_name='Текст')
published_at = models.DateTimeField(verbose_name='Дата публикации')
image = models.ImageField(null=True, blank=True, verbose_name='Изображение',)
image = models.ImageField(null=True, blank=True, verbose_name='Изображение', )

class Meta:
verbose_name = 'Статья'
verbose_name_plural = 'Статьи'

def __str__(self):
return self.title


class Tag(models.Model):
name = models.CharField(max_length=100, verbose_name='Раздел')
articles = models.ManyToManyField(Article, through='Scope')

class Meta:
verbose_name = 'Раздел'
verbose_name_plural = 'Разделы'

def __str__(self):
return self.name


class Scope(models.Model):
article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='scopes', verbose_name='Статья')
tag = models.ForeignKey(Tag, on_delete=models.CASCADE, verbose_name='Раздел')
is_main = models.BooleanField(default=False, verbose_name='Основной')

class Meta:

ordering = ['-is_main', '-tag']
Loading