Добрый вечер у меня есть приложение motiv с бд и мне нужно вывести данные на стр шаблона, но почему-то когда я пишу блок for ... forend это место вообще не отображается. Подскажите что делать. Заранее спасибо Python/Django 3.0
views.py
from django.shortcuts import render
from django.http import Http404, HttpResponseRedirect
from django.urls import reverse
from . models import Motiv
def motiv(request):
motiv = Motiv.objects.order_by('-pub_date')[:1]
return render(request, "firstapp/motiv.html", {'motiv':motiv})
def Motiv_Detail(request, article_id):
try:
m = Motiv.objects.get( id = motiv_id )
except:
raise Http404("Статья не найдена!!!")
return render(request, 'firstapp/detail.html', {'motivation':m})
models.py
import datetime
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from django.core import serializers
class Motiv(models.Model):
motiv_title = models.CharField('Название поста', max_length = 120)
motiv_text = models.TextField('Текст поста')
views = models.IntegerField('Просмотры', default=0)
img = models.ImageField(null = True, blank=True, upload_to='Motiv', help_text='150x150px', verbose_name='Изображение')
pub_date = models.DateTimeField('Дата публикации', auto_now_add = True)
def __str__(self):
return self.motiv_title
def was_published_recently(self):
return self.pub_date >= (timezone.now() - datetime.timedelta(days = 7))
class Meta:
verbose_name = 'Мотивация'
verbose_name_plural = 'Мотивация'
ordering = ["-id"]
urls.py (в приложение)
from django.urls import path, include
from . import views
app_name = 'motiv'
urlpatterns = [
path('home/motiv/', views.motiv, name='motiv'),
path('home/motiv/<int:motiv_id>/<int:img_id>/', views.Motiv_Detail, name='Motiv_Detail'),
]
motiv.html
{% block content %}
<div class="high-title-text" id="font-face">
<p>Our Motivation</p>
</div>
<!------------ CONTENT -------------->
{% if motiv %}
{% for a in motiv %}
<div class="motiv-content">
<p>{{ a.pub_date }}</p>
<a href=""><p>{{ a.motiv_title }}</p></a>
<a href=""><img class="motiv-img-content" src="{{ a.img.url }}"></a>
<div class="motiv-content-text">
<a href="{% url 'motiv:list' %}"><p>{{ a.motiv_text }}</p></a>
</div>
</div>
{% endfor %}
{% else %}
Статьи не найдены =(
{% endif %}
{% endblock %}
settings.py
import os, sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, 'firstapp'))
SECRET_KEY = 'Shalom'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'grappelli',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'articles',
'learn',
'motiv',
]
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 = 'hello.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(PROJECT_ROOT, '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',
'django.template.context_processors.request',
'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'hello.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/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.0/topics/i18n/
LANGUAGE_CODE = 'ru-ru'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
MEDIA_ROOT = os.path.join(PROJECT_ROOT,'media')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, "static"),
]
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
motiv
) переопределять переменную с таким же именем.