Видео
Исходный код
views.py
from django.shortcuts import render,redirect from .models import Articles from django.views.generic import ListView, DetailView from .forms import ArticleForm from django.urls import reverse class HomeListView(ListView): model = Articles template_name = 'index.html' context_object_name = 'list_articles' class HomeDetailView(DetailView): model = Articles template_name = 'detail.html' context_object_name = 'get_article' def edit_page(request): success = False if request.method == 'POST': form = ArticleForm(request.POST) if form.is_valid(): form.save() success = True template = 'edit_page.html' context = { 'list_articles': Articles.objects.all().order_by('-id'), 'form':ArticleForm(), 'success':success } return render(request,template,context) def update_page(request,pk): success_update = False get_article = Articles.objects.get(pk=pk) if request.method == 'POST': form = ArticleForm(request.POST,instance = get_article) if form.is_valid(): form.save() success_update = True template = 'edit_page.html' context = { 'get_article': get_article, 'update':True, 'form':ArticleForm(instance = get_article), 'success_update':success_update } return render(request, template, context) def delete_page(request,pk): get_article = Articles.objects.get(pk=pk) get_article.delete() return redirect(reverse('edit_page'))
urls.py
from django.contrib import admin from django.urls import path from core import views urlpatterns = [ path('', views.HomeListView.as_view(), name='home'), path('detail/', views.HomeDetailView.as_view(), name='detail_page'), path('edit-page', views.edit_page, name='edit_page'), path('update-page/', views.update_page, name='update_page'), path('delete-page/', views.delete_page, name='delete_page'), ]
forms.py
from django import forms from .models import Articles class ArticleForm(forms.ModelForm): class Meta: model = Articles fields = '__all__' def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control'
шаблон index.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"><title>Hello, world!</title>
</head>
<body>
<div class="container mt-4">
<ul class="nav nav-pills">
<li class="nav-item">
{% url 'home' as url_home %}
<a class="nav-link {% if url_home == request.path %}active{% endif %}" href="{{url_home}}">Главная</a>
</li>
<li class="nav-item">
{% url 'edit_page' as url_edit_page %}
<a class="nav-link {% if url_edit_page == request.path %}active{% endif %}" href="{{url_edit_page}}">Создание/ред/удал</a>
</li></ul>
{% block content %}
<h1 class="mt-4">Hello, world!</h1>
{% for i in list_articles %}
<ul class="list-group mt-4">
<li class="list-group-item">
<b>{{i.create_date}}</b>
<span class="m-2">{{i.name}}</span>
<span>{{i.text|truncatechars:"5"}}</span>
<span class="float-right mr-3"><a href="/detail/{{i.id}}">перейти к статье</a></span>
</li>
</ul>{% endfor %}
{% endblock %}
</div><!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
Шаблон detail.html
{% extends 'index.html' %}
{% block content %}
<h1 class="mt-4">Статья: {{get_article.name}}</h1>
<p><a href="/">Вернуться назад</a></p>
<p>Дата создания: {{get_article.create_date}}</p>
<p>Название: {{get_article.name}}</p>
<p>Текст: {{get_article.text}}</p>
{% endblock %}
Шаблон edit_page.html
{% extends 'index.html' %}
{% block content %}
<h1 class="mt-4">Админ панель</h1>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Добавить новую статью
</button>
{% if success %}
<p style="color:red">Запись добавлена</p>
{% endif %}
{% if update %}
{% if success_update %}
<p style="color:red">Запись обновлена</p>
{% endif %}
<p class="mt-4">Страница редактирования</p>
<p><a href="{% url 'edit_page' %}">Вернуться назад</a></p>
<form id="update_data" method="post">
{% csrf_token %}
{{form}}
</form>
<button form="update_data" type="submit" class="btn btn-primary">Обновить</button>
{% else %}
<table class="table table-bordered mt-4">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">Дата создания</th>
<th scope="col">Название</th>
<th scope="col">Редактирование</th>
<th scope="col">Удаление</th>
</tr>
</thead>
<tbody>
{% for i in list_articles %}
<tr>
<th>{{i.id}}</th>
<td>{{i.create_date}}</td>
<td>{{i.name}}</td>
<td><a href="{% url 'update_page' i.id %}">редактировать</a></td>
<td><a href="{% url 'delete_page' i.id %}">удалить</a></td>
</tr>
{% endfor %}</tbody>
</table>{% endif %}
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="add_form" method="post">
{% csrf_token %}
{{form}}
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">закрыть</button>
<button form="add_form" type="submit" class="btn btn-primary">Добавить</button>
</div>
</div>
</div>
</div>
{% endblock %}