NoReverseMatch error Django with slug - django

I'm trying to make the index view show a list of "Journal"s, with each linking to a view that lists "Manuscripts" in the Journal. I also want journal_view to be located at a slug for the name of the journal, and likewise for manuscript_view.
This is the traceback I get:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/journals/
Django Version: 2.0.3
Python Version: 3.6.4
Installed Applications:
['social_django',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'journal.apps.JournalConfig']
Installed 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']
Template error:
In template ... error at line 8
Reverse for 'view_journal' not found. 'view_journal' is not a valid view function or pattern name.
1 : {% load static %}
2 :
3 : <link rel="stylesheet" type="text/css" href="{% static 'journal/style.css' %}" />
4 :
5 : {% if journal_list %}
6 : <ul>
7 : {% for journal in journal_list %}
8 : <li>{{ journal.title }}</li>
9 : {% endfor %}
10 : </ul>
11 : {% else %}
12 : <p>No journals are available.</p>
13 : {% endif %}
# ...(Traceback)...
Exception Type: NoReverseMatch at /journals/
Exception Value: Reverse for 'view_journal' not found. 'view_journal' is not a valid view function or pattern name.
The Journal model looks like this:
class Journal(models.Model):
title = models.CharField(max_length=100, unique=True)
slug = models.SlugField(unique=True)
# blah blah
def __str__(self):
return self.title
def get_absolute_url(self, *args, **kwargs):
return reverse("view_journal", kwargs={"slug": self.slug})
My views look like this:
class IndexView(generic.ListView):
template_name = 'journal/index.html'
context_object_name = 'journal_list'
def get_queryset(self):
return Journal.objects.all()
class JournalView(generic.ListView):
template_name = 'journal/journal.html'
context_object_name = 'latest_article_list'
def get_queryset(self):
return Manuscript.objects.filter(
pub_date__lte=timezone.now()
).order_by('-pub_date')[:5]
My app urls look like this:
app_name = 'journal'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<slug>/', views.JournalView.as_view(), name='view_journal'),
path('<slug>/', views.ArticleView.as_view(), name='view_manuscript'), ]
Project urls:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('journals/', include('journal.urls')),
path('social/', include('social.apps.django_app.urls', namespace='social')),
]

I had it working this way:
I defined a slug field in my model first, as you did too:
slug = models.SlugField(max_length=20, unique=True)
then in my views.py I did add this:
slug_url_kwarg = 'slug'
and finally wrote my path this way:
path('<slug:slug>/', MyView.as_view(), name='myview')

Related

Using Django Template Tags in Markdown

I am using Markdown to format/style my blog posts in Django. The problem is that the Django template tags in Markdown don't seem to work for me.
More details:
Markdown module: Markdown==3.2.1
details.html (my blog posts template file)
{% block content %}
...
</p>
{{ post.body|markdown }}
<p>
...
{% endblock %}
Next, in the body of my blog post, I tried to add an HTML tag that includes a django template tag:
<img src="{% static '/img/image.jpg' %}" alt="image">
and I see this in the result:
Other details:
views.py
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
# List of active comments for this post
comments = post.comments.filter(active=True)
new_comment = None
if request.method == 'POST':
# A comment was posted
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# create comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# assign the current post to the comment
new_comment.post = post
# save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.postgres',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.sitemaps',
'blog.apps.BlogConfig',
'main.apps.MainConfig',
"crispy_forms",
"crispy_bootstrap5",
'taggit',
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
Any ideas what I'm doing wrong?
I converted the Django tag to HTML and it worked.
What I tried and didn't work in my Markdown:
<img src="{% static '/img/my_images/flower.jpg' %}">
What I tried and worked in Markdown:
<img src="/static/img/my_images/flower.jpg' %}">
The 'static' folder is in another App. It seems that Django HTML code is smart enough to trace the folder based on my settings.py instructions.

django1.8, I try to get current logined username. in template got work but in view I got failed [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm quite new in django 1.8.
Now, I'm trying to get current logined username.
I wanna do this. When I post some articles it's author automatically saved to database and displayed in template table.
I already know about
from django.contrib.auth.models import User
and request.user.get_username()
and read lots of articles and QNA about this subject and various tries in two days. But I never find why I only can get username in template but not in view.
I did belows
python manage.py makemigrations BTS(This is name of app)
python manage.py migrate
It works well.
In template, Belows all works well:
{{ user.username }}
{{ request.user.username }}
{{ request.user }}
In views.py I use get_username method like this. No error but it's not work.:
form.username = request.user.get_username()
Every other things works fine. But only above one line get anything only empty null value about username, I guess. I need help.
Here is my code. I skip some unnecessary def.
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.utils import timezone
from django.template import RequestContext, loader
from django.shortcuts import redirect
from .models import BTSinput
from .models import BTSreply
from .forms import BTSinputForm
from .forms import BTSreplyForm
from django.contrib.auth.models import User
def inputvalidate(request):
if request.method == 'POST':
form = BTSinputForm(request.POST or None)
if form.is_valid():
hold = form.save(commit=False)
form.created = timezone.now()
form.updated = timezone.now()
form.username = request.user.get_username()
hold.save()
return redirect('/BTS/list/')
else:
form = BTSinputForm()
return render(request,'BTS/input.html',{'inputform':form})
return render(request,'BTS/input.html',{'inputform':form})
input.html
{% block content %}
{% load widget_tweaks %}
<div class="container">
<div class="starter-template">
<form method="post" action="/BTS/inputvalidate/">
{% csrf_token %}
<div class="form-group">
<p>subject</p>
<p>{{inputform.subject|add_class:"form-control"}}</p>
<p>URLS</p>
<p>{{inputform.urls|add_class:"form-control"}}</p>
<p>text</p>
<p>{{inputform.text|add_class:"form-control"}}</p>
<button type="submit" class="btn btn-default">Confirm</button>
<button type="button" class="btn btn-default">To List</button>
</div>
</form>
</div>
</div>
{% endblock%}
models.py
class BTSinput(models.Model):
subject = models.CharField(max_length=100)
username = models.CharField(max_length=30, blank = True)
text = models.TextField()
urls = models.URLField(max_length = 100)
created = models.DateTimeField(default = datetime.datetime.now)
updated = models.DateTimeField(default = datetime.datetime.now)
forms.py
from django import forms
from django.forms import ModelForm
from BTS.models import BTSinput
from BTS.models import BTSreply
# Create your models here.
class BTSinputForm(ModelForm):
class Meta:
model = BTSinput
fields = ['subject','text','urls']
class BTSreplyForm(ModelForm):
class Meta:
model = BTSreply
fields = ['reply']
I checked my setting.py over and over. But... ^^;;;
Here is my setting.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.8.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'n^63(%(va-3wb9l!!2-vg003f)s(3g=%w1*%tv2(8%l)65g&a2'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'QNA',
'BTS',
'accounts',
'widget_tweaks',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'ko-kr'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
Once you have called save with commit=False, you should update the instance, not the form.
if form.is_valid():
hold = form.save(commit=False)
hold.created = timezone.now()
hold.updated = timezone.now()
hold.username = request.user.get_username() # or request.user.username
hold.save()

How to render image in my Django Blog Template?

Hi Guys I have a blog setup and I want to add the ability for an image or thumbnail to be included in every blog post. I'm having trouble getting the location of the file and the blog template to match up and show the image. I'm also having difficulties integrating the ImageWithThumbnail model to the Entry model.
post.html
{% include 'head.html' %}
{% include 'navbar.html' %}
{% load staticfiles %}
{% load django_markdown %}
<div class="container">
<div class="post">
<h2>{{ object.title }}</h2>
<p class="meta">
{{ object.created }} |
Tagged under {{ object.tags.all|join:", " }} <p> Created by
{{ object.author }} </p>
</p>
{{ object.body|markdown }}
<img src="{% static "{{ STATIC_ROOT }}/media/tableau_public.jpg" %}" alt="My image"/>
{{ object.file }}
</div>
{% include 'footer.html' %}
Settings.py
"""
Django settings for vizualytic project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#ic_*)dw$fxp+p_c=3e=91ujzivxurqf7y7572z9&sfs19aek%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_markdown',
'website',
'blog',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'vizualytic.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.dirname(BASE_DIR), "static", "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',
],
},
},
]
WSGI_APPLICATION = 'vizualytic.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media")
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static", "static"),
)
view.py
from django.views import generic
from . import models
class BlogIndex(generic.ListView):
queryset = models.Entry.objects.published()
template_name = "blog.html"
paginate_by = 3
class BlogDetail(generic.DetailView):
model = models.Entry
template_name = "post.html"
models.py
from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings
class Tag(models.Model):
slug = models.SlugField(max_length=200, unique=True)
def __str__(self):
return self.slug
class EntryQuerySet(models.QuerySet):
def published(self):
return self.filter(publish=True)
class Entry(models.Model):
title = models.CharField(max_length=200)
name = models.CharField(max_length = 255)
file = models.ImageField()
thumbnail = models.ImageField(upload_to=settings.MEDIA_ROOT+"/%Y/%m/%d",max_length=500,blank=True,null=True)
author = models.CharField(max_length=200, null=True)
body = models.TextField()
slug = models.SlugField(max_length=200, unique=True)
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(Tag)
objects = EntryQuerySet.as_manager()
def filename(self):
return os.path.basename(self.file.name)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("entry_detail", kwargs={"slug": self.slug})
class Meta:
verbose_name = "Blog Entry"
verbose_name_plural = "Blog Entries"
ordering = ["-created"]
class ImageWithThumbnail(models.Model):
name = models.CharField(max_length = 255)
image = models.ImageField(upload_to="/%Y/%m/%d",max_length=500,blank=True,null=True)
thumbnail = models.ImageField(upload_to="/%Y/%m/%d",max_length=500,blank=True,null=True)
def create_thumbnail(self):
# original code for this method came from
# http://snipt.net/danfreak/generate-thumbnails-in-django-with-pil/
# If there is no image associated with this.
# do not create thumbnail
if not self.image:
return
from PIL import Image
from cStringIO import StringIO
from django.core.files.uploadedfile import SimpleUploadedFile
import os
# Set our max thumbnail size in a tuple (max width, max height)
THUMBNAIL_SIZE = (200,200)
DJANGO_TYPE = self.image.file.content_type
if DJANGO_TYPE == 'image/jpeg':
PIL_TYPE = 'jpeg'
FILE_EXTENSION = 'jpg'
elif DJANGO_TYPE == 'image/png':
PIL_TYPE = 'png'
FILE_EXTENSION = 'png'
# Open original photo which we want to thumbnail using PIL's Image
image = Image.open(StringIO(self.image.read()))
# Convert to RGB if necessary
# Thanks to Limodou on DjangoSnippets.org
# http://www.djangosnippets.org/snippets/20/
#
# I commented this part since it messes up my png files
#
#if image.mode not in ('L', 'RGB'):
# image = image.convert('RGB')
# We use our PIL Image object to create the thumbnail, which already
# has a thumbnail() convenience method that contrains proportions.
# Additionally, we use Image.ANTIALIAS to make the image look better.
# Without antialiasing the image pattern artifacts may result.
image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
# Save the thumbnail
temp_handle = StringIO()
image.save(temp_handle, PIL_TYPE)
temp_handle.seek(0)
# Save image to a SimpleUploadedFile which can be saved into
# ImageField
suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
temp_handle.read(), content_type=DJANGO_TYPE)
# Save SimpleUploadedFile into image field
self.thumbnail.save('%s_thumbnail.%s'%(os.path.splitext(suf.name)[0],FILE_EXTENSION), suf, save=False)
def save(self):
# create a thumbnail
self.create_thumbnail()
super(ImageWithThumbnail, self).save()
Any help would be greatly appreciated.
Thanks
you just need:
<img src="{{ object.thumbnail.url }}" alt="My image"/>
note that the {% static 'file.extension' %} is used only to render static files.
I would suggest to use Django Filer with Easy Thumbnails.
You will only need one image field in your model and leave making the thumbnail to Easy Thumbnails on rendering of the template.

Using image in a template django

I want to view images, in a template, but I don't understand what I'm doing wrong.
models.py
class Item(models.Model):
name = models.CharField(verbose_name = "Название", max_length = 100)
TYPE_ITEMS = (
("shirt", "Футболка"),
("shoes", "Обувь"),
("bags", "Рюкзаки и сумки"),
("heads", "Головные уборы"),
("others", "Другое"),
)
type_item = models.CharField(verbose_name = "Тип продукта",
choices = TYPE_ITEMS, max_length = 6,
default = "shirt")
other = models.CharField("другая информация", max_length = 200)
color = models.CharField("Цвет(а)", max_length = 100)
cost = models.IntegerField("Стоимость за штуку", default = 0)
is_available_now = models.BooleanField("Есть ли в наличии?",
default = False)
available_count = models.IntegerField("Количество в наличии", default = 0)
photo = models.ImageField("Фото", upload_to = "photos/to_trade")
def __str__(self):
return self.name + " " + self.color + " (" + str(self.cost) + " грн)"
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader ####
from myapp.models import Item
def index(request):
return render(request, "index.html")
def goods(request):
shirts_list = Item.objects.filter(type_item = "shirt")
template = loader.get_template("goods.html")
context = RequestContext(request, {
"shirts_list": shirts_list,})
return HttpResponse(template.render(context))
def contacts(request):
return render(request, "contacts.html")
def delivery(request):
return render(request, "delivery.html")
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from myapp import views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'paporotnik.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.index, name = "index"),
url(r'^goods', views.goods, name = "goods"),
url(r'^contacts', views.contacts, name = "contacts"),
url(r'^delivery', views.delivery, name = "delivery"),
url(r'^photos/to_trade/(?P<path>.*)$', 'django.views.static.serve'),
)
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = '(=bk#zukikdq==0dtokjbg-sbgge5zi(^te01+9=w%is-76sxv'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
TEMPLATE_DIRS = [os.path.join(BASE_DIR, "templates")]
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'paporotnik.urls'
WSGI_APPLICATION = 'paporotnik.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = "C:\\Python33\\Scripts\\paporotnik\\static"
This is my template:
{% load staticfiles %}
<!DOCTYPE HTML>
<html>
<head>
<meta charset = "utf-8">
<title>Товары - Paporotnik.ua</title>
<link rel = "stylesheet", type = "text/css", href = "{% static 'myapp/style_index.css' %}">
</head>
<body>
<div id="container">
<!-- Верхняя панель (заголовок) -->
<div id="header">
<div style = "float: left; width:100%">
<div style = "margin: 0 10%;">
<br><h1 id = "heed">Paporotnik.ua</h1><br>
</div>
</div>
<div id = "divLogo">
<img id = "logo", width = "125", height = "125">
</div>
<div id = "trash" align = "center">
<h3>Корзина</h3>
<img align = "center", width = "70", height = "50">
</div>
</div>
<!-- Центр, основное содержимое -->
<div id="wrapper">
<div id="content">
<p align = "center">
<h2 align = "center">Футболки</h2>
<div align = "center">
{% for item in shirts_list %}
<img src = "{{item.photo}}", width = "150", height = "250">
{% endfor %}
</div>
</div>
</div>
</div>
</body>
</html>
When I view the code in a browser, the path is correct:
But when I click on the URL, I see this:
It tells me that my picture doesn't exist, but it is there!
Something that I would like to bring to your notice. static stores your css,js and images that are needed for the website frontend. media stores all the images uploaded by the user. So, in your settings define,
MEDIA_URL = 'media/'
Then, inside your template append /{{MEDIA_URL}} in front of {{item.photo}}.
And in your urls.py file, to the urlpatterns append:
+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This ought to sort the problem.
You are not specifying the URL of the photo correctly. In your template, replace the line
<img src = "{{item.photo}}", width = "150", height = "250">
with
<img src = "{{item.photo.url}}", width = "150", height = "250">
I think you haven't specified a media folder. In your settings.py you need this:
MEDIA_URL = '/media/'
MEDIA_ROOT = join(settings.PROJECT_ROOT, 'media')
And photos/to_trade should be inside this media folder. Also you need to use {{item.photo.url}} in your template instead of {{item.photo}}

NoReverseMatch implementing django-likes

Getting the following error when trying to install django-likes
NoReverseMatch at /post/25/
Reverse for '' with arguments '('posts-post', 25, 1)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Exception Location: /Users/Pete/.virtualenvs/innerlocal-mvp/lib/python2.7/site-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 463
I'm not sure where to even start on this error, I've done a lot of searching, but nothing comes up.
My view that this is referring to:
def single_post(request, id):
post = get_object_or_404(Post, id=id)
...
return render(request, 'posts/single_post.html', locals())
with {% likes post %} in the html.
and this line highlighted from the resulting html:
<a class="liker" href="{% url like content_type content_obj.id 1 %}" rel="nofollow">{% trans "I Like" %}</a>
I'm using Django 1.7 so wouldn't be surprised if that was a problem.
Any help would be greatly appreciated!!
Extra settings as requested:
the urls.py lines (first, the app, second, the django-likes url:
url(r'^', include('posts.urls')),
(r'^likes/', include('likes.urls')),
and the urls.py for the posts app:
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from views import PostDelete
urlpatterns = patterns('posts.views',
# (r'^', 'home'),
url(r'^$', 'all_posts', name='home'),
url(r'^post/(?P<id>\w+)/$', 'single_post', name='single_post'),
url(r'^new-post/$', 'new_post', name='new_post'),
url(r'^search/$', 'search', name='search'),
url(r'^delete/(?P<pk>\d+)/$', PostDelete.as_view(),
name='entry_delete'),
)
Installed apps:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'django.contrib.sites',
....
'secretballot',
'likes',
)
Middleware classes:
MIDDLEWARE_CLASSES = (
'django.middleware.gzip.GZipMiddleware',
'pipeline.middleware.MinifyHTMLMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
'secretballot.middleware.SecretBallotIpMiddleware',
'secretballot.middleware.SecretBallotIpUseragentMiddleware',
'likes.middleware.SecretBallotUserIpUseragentMiddleware',
)
Template context processors:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.request",
"allauth.account.context_processors.account",
"allauth.socialaccount.context_processors.socialaccount",
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.static",
"django.core.context_processors.media",
"django.contrib.messages.context_processors.messages",
)
Turns out that the app code needed a change:
In likes.html
from
<a class="liker" href="{% url like content_type content_obj.id 1 %}" rel="nofollow">{% trans "I Like" %}</a>
to
<a class="liker" href="{% url 'like' content_type content_obj.id 1 %}" rel="nofollow">{% trans "I Like" %}</a>
ie - the quotation marks around 'like'