urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='home'),
path('about-us', views.about, name='about'),
path('create', views.create, name='create')
]
views.py
from django.shortcuts import render, redirect
from .models import Task
from .forms import TaskForm
def index(request):
tasks = Task.objects.order_by('id')[:5]
return render(request, 'main/index.html', {'title': 'Главная страница сайта', 'tasks': tasks})
def about(request):
return render(request, 'main/about.html')
def create(request):
error = ''
if request.method =="POST":
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
error = 'Форма была неверной'
form = TaskForm()
context = {
'form': form,
'error': error
}
return render(request, 'main/create.html')
forms.py
from .models import Task
from django.forms import ModelForm, TextInput, Textarea
class TaskForm(ModelForm):
class Meta:
model = Task
fields = ["title", "task"]
widgets = {
"title": TextInput(attrs={
'placeholder': 'Введите название',
'class': 'form-control'
}),
"task": Textarea(attrs={
'class': 'form-control',
'placeholder': 'Введите описание'
}),
}
index.html
{% extends 'main/base.html' %}
{% block title %}
{{ title }}
{% endblock %}
{% block content %}
<h1>Главная страница</h1>
{% if tasks %}
{% for el in tasks %}
<div class="alert alert-warning mt-2">
<h3>{{ el.title }}</h3>
<p>{{ el.task }}</p>
</div>
{% endfor %}
{% else %}
<p>У нас нет записей!</p>
{% endif %}
{% endblock %}
create.html (сам html шаблон)
{% extends 'main/base.html' %}
{% block title %}
Придумать задание
{% endblock %}
{% block content %}
<h1>Придумать задание</h1>
<form method="post">
{% csrf_token %}
{{ form.title }}
{{ form.task }}
<button type="submit" class="btn btn-success">Добавить</button>
<span>{{ error }}</span>
</form>
{% endblock %}