How do you access and display Cloudinary uploaded image in Django template - python

Using
Framework: Django 1.9
Language: Python 3.4
Development Server: Django
OS: Windows 10
I am still a relative newbie to creating websites. I've been using django to learn. Now, I have run into a problem involving Cloudinary. I have a template that needs to retrieve and display an image from Cloudinary. However, when I use the Cloudinary template tag, displays the image url, but not the image. I need to display the image.
Can someone please help?
Models:
from django.db import models
from cloudinary.models import CloudinaryField
from django.core.urlresolvers import reverse
class PostQuerySet(models.QuerySet):
def published(self):
return self.filter(publish=True)
class HeroImage(models.Model):
image = CloudinaryField('image')
title = models.CharField(max_length=200, default='')
def __str__(self):
return self.title
class Tag(models.Model):
slug = models.SlugField(max_length=200, unique=True)
def __str__(self):
return self.slug
class Post(models.Model):
STATUS_CHOICES = (
('d', 'Draft'),
('c', 'Complete'),
('r', 'Review'),
('p', 'Published'),
('w', 'Withdrawn'),
)
FACEBOOK_CHOICES = (
('web', 'website'),
('art', 'article'),
('blg', 'blog'),
('vid', 'video'),
('aud', 'audio'),
)
hero_image = models.ForeignKey(HeroImage)
tag = models.ManyToManyField(Tag)
featured_image = CloudinaryField('image', default='')
page_title = models.CharField(max_length=70, default='')
page_description = models.CharField(max_length=155, default='')
canonical = models.URLField(default='')
situation = models.TextField()
breakdown = models.TextField()
review = models.TextField()
slug = models.SlugField(max_length=200, unique=True, default='')
publish = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='')
og_title = models.CharField(max_length=88, default='')
og_type = models.CharField(max_length=3, choices=FACEBOOK_CHOICES, default='')
og_description = models.CharField(max_length=200, default='')
og_url = models.URLField(default='')
objects = PostQuerySet.as_manager()
def __str__(self):
return self.page_title
def get_absolute_url(self):
return reverse("post_detail", kwargs={"slug": self.slug})
class Meta:
verbose_name = "Post"
verbose_name_plural = "Posts"
ordering = ["-created"]
Views:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from django import forms
from django.http import HttpResponse
from cloudinary.forms import cl_init_js_callbacks
from . import models
class PostIndex(generic.ListView):
queryset = models.Post.objects.published()
template_name = 'index.html'
class PostDetail(generic.DetailView):
model = models.Post
template_name = "post.html"
Templates:
index.html
{% block blog_posts %}
{% for object in object_list %}
{% load cloudinary %}
<div class="post">
<h2>{{ object.page_title }}</h2>
{% cloudinary "shq7cw9kjufj8zhj1rni.png" %}
<p class="meta">{{ object.created }}</p>
{{ object.situation }}
</div>
{% endfor %}
{% endblock %}
post.html
<div class="post">
<h2>{{ object.title }}</h2>
<p class="meta">
{{ object.created }} | Tagged under {{ object.tags.all|join:", " }}
</p>
<div>
{{ object.situation }}
</div>
<div>
{{ object.breakdown }}
</div>
<div>
{{ object.review }}
</div>
</div>

You can try clicking on the link to see weather it takes you that image or not. Or check for the name that the image is saved with, sometimes they differ.
This site has detailed instructions http://cloudinary.com/documentation/django_integration

Related

Django version 3.1.3 form not saving to model

I am following this tutorial
I have gone back and written the code to match exactly. I have another form that works called category_add which is exactly the same as this form. But for the life of me I cannot figure out why bookmark_add doesn't update the database with the form entries.
Models.py
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
title = models.CharField(max_length=255)
description = models.TextField(blank=True, null=True)
created_by = models.ForeignKey(User, related_name='categories', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'Categories'
def __str__(self):
return self.title
class Bookmark(models.Model):
category = models.ForeignKey(Category, related_name='bookmarks', on_delete=models.CASCADE)
title = models.CharField(max_length=255)
description = models.TextField(blank=True, null=True)
url = models.CharField(max_length=255, blank=True)
created_by = models.ForeignKey(User, related_name='bookmarks', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
View.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .forms import BookmarkForm
#login_required
def bookmark_add(request, category_id):
if request.method == 'POST':
form = BookmarkForm(request.POST)
if form.is_valid():
bookmark = form.save(commit=False)
bookmark.created_by = request.user
bookmark.category_id = category_id
bookmark.save()
return redirect('category', category_id=category_id)
else:
form = BookmarkForm()
context = {
'form': form
}
return render(request, 'bookmark/bookmark_add.html', context)
Forms.py
from django.forms import ModelForm
from .models import Bookmark
class BookmarkForm(ModelForm):
class Meta:
model = Bookmark
fields = ['title', 'description', 'url']
Urls.py
path('', dashboard, name='dashboard'),
path('categories/', categories, name='categories'),
path('categories/add/', category_add, name='category_add'),
path('categories/<int:category_id>/', category, name='category'),
path('categories/<int:category_id>/add_bookmark', bookmark_add, name='bookmark_add')
]
bookmark_add.html
{% extends 'core/base.html' %}
{% block content %}
<div class="container">
<h1 class="title">Add link</h1>
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="button is-primary">Submit</button>
</form>
</div>
{% endblock %}
Solved this!
This was a dumb issue and an oversight on my end. Thanks to the content creator on youtube. I just needed to append "/" to the url path for add_bookmark.
Problem:
path('categories/<int:category_id>/add_bookmark', bookmark_add, name='bookmark_add')
The Fix:
path('categories/<int:category_id>/add_bookmark/', bookmark_add, name='bookmark_add')

'Category' object has no attribute 'post_set'

so I am trying to add a category system for posts by following a tutorial on this website https://djangopy.org/how-to/how-to-implement-categories-in-django/ (I changed my code up a little)
Everything works like creating categories, adding a post, viewing a post, but if I try to go to the category page to view posts only in that category so /category/CATNAME but it shows me this error
'Category' object has no attribute 'post_set'
models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils.text import slugify
from markdownx.models import MarkdownxField
from markdownx.utils import markdownify
from taggit.managers import TaggableManager
class Category(models.Model):
name = models.CharField(max_length=100)
short_desc = models.CharField(max_length=160)
slug = models.SlugField()
parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE)
class Meta:
unique_together = ('slug', 'parent',)
verbose_name_plural = "Categories"
def __str__(self):
full_path = [self.name]
k = self.parent
while k is not None:
full_path.append(k.name)
k = k.parent
return ' -> '.join(full_path[::-1])
def save(self, *args, **kwargs):
value = self.title
self.slug = slugify(value, allow_unicode=True)
super().save(*args, **kwargs)
class Thread(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=150)
content = MarkdownxField()
tags = TaggableManager()
slug = models.SlugField(unique=True)
category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
class Meta:
verbose_name_plural = 'Threads'
def get_cat_list(self):
k = self.category
breadcrumb = ["dummy"]
while k is not None:
breadcrumb.append(k.slug)
k = k.parent
for i in range(len(breadcrumb)-1):
breadcrumb[i] = '/'.join(breadcrumb[-1:i-1:-1])
return breadcrumb[-1:0:-1]
def save(self, *args, **kwargs):
value = self.title
self.slug = slugify(value, allow_unicode=True)
super().save(*args, **kwargs)
views.py
from django.shortcuts import render, redirect, get_object_or_404
from .models import Category, Thread
from .forms import NewThreadForm
def show_thread_view(request, hierarchy=None):
category_slug = hierarchy.split('/')
category_queryset = list(Category.objects.all())
all_slugs = [ x.slug for x in category_queryset ]
for slug in category_slug:
if slug in all_slugs:
# parent = get_object_or_404(Category, slug=slug, parent=parent)
parent = Category.objects.filter(slug__in=category_slug, parent=None).first()
thread = get_object_or_404(Thread, slug=slug)
instance = get_object_or_404(Thread, slug=slug)
breadcrumbs_link = instance.get_cat_list()
category_name = [' '.join(i.split('/')[-1].split('-')) for i in breadcrumbs_link]
breadcrumbs = zip(breadcrumbs_link, category_name)
context = {
'thread': thread,
'instance': instance,
'breadcrumbs': breadcrumbs,
}
return render(request, "forums/threads/thread_detail.html", context)
def show_category_view(request, hierarchy=None):
category_slug = hierarchy.split('/')
category_queryset = list(Category.objects.all())
all_slugs = [ x.slug for x in category_queryset ]
parent = None
for slug in category_slug:
if slug in all_slugs:
#parent = get_object_or_404(Category, slug=slug, parent=parent)
parent = Category.objects.filter(slug__in=category_slug, parent=None).first()
context = {
'category': parent,
'post_set': parent.post_set.all(),
'sub_categories': parent.children.all(),
}
return render(request, "forums/categories.html", context)
def new_thread_form_view(request):
if request.method == "POST":
form_data = request.POST or None
form = NewThreadForm(form_data)
if form.is_valid():
news = form.save(commit=False)
news.author = request.user
news.save()
return redirect('/forums')
else:
form = NewThreadForm()
context = {
'form': form
}
return render(request, "forums/threads/thread_form.html", context)
categories.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<br>
{% if sub_categories %}
<h3>Sub Categories</h3>
{% for i in sub_categories %}
{{ i.name }}
{% endfor %}
{% endif %}
<div class="row small-up-1 medium-up-3" >
{% if post_set %}
{% for i in post_set %}
<div class="columns">
<div class=" card-article-hover card">
<a href="{{ i.slug }}">
<img src="{{ i.cover_photo.url }}">
</a>
<div class="card-section">
<a href="{{ i.slug }}">
<h6 class="article-title">{{ i.title | truncatechars:30}}</h6>
</a>
</div>
<div class="card-divider flex-container align-middle">
{{ i.user.get_full_name }}
</div>
<div class="hover-border">
</div>
</div>
</div>
{% endfor %}
{% endif %}
</div>
{% endblock %}
The model which has ForeignKey relation to Category model is Thread(as per shared code from the question). So you need to use parent.thread_set.all() to get all the threads related to that category. Also if you define related_name inside Thread to Category ForeignKey like following example:
class Thread(..):
category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE, related_name='threads')
Then you can get the threads by parent.threads.all(). More information can be found in documentation.

can't find data in django

I have some questions about django orm with mysql.
This is my models.py
from django.db import models
#电影列表
class Movieinfo(models.Model):
movienum = models.IntegerField(primary_key=True)
moviename = models.CharField(max_length=100)
movierelease_time = models.CharField(max_length=20)
movietype = models.CharField(max_length=100)
class Meta:
ordering = ["movienum"]
def __str__(self):
return self.moviename
#短评论
class Moviescritic(models.Model):
movieinfo = models.ForeignKey(Movieinfo)
movienum = models.IntegerField()
moviescrit= models.TextField()
class Meta:
ordering = ["movienum"]
def __str__(self):
return self.moviescrit
#长影评
class Movielcritic(models.Model):
movieinfo = models.ForeignKey(Movieinfo)
movienum = models.IntegerField()
movielcrittitle = models.TextField()
movielcrit = models.TextField()
class Meta:
ordering = ["movienum"]
def __str__(self):
return self.movielcrit
This is my views.py
import logging
from django.http import HttpResponse
from django.views.generic import DetailView
from django.template import loader
from yingping.models import Moviescritic
logger = logging.getLogger('__name__')
def cdview(request):
template = loader.get_template('worldcloud.html')
movie_shu = Moviescritic.objects.filter(
movieinfo__movienum='10014'
)
content = {
'movie_shu':movie_shu,
}
return HttpResponse(template.render(content,request))
But I can't find any data in html, is my understanding of django onetomany wrong?
{% block worldcloud %}
{% if movie_shu %}
{% for x in movie_shu %}
<p>{{x}}</p>
{% endfor %}
{% else %}
print("err")
{% endif %}
<!--SERVICES SECTION END -->
{% endblock %}
the html just find print("error"), when i find data in itself table I can find data in HTML. so what's wrong with my code?

Django tree query spanning multi model relation

Please consider code the following code. I'd like to create something like a tree structure (it will be in a table) related to a specific loged-in user. I'd like to have an overviewpage in which all categories are shown for which this user has items in the subcategories. My query works, but gives me all subcategory records and all posible items in those subcategories (so not just the subset for which the user has records.
I have another way working by starting with the itemmodel and then going up in the tree, but thats not what i'm looking for (this makes creating a dynamic set of tables far to depended on the django template layer).
I've looked at select_related and prefetch, but I can't get close to a solution. Any help would be appriciated.
models.py:
from django.db import models
from model_utils.models import TimeStampedModel
from django.conf import settings
User = settings.AUTH_USER_MODEL
class MainCat(TimeStampedModel):
name = models.CharField(max_length=100, unique=True)
rank = models.IntegerField(default=10)
icon_class = models.CharField(max_length=100, null=True, blank=True)
class SubCat(TimeStampedModel):
name = models.CharField(max_length=100, null=False, blank=False)
slug = models.SlugField(null=True, blank=True)
icon_class = models.CharField(max_length=100, null=True, blank=True)
main_cat = models.ForeignKey(MainCat)
class Item(TimeStampedModel):
user = models.ForeignKey(User, blank=True, null=True)
item_name = models.CharField(max_length=100, null=False, blank=False)
sub_cat = models.ForeignKey(SubCat, blank=True, null=True)
views.py:
from django.views.generic import ListView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import MainCat
class MainCatByUserListView(LoginRequiredMixin, ListView):
model = MainCat
def get_queryset(self):
qs = super(MainCatByUserListView, self).get_queryset()
qs = qs.filter(subcat__item__user=self.request.user)
return qs
template:
< html >
< body >
{% for maincat in object_list %}
< ul >
<li> {{maincat.name}} </li>
<ul>
{% for subcat in maincat.subcat_set.all %}
<li> {{subcat.name}} </li>
{% for item in subcat.item_set.all %}
<li> {{item.name}} </li>
</ul>
</ul>
{% endfor %}
{% endfor %}
{% endfor %}
< / body >
< / html >
{% endfor %}
You should be able to use something like: Subcat.objects.filter(item_set__user=self.request.user).select_related('main_cat')
Finaly got to an answer to my question. For future reference:
class MainCatListView(LoginRequiredMixin, ListView):
model = MainCat
template_name = 'app/main_cat_overview.html'
def get_queryset(self):
qs = super(MainCatListView, self).get_queryset()
qs_user_cat_set = SubCat.objects.filter(item__user=self.request.user).prefetch_related(Prefetch(
"item_set",
queryset=Item.objects.filter(user=self.request.user),
to_attr="item_attr")
).distinct()
qs = qs.filter(subcat__item__user=self.request.user).prefetch_related(Prefetch(
"subcat_set",
queryset=qs_user_subcat_set,
to_attr="subcat_attr")
).distinct()
return qs

Can I use filter() in django template?

What I'd like to do is using filter() in django template like belows:
models.py
from django.db import models
From Django. utils import Timezone
class Category(models.Model):
url = models.CharField(max_length=200)
site_name = models.CharField(max_length=50)
board_name = models.CharField(max_length=50)
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField(blank=True)
category = models.ForeignKey(Category)
created_date = models.DateField(blank=True, null=True)
crawl_date = models.DateTimeField()
num_of_comments = models.PositiveSmallIntegerField(default=0, blank=True, null=True)
notice = models.BooleanField(default=False)
views.py
def post_list(request, site_name=None, page=1):
categories = Category.objects.filter(site_name=site_name.upper()).order_by('board_name')
return render(request, 'SNU/post_list.html', {'site_name':site_name.upper(), 'categories':categories})
post_list.html
{% for category in categories %}
<p> {{category}} </p>
{% for post in category.post_set.filter(notice=True) %}
<li>{{ post.title }}</li>
{% endfor %}
{% endfor %}
In post_list.html, {% for post in category.post_set.filter(notice=True) %} occurs error. Only category.post_set.all is the one that I can use in template?
You can do it on view level by
def post_list(request, site_name=None, page=1):
categories = Category.objects.filter(site_name=site_name.upper(),
notice=True).order_by('board_name')
return render(request, 'SNU/post_list.html',{'site_name':site_name.upper(),
'categories':categories})
If for some reason you need all categories, not just those having notice = True,
add one more query without notice=True in filter and pass it in the dictionary.
Alternatively, you can create custom tag and provide filter - see https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/

Categories