QuerySet returning empty - django

I am building a website where users can follow certain stocks and see articles based on the stocks they follow
models.py:
from django.db import models
from django.contrib.auth.models import User
class Stock(models.Model):
name = models.CharField(max_length = 50)
ticker = models.CharField(max_length = 50)
def __str__(self):
return self.name
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
followed_stocks = models.ManyToManyField(Stock, blank=True)
def __str__(self):
return self.user.first_name
class Article(models.Model):
stock = models.ForeignKey(Stock, on_delete=models.CASCADE, default = 0 )
title = models.CharField(max_length = 200)
url = models.URLField()
description = models.TextField()
def __str__(self):
return self.title
views.py:
from django.shortcuts import render
from .models import Article
def index(request):
stocks_user_follows = request.user.profile.followed_stocks.all()
articles_to_display = Article.objects.filter(stock__in=stocks_user_follows) #where the problem lies
return render(request, 'core/index.html', {'stocks_user_follows':stocks_user_follows, 'articles_to_display':articles_to_display})
stocks_user_follows = request.user.profile.followed_stocks.all() returns the correct value but when I print {{articles_to_display}} in index.html there is nothing in the QuerySet which means i must be doing something wrong. Thanks in advance!

Related

Filtering on Django Queryset

So, I think I am missing something very obvious, or setup my models incorrectly, I am attempting to create a view on my blog that filters on the category slug, but my filter will only work on the Entry slug; please see my models below as well as my views. Any help would be greatly appreciated. Thank you.
My Models
from django.db import models
from django.core.urlresolvers import reverse
from django_markdown.models import MarkdownField
class EntryQuerySet(models.QuerySet):
def published(self):
return self.filter(publish=True)
class Tag(models.Model):
slug = models.SlugField(max_length=200, unique=True)
def __str__(self):
return self.slug
class Category(models.Model):
slug = models.SlugField(max_length=100, blank=False)
def __str__(self):
return self.slug
class Entry(models.Model):
title = models.CharField(max_length=200)
body = MarkdownField()
slug = models.SlugField(max_length=200, unique=True)
publish = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(Tag)
category = models.ForeignKey(Category)
objects = EntryQuerySet.as_manager()
def get_absolute_url(self):
return reverse("post_detail", kwargs={"slug": self.slug})
def __str__(self):
return self.title
class Meta:
verbose_name = "Blog Entry"
verbose_name_plural = "Blog Entries"
ordering = ["-created"]
My Views
from django.views import generic
from . import models
class BlogIndex(generic.ListView):
queryset = models.Entry.objects.published()
template_name = "blog/post_list.html"
class BlogDetail(generic.DetailView):
model = models.Entry
template_name = "blog/post_detail.html"
# Marketing Pages
class GlamisView(generic.ListView):
queryset = models.Entry.objects.filter(slug="glamis")
template_name = "blog/glamis_list.html"
If I understand you right you can use a lookup expression. Your query will look like:
queryset = models.Entry.objects.filter(category__slug="glamis")
More on querying many to one relations

how to populate django models randomly

I am following a tutorial online for Django. The presenter loads in random data as follows:
for i in xrange(100): Vote(link = Link.objects.order_by('?')[0],voter=a).save()
From what I could understand, it goes from 0 to 100 and creates a new vote. The vote object has a link object. I don't understand what the order_by('?') means.
Here is the model.py file:
from django.db import models
from django.contrib.auth.models import User
from django.db.models import Count
class LinkVoteCountManager(models.Manager):
def get_query_set(self):
return super(LinkVoteCountManager, self).get_query_set().annotate(
votes=Count('vote')).order_by("-votes")
class Link(models.Model):
title = models.CharField("Headline", max_length=100)
submitter = models.ForeignKey(User)
submitted_on = models.DateTimeField(auto_now=True)
rank_score = models.FloatField(default=0.0)
url = models.URLField("URL", max_length=250, blank=True)
description = models.TextField(blank=True)
with_votes = LinkVoteCountManager()
objects = models.Manager()
def __unicode__(self):
return self.title
class Vote(models.Model):
voter = models.ForeignKey(User)
link = models.ForeignKey(Link)
def __unicode__(self):
return "%s voted %s" %(self.voter.username, self.link.title)

No module named models

I know this error has been referred number of items in the forum, I tried it all but still it fails..
Case1:
from models import Category,Product
Error:
Could not import ecomstore.catalog.views. Error was: No module named models
Case2:
from ecomstore.catalog.models import Category,Product
Error:
could not import ecomstore.catalog.views. Error was: No module named models
Case3:
from catalog.models import Category,Product
Error:
could not import ecomstore.catalog.views. Error was: No module named models
Folder structure:
Catalog
models.py
views.py
urls.py
models.py
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True,
help_text='Unique value for product page URL, created from name.')
description = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords",max_length=255,
help_text='Comma-delimited set of SEO keywords for meta tag')
meta_description = models.CharField("Meta Description", max_length=255,
help_text='Content for description meta tag')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
db_table = 'categories'
ordering = ['-created_at']
verbose_name_plural = 'Categories'
def __unicode__(self):
return self.name
#models.permalink
def get_absolute_url(self):
return ('catalog_category', (), { 'category_slug': self.slug })
class Product(models.Model):
name = models.CharField(max_length=255, unique=True)
slug = models.SlugField(max_length=255, unique=True,
help_text='Unique value for product page URL, created from name.')
brand = models.CharField(max_length=50)
sku = models.CharField(max_length=50)
price = models.DecimalField(max_digits=9,decimal_places=2)
old_price = models.DecimalField(max_digits=9,decimal_places=2,
blank=True,default=0.00)
image = models.CharField(max_length=50)
is_active = models.BooleanField(default=True)
is_bestseller = models.BooleanField(default=False)
is_featured = models.BooleanField(default=False)
quantity = models.IntegerField()
description = models.TextField()
meta_keywords = models.CharField(max_length=255,
help_text='Comma-delimited set of SEO keywords for meta tag')
meta_description = models.CharField(max_length=255,
help_text='Content for description meta tag')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
categories = models.ManyToManyField(Category)
class Meta:
db_table = 'products'
ordering = ['-created_at']
def __unicode__(self):
return self.name
#models.permalink
def get_absolute_url(self):
return ('catalog_product', (), { 'product_slug': self.slug })
def sale_price(self):
if self.old_price > self.price:
return self.price
else:
return None
views.py
from django.shortcuts import get_object_or_404, render_to_response
from models import Category,Product
from django.template import RequestContext
from django.core import urlresolvers
from django.http import HttpResponseRedirect
from forms import ProductAddToCartForm
from cart import cart
# Create your views here.
print 'prem in catalog views.py'
def index(request,template_name="catalog/index.html"):
page_title = 'Musical instruments and Sheet Music for Musicians'
return render_to_response(template_name,locals(),context_instance=RequestContext(request))
def show_category(request,category_slug,template_name="catalog/category.html"):
c = get_object_or_404(Category,slug=category_slug)
products = c.product_set.all()
page_title = c.name
meta_keywords = c.meta_keywords
meta_description = c.meta_description
return render_to_response(template_name,locals(),context_instance=RequestContext(request))
def show_product(request, product_slug, template_name="catalog/product.html"):
p = get_object_or_404(Product, slug=product_slug)
categories = p.categories.all()
page_title = p.name
meta_keywords = p.meta_keywords
meta_description = p.meta_description
# need to evaluate the HTTP method
if request.method == 'POST':
# add to cart create the bound form
postdata = request.POST.copy()
form = ProductAddToCartForm(request, postdata)
#check if posted data is valid
if form.is_valid():
#add to cart and redirect to cart page
cart.add_to_cart(request)
# if test cookie worked, get rid of it
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
url = urlresolvers.reverse('show_cart')
return HttpResponseRedirect(url)
else:
# its a GET, create the unbound form.Note request as a kwarg
form = ProductAddToCartForm(request=request, label_suffix=':')
# assign the hidden input the product slug
form.fields['product_slug'].widget.attrs['value'] = product_slug
# set the test cookie on our first GET request
request.session.set_test_cookie()
return render_to_response(template_name, locals(),context_instance=RequestContext(request))
ecomstore
catalog
models
urls
views
cart
models
urls
views
cart
settings
urls

ContentType Issue — Human is an idiot - Can't figure out how to tie the original model to a ContentType abstracted 'Favorite' model

Originally started here: Django IN query as a string result - invalid literal for int() with base 10
I have a number of apps within my site, currently working with a simple "Blog" app. I have developed a 'Favorite' app, easily enough, that leverages the ContentType framework in Django to allow me to have a 'favorite' of any type... trying to go the other way, however, I don't know what I'm doing, and can't find any examples for.
I'll start off with the favorite model:
favorite/models.py
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.auth.models import User
class Favorite(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
user = models.ForeignKey(User)
content_object = generic.GenericForeignKey()
class Admin:
list_display = ('key', 'id', 'user')
class Meta:
unique_together = ("content_type", "object_id", "user")
Now, that allows me to loop through the favorites (on a user's "favorites" page, for example) and get the associated blog objects via {{ favorite.content_object.title }}.
What I want now, and can't figure out, is what I need to do to the blog model to allow me to have some tether to the favorite (so when it is displayed in a list it can be highlighted, for example).
Here is the blog model:
blog/models.py
from django.db import models
from django.db.models import permalink
from django.template.defaultfilters import slugify
from category.models import Category
from section.models import Section
from favorite.models import Favorite
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class Blog(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=140, editable=False)
author = models.ForeignKey(User)
homepage = models.URLField()
feed = models.URLField()
description = models.TextField()
page_views = models.IntegerField(null=True, blank=True, default=0 )
created_on = models.DateTimeField(auto_now_add = True)
updated_on = models.DateTimeField(auto_now = True)
def __unicode__(self):
return self.title
#models.permalink
def get_absolute_url(self):
return ('blog.views.show', [str(self.slug)])
def save(self, *args, **kwargs):
if not self.slug:
slug = slugify(self.title)
duplicate_count = Blog.objects.filter(slug__startswith = slug).count()
if duplicate_count:
slug = slug + str(duplicate_count)
self.slug = slug
super(Blog, self).save(*args, **kwargs)
class Entry(models.Model):
blog = models.ForeignKey('Blog')
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=140, editable=False)
description = models.TextField()
url = models.URLField(unique=True)
image = models.URLField(blank=True, null=True)
created_on = models.DateTimeField(auto_now_add = True)
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
if not self.slug:
slug = slugify(self.title)
duplicate_count = Entry.objects.filter(slug__startswith = slug).count()
if duplicate_count:
slug = slug + str(duplicate_count)
self.slug = slug
super(Entry, self).save(*args, **kwargs)
class Meta:
verbose_name = "Entry"
verbose_name_plural = "Entries"
Any guidance?
The django doc on it is here: Reverse generic relations. Basically on the Blog model itself you can add a GenericRelation...
class Blog(models.Model):
favorites = generic.GenericRelation(Favorite)
For a given blog you can find all of the Favorite models that are associated with it...
b = Blog.objects.get(slug='hello-world-blog-slug')
all_blog_favorites = b.favorites.objects.all()
Or see if the current user has the blog favorited...
user_has_blog_favorited = b.favorites.objects.filter(user=request.user).exists()

Django admin form - how to change select options dynamically?

I have 2 models:
class City(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50)
class CityNews(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
add_date = models.DateTimeField(auto_now=False, auto_now_add=True, editable=False)
content = models.TextField()
city = models.ForeignKey(City)
My each user has been connected with 1 city. I want him to add news only to the city he id connected with. But superadmin must have possibility to add news to each city.
How can I change 'city' field in CityNews, that they show only the city that user is connected with? I can write custom ModelForm but how can I check user_city there and change its queryset?
One obvious way of doing this is to utilize the formfield_for_foreignkey() method on the ModelAdmin.
So if your models.py looks like this:
from django.db import models
from django.contrib.auth.models import User
class City(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class CityNews(models.Model):
added_by = models.ForeignKey(User)
city = models.ForeignKey(City)
title = models.CharField(max_length=100)
content = models.TextField()
class UserExtra(models.Model):
user = models.ForeignKey(User)
city = models.ForeignKey(City)
Then your admin.py could look like this:
from django.contrib import admin
from formtesting.models import City, CityNews, UserExtra
from django.forms.models import ModelChoiceField
from django.contrib.auth.models import User
class CityAdmin(admin.ModelAdmin):
pass
admin.site.register(City, CityAdmin)
class CityNewsAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "city":
if request.user.is_superuser:
queryset = City.objects.all()
else:
queryset = City.objects.filter(userextra__user=request.user)
return ModelChoiceField(queryset, initial=request.user)
elif db_field.name == "added_by":
if request.user.is_superuser:
queryset = User.objects.all()
else:
queryset = User.objects.filter(id=request.user.id)
return ModelChoiceField(queryset, initial=request.user)
else:
return super(CityNewsAdmin, self).formfield_for_foreignkey(db_field,
request, **kwargs)
admin.site.register(CityNews, CityNewsAdmin)
class UserExtraAdmin(admin.ModelAdmin):
pass
admin.site.register(UserExtra, UserExtraAdmin)

Resources