Вебинар 37

parent 062771cb
# Generated by Django 3.2.4 on 2021-06-23 13:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('article', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='article',
options={'verbose_name': 'Статья', 'verbose_name_plural': 'Статьи'},
),
migrations.AddField(
model_name='article',
name='publication_date',
field=models.DateTimeField(null=True, verbose_name='Дата и время публикации'),
),
]
...@@ -7,6 +7,7 @@ class Article(models.Model): ...@@ -7,6 +7,7 @@ class Article(models.Model):
author = models.CharField(max_length=100, null=False, blank=False, verbose_name='Автор') author = models.CharField(max_length=100, null=False, blank=False, verbose_name='Автор')
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Дата и время создания") created_at = models.DateTimeField(auto_now_add=True, verbose_name="Дата и время создания")
updated_at = models.DateTimeField(auto_now=True, verbose_name="Дата и время изменения") updated_at = models.DateTimeField(auto_now=True, verbose_name="Дата и время изменения")
publication_date = models.DateTimeField(verbose_name="Дата и время публикации", null=True, blank=False)
def __str__(self): def __str__(self):
return f"{self.pk}. {self.title}" return f"{self.pk}. {self.title}"
...@@ -14,3 +15,4 @@ class Article(models.Model): ...@@ -14,3 +15,4 @@ class Article(models.Model):
class Meta: class Meta:
verbose_name='Статья' verbose_name='Статья'
verbose_name_plural='Статьи' verbose_name_plural='Статьи'
from django.urls import path from django.urls import path
from article.views import article_create_view, article_list_view from article.views import article_create_view, article_list_view, article_detail_view, article_update_view
urlpatterns = [ urlpatterns = [
path('add/', article_create_view, name='add_article'), path('add/', article_create_view, name='add_article'),
path('list/', article_list_view, name='article_list') path('list/', article_list_view, name='article_list'),
path('detail/<int:pk>', article_detail_view, name='article_detail'),
path('edit/<int:pk>', article_update_view, name='article_update'),
] ]
\ No newline at end of file
from django.shortcuts import render from django.shortcuts import render
from article.models import Article from article.models import Article
from django.shortcuts import redirect
from django.http import HttpResponseNotFound
from datetime import datetime
def index_view(request): def index_view(request):
...@@ -10,20 +13,53 @@ def article_create_view(request): ...@@ -10,20 +13,53 @@ def article_create_view(request):
if request.method == 'GET': if request.method == 'GET':
return render(request, 'article/create.html') return render(request, 'article/create.html')
elif request.method == 'POST': elif request.method == 'POST':
publication_date = datetime.strptime(request.POST.get("publication_date"), "%Y-%m-%dT%H:%M")
now_time = datetime.now()
if publication_date < datetime.now():
return render(request, 'article/create.html', context={
"error_message": f"Дата публикации ({publication_date}) не должна быть раньше текущей {now_time}"})
new_article = Article.objects.create( new_article = Article.objects.create(
title=request.POST.get('title'), title=request.POST.get('title'),
content=request.POST.get('content'), content=request.POST.get('content'),
author=request.POST.get('author') author=request.POST.get('author'),
publication_date=publication_date
) )
new_article.save() new_article.save()
articles_list = Article.objects.all() return redirect('article_detail', pk=new_article.pk)
return render(request, 'article/list.html', context={
'articles': articles_list
}) def article_detail_view(request, *args, **kwargs):
try:
article = Article.objects.get(pk=kwargs.get('pk'))
except Article.DoesNotExist as e:
return HttpResponseNotFound(f'Статья с id {kwargs.get("pk")} не найдена')
return render(request, 'article/detail.html', context={'article': article})
def article_update_view(request, pk):
article = Article.objects.get(pk=pk)
if request.method == 'GET':
publication_date_format = article.publication_date
article.publication_date = publication_date_format.strftime('%Y-%m-%dT%H:%M')
return render(request, 'article/update.html', context={'article': article})
if request.method == 'POST':
publication_date = datetime.strptime(request.POST.get("publication_date"), "%Y-%m-%dT%H:%M")
now_time = datetime.now()
if publication_date < datetime.now():
return render(request, 'article/update.html', context={
"error_message": f"Дата публикации ({publication_date}) не должна быть раньше текущей {now_time}"})
article.title = request.POST.get('title'),
print(request.POST.get('title'))
article.content = request.POST.get('content'),
article.author = request.POST.get('author'),
article.publication_date = publication_date
article.save()
return redirect('article_detail', pk=article.pk)
def article_list_view(request): def article_list_view(request):
articles_list = Article.objects.all()
return render(request, 'article/list.html', context={ return render(request, 'article/list.html', context={
'articles': articles_list 'articles': Article.objects.all()
}) })
...@@ -19,6 +19,6 @@ from article.views import index_view ...@@ -19,6 +19,6 @@ from article.views import index_view
urlpatterns = [ urlpatterns = [
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
path('articles/', include('article.urls')), path('aricles/', include('article.urls')),
path('', index_view) path('', index_view, name='index_view')
] ]
...@@ -3,6 +3,11 @@ ...@@ -3,6 +3,11 @@
{% block content %} {% block content %}
<div class="row"> <div class="row">
<div class="col-md-6"> <div class="col-md-6">
{% if error_message %}
<div class="alert alert-danger" role="alert">
{{ error_message }}
</div>
{% endif %}
<form action="{% url 'add_article' %}" method="post"> <form action="{% url 'add_article' %}" method="post">
{% csrf_token %} {% csrf_token %}
<div class="mb-3"> <div class="mb-3">
...@@ -17,6 +22,10 @@ ...@@ -17,6 +22,10 @@
<label for="author_input" class="form-label">Author</label> <label for="author_input" class="form-label">Author</label>
<input type="text" name="author" class="form-control" id="author_input" placeholder="Автор..."> <input type="text" name="author" class="form-control" id="author_input" placeholder="Автор...">
</div> </div>
<div class="mb-3">
<label for="publication_date_input" class="form-label">Дата публикации</label>
<input type="datetime-local" name="publication_date" class="form-control" id="publication_date_input" placeholder="Дата публикации...">
</div>
<button type="submit" class="btn btn-success">Create</button> <button type="submit" class="btn btn-success">Create</button>
</form> </form>
</div> </div>
......
{% extends 'base.html' %} {% extends 'base.html' %}
{% block content %} {% block content %}
<h4>{{ message }}</h4>
<div class="row"> <div class="row">
<div class="col-md-6"> <div class="col-md-6">
<h2>Статья</h2> <h2>Статья</h2>
<p>{{ article.title }}</p> <p>{{ article.title }}</p>
<p>{{ article.author }}</p> <p>{{ article.author }}</p>
<p>{{ article.content }}</p> <p>{{ article.content }}</p>
<a href="{% url 'article_update' article.pk %}" type="button" class="btn btn-warning">Редактировать статью</a>
</div> </div>
</div> </div>
{% endblock %} {% endblock %}
\ No newline at end of file
...@@ -3,11 +3,12 @@ ...@@ -3,11 +3,12 @@
{% block content %} {% block content %}
<div class="row"> <div class="row">
<div class="col-md-6"> <div class="col-md-6">
<ul> <div class="list-group">
{% for article in articles %} {% for article in articles %}
<li>{{ article }}</li> <a href="{% url 'article_detail' article.id %}" class="list-group-item list-group-item-action">{{ article }}</a>
{% endfor %} {% endfor %}
</ul> </div>
</div> </div>
</div> </div>
<a href="{% url 'add_article' %}" class="btn btn-info">Add New Article</a>
{% endblock %} {% endblock %}
{% extends 'base.html' %}
{% block content %}
<div class="row">
<div class="col-md-6">
{% if error_message %}
<div class="alert alert-danger" role="alert">
{{ error_message }}
</div>
{% endif %}
<form action="{% url 'article_update' article.pk %}" method="post">
{% csrf_token %}
<div class="mb-3">
<label for="title_input" class="form-label">Title</label>
<input type="text" name="title" class="form-control" id="title_input" value="{{ article.title }}" placeholder="Название...">
</div>
<div class="mb-3">
<label for="content_input" class="form-label">Content</label>
<textarea name="content" class="form-control" id="content_input" placeholder="Текст...">
{{ article.content }}
</textarea>
</div>
<div class="mb-3">
<label for="author_input" class="form-label">Author</label>
<input type="text" name="author" class="form-control" value="{{ article.author }}" id="author_input" placeholder="Автор...">
</div>
<div class="mb-3">
<label for="publication_date_input" class="form-label">Дата публикации</label>
<input type="datetime-local" name="publication_date" class="form-control" value="{{ article.publication_date }}" id="publication_date_input" placeholder="Дата публикации...">
</div>
<button type="submit" class="btn btn-success">Create</button>
</form>
</div>
</div>
{% endblock %}
\ No newline at end of file
...@@ -13,23 +13,17 @@ ...@@ -13,23 +13,17 @@
<body> <body>
<nav class="navbar navbar-expand-lg navbar-light bg-light"> <nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid"> <div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a> <a class="navbar-brand" href="{% url 'index_view' %}">My Blog</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"> <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> <span class="navbar-toggler-icon"></span>
</button> </button>
<div class="collapse navbar-collapse" id="navbarNav"> <div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav"> <ul class="navbar-nav">
<li class="nav-item"> <li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a> <a class="nav-link" href="{% url 'article_list' %}">Articles</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href="#">Features</a> <a class="nav-link" href="{% url 'add_article' %}">Add New Article</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li> </li>
</ul> </ul>
</div> </div>
......
<!doctype html> {% extends 'base.html' %}
<html lang="en"> {% block content %}
<head> <h1>
<meta charset="UTF-8"> Мой блог
<meta name="viewport" </h1>
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> {% if False %}
<meta http-equiv="X-UA-Compatible" content="ie=edge"> а
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> {% elif False %}
<title>Document</title> b
</head> {% else %}
<body> с
<a href="{% url 'add_article' %}" class="btn btn-success">Add Article</a> {% endif %}
</body> {% endblock %}
</html> \ No newline at end of file
\ No newline at end of file
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