news_home.py
{% extends 'main/layout.html' %}
{% block title %}Новости на сайте{{ title }}{% endblock %}
{% block content %}
<div class="features">
<h1> Новости на сайте </h1>
{% if news %}
{% for el in news %}
<div class="alert alert-warning">
<h3>{{ el.title }}</h3>
<p>{{ el.anons }}</p>
</div>
{% endfor %}
{% else %}
<p>У вас нету записей!</p>
{% endif %}
{# Комментарий #}
</div>
{% endblock %}
views.py
from django.shortcuts import render, redirect
from .models import Articles
from .forms import ArticlesForm
def news_home(request):
news = Articles.objects.order_by('-date')
return render(request, 'news/news_home.html', {'news': news})
def create(request):
error = ''
if request.method == 'POST':
form = ArticlesForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
error = 'Форма была не верна'
form = ArticlesForm()
data = {
'form': form,
'error': error
}
return render(request, 'news/create.html', data)
forms.py
from .models import Articles
from django.forms import ModelForm, TextInput, DateTimeInput, Textarea
class ArticlesForm(ModelForm):
class Meta:
model = Articles
fields = ['title', 'anons', 'full_text', 'date']
widgets = {
"title": TextInput(attrs={
'class': 'form-control',
'placeholder': 'Название статьи'
}),
"anons": TextInput(attrs={
'class': 'form-control',
'placeholder': 'Анонс статьи'
}),
"date": DateTimeInput(attrs={
'class': 'form-control',
'placeholder': 'Дата публикации'
}),
"full_text": Textarea(attrs={
'class': 'form-control',
'placeholder': 'Текст статьи'
})
}