Initial commit

parents
venv/
__pycache__/
db.sqlite3
.idea
\ No newline at end of file
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class ArticlesConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'articles'
from django.forms.models import ModelForm
from articles.models import Article, Author
class AuthorForm(ModelForm):
class Meta:
model = Author
fields = ("name",)
# Generated by Django 3.2.6 on 2021-08-09 13:55
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Author',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
],
),
migrations.CreateModel(
name='Article',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=250)),
('body', models.CharField(max_length=2000, null=True)),
('author', models.ForeignKey(default='Автор не указан', on_delete=django.db.models.deletion.SET_DEFAULT, related_name='articles', to='articles.author')),
],
),
]
# Generated by Django 3.2.6 on 2021-08-09 14:02
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('articles', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='article',
name='author',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='articles', to='articles.author'),
),
]
# Generated by Django 3.2.6 on 2021-08-11 13:47
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('articles', '0002_alter_article_author'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('text', models.TextField(max_length=400, verbose_name='Комментарий')),
('author', models.CharField(blank=True, default='Аноним', max_length=40, null=True, verbose_name='Автор')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Дата создания')),
('updated_at', models.DateTimeField(auto_now=True, verbose_name='Дата изменения')),
('article', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='articles.article', verbose_name='Статья')),
],
),
]
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=50, null=False, verbose_name="Автор")
class Article(models.Model):
title = models.CharField(max_length=250, null=False)
body = models.CharField(max_length=2000, null=True)
author = models.ForeignKey(
"articles.Author",
on_delete=models.SET_NULL,
null=True, related_name='articles')
class Comment(models.Model):
article = models.ForeignKey(
"articles.Article",
related_name="comments",
on_delete=models.CASCADE,
verbose_name="Статья")
text = models.TextField(max_length=400, verbose_name="Комментарий")
author = models.CharField(max_length=40, null=True, blank=True, verbose_name="Автор", default="Аноним")
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Дата создания")
updated_at = models.DateTimeField(auto_now=True, verbose_name="Дата изменения")
def __str__(self):
return self.text[:20]
{% extends 'base.html' %}
{% block content %}
<div class="container">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Title</th>
<th scope="col">Author</th>
</tr>
</thead>
<tbody>
{% for article in articles %}
<tr>
<th scope="row">1</th>
<td>{{ article.title }}</td>
<td>{{ article.author.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<a href="{% url 'author_create' %}">Создать автора</a>
</div>
{% endblock %}
\ No newline at end of file
{% extends 'base.html' %}
{% block content %}
<div class="container">
<form action="{% url 'author_create' %}" method="POST">
{% csrf_token %}
<div class="mb-3">
<label for="formGroupExampleInput" class="form-label">{{ form.name.label }}</label>
<input type="text" class="form-control" name="{{ form.name.name }}" id="formGroupExampleInput" placeholder="Введите имя автора">
</div>
<input type="submit">
</form>
</div>
{% endblock %}
\ No newline at end of file
{% extends 'base.html' %}
{% block content %}
<div class="container">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
{% for author in authors %}
<tr>
<th scope="row">1</th>
<td>{{ author.name }}</td>
<td>
<div style="display: flex;">
<a class="btn btn-info small" href="{% url 'author_update' author.pk %}">Изменить</a>
<a class="btn btn-danger small" href="{% url 'author_delete' author.pk %}">Удалить</a>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<a href="{% url 'author_create' %}">Создать автора</a>
</div>
{% endblock %}
\ No newline at end of file
{% extends 'base.html' %}
{% block content %}
<form action="{% url 'author_update' pk %}" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
{% endblock %}
\ No newline at end of file
<!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">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<title>Document</title>
</head>
<body>
{% include 'partial/navbar.html' %}
{% block content %}
{% endblock %}
</body>
</html>
\ No newline at end of file
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{% url 'author_list' %}">Список авторов</a>
</li>
</ul>
</div>
</div>
</nav>
\ No newline at end of file
from django.test import TestCase
# Create your tests here.
from django.urls import path
from .views import (
article_list_view,
create_author_view,
author_list_view, author_edit_view, author_delete_view, AuthorView
)
urlpatterns = [
path(
'',
article_list_view,
name="article_list"
),
path(
'create/',
AuthorView.as_view(),
name="author_create"
),
path(
'authors/',
author_list_view,
name="author_list"
),
path(
'author/<int:pk>/update/',
author_edit_view,
name="author_update"
),
path(
'author/<int:pk>/delete/',
author_delete_view,
name="author_delete"
)
]
from django.shortcuts import render, redirect, get_object_or_404
from django.views import View
from articles.models import Article, Author
from .forms import AuthorForm
def article_list_view(request):
if request.method == "GET":
articles = Article.objects.all()
return render(
request,
template_name="articles/article_list.html",
context={'articles': articles}
)
def author_list_view(request):
if request.method == "GET":
authors = Author.objects.all()
return render(
request,
template_name="authors/author_list.html",
context={'authors': authors}
)
class AuthorView(View):
url_pattern = 'authors/author_create.html'
def get(self, request, *args, **kwargs):
form = AuthorForm()
return render(
request,
self.url_pattern,
context={'form': form})
def post(self, request, *args, **kwargs):
form = AuthorForm(request.POST)
if form.is_valid():
form.save()
return redirect('author_list')
def create_author_view(request):
if request.method == "GET":
form = AuthorForm()
return render(
request,
'authors/author_create.html',
context={'form': form})
if request.method == "POST":
form = AuthorForm(request.POST)
if form.is_valid():
form.save()
return redirect('author_list')
def author_edit_view(request, pk):
author = get_object_or_404(Author, pk=pk)
if request.method == "GET":
form = AuthorForm(instance=author)
return render(
request,
'authors/author_update.html',
context={'form': form, "pk": pk})
if request.method == "POST":
form = AuthorForm(request.POST)
if form.is_valid():
author.name = request.POST.get("name")
author.save(update_fields=['name', ])
return redirect('author_list')
def author_delete_view(request, pk):
if request.method == "GET":
author = get_object_or_404(Author, pk=pk)
author.delete()
return redirect('author_list')
"""
ASGI config for article_proj 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/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'article_proj.settings')
application = get_asgi_application()
"""
Django settings for article_proj project.
Generated by 'django-admin startproject' using Django 3.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# 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/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-wse7x-3t6%mo#l9t3r_c2_5ek_c$npk1lj31!*(lt9xtq!t5ea'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'articles',
]
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 = 'core.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'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 = 'core.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
"""article_proj URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('articles.urls')),
]
"""
WSGI config for article_proj 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/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
application = get_wsgi_application()
#!/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', 'core.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()
asgiref==3.4.1
Django==3.2.6
pytz==2021.1
sqlparse==0.4.1
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment