can't find data in django - python

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?

Related

How to send multiple model from a classbased view in django

I made a booklist where cover image can be uploaded inside Booklist class. For more image I added another class called Bookcover. Now in Views.py how can I send both Booklist and Bookcover's by using BookListView
models.py file is below
from django.db import models
from django.utils import timezone
class Booklist(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length = 100)
cover = models.ImageField(null=True, blank=True, default='default-book.jpg')
description = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
price = models.DecimalField(decimal_places=3, max_digits=100)
def __str__(self):
return self.title
class Bookcover(models.Model):
post = models.ForeignKey(Booklist, default=None, on_delete=models.CASCADE)
covers = models.ImageField(upload_to = 'images/')
def __str__(self):
return self.post.title
here is views.py file
from django.shortcuts import render
from django.views.generic import ListView
from .models import Booklist, Bookcover
def home(request):
return render(request, template_name='home/index.html')
class BookListView(ListView):
model = Booklist
template_name = 'home/index.html'
context_object_name = 'books'
ordering = ['-date_posted']
If you make a ForeignKey, Django automatically will generate a relation in reverse to access - in this case - the related BookCovers for a specific Book. Since you did not specify the related_name=… parameter [Django-doc], the name of this relation is modelname_set, so in this case, bookcover_set.
In the template you can access the book covers of a book with:
{% for book in books %}
{{ book.title }}
{% for cover in book.bookcover_set.all %}
<img src="{{ cover.covers.url }}">
{% endfor %}
{% endfor %}
This will result in an N+1 problem however. You can avoid that by using .prefetch_related(…) [Django-doc]:
class BookListView(ListView):
queryset = Booklist.objects.prefetch_related('bookcover_set')
template_name = 'home/index.html'
context_object_name = 'books'
ordering = ['-date_posted']

dropdown box empty in django when trying to populate values from database

I am new to Django and I was unable to find a fix for this. I am trying to populate a dropdown box with the database values.
Here are my files
models.py file
from django.db import models
# Create your models here.
class Page(models.Model):
title = models.CharField(max_length=60)
permalink = models.CharField(max_length=12, unique=True)
update_date = models.DateTimeField('Last Updated')
bodytext = models.TextField('Page Content', blank=True)
def __str__(self):
return self.title
class Item(models.Model):
itemId = models.AutoField(primary_key=True)
itemName = models.CharField(max_length = 100, unique=True)
itemPrice = models.IntegerField()
def __str__(self):
return self.itemName
forms.py file
from django import forms
from .models import Item
class OrderListForm(forms.Form):
itemNames = forms.queryset = Item.objects.all().order_by('itemName')
urls.py file
from django.urls import path
from . import views
urlpatterns =[
path('',views.OrderListView.as_view(),name ='hello'),
]
views.py file
from django.views.generic.edit import FormView
from .forms import OrderListForm
# Create your views here.
class OrderListView(FormView):
template_name = "myapp/orderlist.html"
form_class = OrderListForm
context_object_name = 'itemNames'
orderlist.html file
<form action="" method = "post">
{% csrf_token %}
<label for="Items">Choose an Item:</label>
<select id = items >
{% for item in itemNames %}
<option value = "">{{item.itemName}}</option>
{% endfor %}
</form>
Changed the view to listview. I am not sure why I used Formview
Here's the code
views.py
from django.views.generic import ListView
from .models import Item
class OrderListView(ListView):
template_name = "myapp/orderlist.html"
context_object_name = 'itemNames'
def get_queryset(self):
return Item.objects.all()
The other answer is to change the html file to
<form action="" method = "post">
{% csrf_token %}
<label for="Items">Choose an Item:</label>
{{form.as_p}}
</form>

How do I sort my topics by category in Django?

Alright so I want to order my topics by the category in Django. What's the best way of doing this?
views.py:
from django.shortcuts import render
from .models import Category
from .models import Topic
# Create your views here.
def forums(request):
categorys = Category.objects.all()
topics = Topic.objects.all()
return render(request, 'forums.html', {'categorys': categorys, 'topics': topics})
models.py:
from django.db import models
# Create your models here.
class Attachment(models.Model):
file = models.FileField()
def __str__(self):
return self.file
class Category(models.Model):
title = models.CharField(max_length=150)
def __str__(self):
return self.title
class Topic(models.Model):
title = models.CharField(max_length=150)
description = models.TextField()
category = models.ForeignKey('Category', on_delete=models.CASCADE)
def __str__(self):
return self.title
class Post(models.Model):
title = models.CharField(max_length=150)
body = models.TextField()
forum = models.ForeignKey('Topic', on_delete=models.CASCADE)
def __str__(self):
return self.title
Also, yes I know that categories is spelled wrong, I still need to add the Meta.
You can get all the topics inside categories in following way:
{% for category in categorys %}
<h1>{{category.title}}</h1>
<ul>
{% for topic in category.topic_set.all %}
<li>{{topic.title}}</li>
{% endfor %}
</ul>
{% endfor %}

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/

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

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

Categories