I'm been trying to figure out how could I query forthe most liked whiteboard for a particular category
At the moment i'm been querying for all the whiteboards objects for a particular category.
One of my solutions was to query by the boards by the counts of liked but I just couldn't think of a way to query for it
An example at the moment I can retrieve all the whiteboard objects for a particular category , Now how could I retrieve the most liked whiteboard for a particular category.
Can someone help me create function that would query the most liked board of the category so I can understand logically how I can create my own later .Thank you
class WhiteBoard(models.Model):
ENGLISH = 'ENGLISH'
MATH = 'MATH'
SCIENCE = 'SCIENCE'
BIOLOGY = 'BIOLOGY'
CATEGORY = (
(ENGLISH , 'English'),
(MATH, 'Math'),
(SCIENCE, 'Science'),
(BIOLOGY, 'Biology'),
)
Category =models.CharField(max_length=30,choices=CATEGORY)
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
picture = models.OneToOneField('Picture',related_name='picture',blank=True,null=True)
def __unicode__(self):
return self.name
class LikeBoard(models.Model):
user = models.ForeignKey(User)
Whiteboard = models.ForeignKey(WhiteBoard)
created = models.DateTimeField(auto_now_add=True)
My views.py
def WhiteBoardFinder(request):
form = WhiteBoardFinderForm(request.POST)
fo = WhiteBoardFinderForm()
if form.is_valid():
Category = form.cleaned_data['Category']
Whiteboard = WhiteBoard.objects.filter(Category=Category)
return render(request,"boardfinder.html",{"board":board,"fo":fo})
return render(request,"boardfinder.html",{"fo":fo})
boardfinder.html
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ fo.as_p }}
<input type = "submit" value= "Find Board" />
</form>
{% if board %}
<ul>
{% for b in board %}
<li><a href ="{% url world:Boat b.id %}">{{ b.name }}</li>
{% if b.picture %}
<br><img src="{{ b.picture.image.url }}">
{% endif %}
{% endfor %}
</ul>
{% endif %}
My forms.py
class BoardFinderForm(forms.ModelForm):
class Meta:
model = WhiteBoard
fields = ('Category',)
models.py
class WhiteBoard(models.Model):
ENGLISH = 'ENGLISH'
MATH = 'MATH'
SCIENCE = 'SCIENCE'
BIOLOGY = 'BIOLOGY'
CATEGORY = (
(ENGLISH , 'English'),
(MATH, 'Math'),
(SCIENCE, 'Science'),
(BIOLOGY, 'Biology'),
)
Category =models.CharField(max_length=30,choices=CATEGORY)
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
picture = models.OneToOneField('Picture',related_name='picture',blank=True,null=True)
def __unicode__(self):
return self.name
#property
def count_likes(self):
return LikeBoard.objects.filter(whiteboard=self).count()
class LikeBoard(models.Model):
user = models.ForeignKey(User)
whiteboard = models.ForeignKey(WhiteBoard) //modified because of conflict
created = models.DateTimeField(auto_now_add=True)
views.py
def WhiteBoardFinder(request):
form = WhiteBoardFinderForm(request.POST)
fo = WhiteBoardFinderForm()
if form.is_valid():
Category = form.cleaned_data['Category']
whiteboard = WhiteBoard.objects.filter(Category=Category)
categories = WhiteBoard.objects.values_list('Category', flat=True).distinct()
whites = sorted(whiteboard, key=lambda x: x.count_likes, reverse=True)
return render(request,"boardfinder.html",{
"board":board,"fo":fo, "categories": categories, "whites": whites})
return render(request,"boardfinder.html",{"fo":fo})
templates
{% for category in categories %}
{{ category }}<br/>
{% for white in whites %}
{% if white.Category == category %}
{{ white }} - {{ white.count_likes }},
{% endif %}
{% endfor %}<br/>
{% endfor %}
Related
I am creating a website with a collection of menus from restaurants in my town (since none of them seem to be on grubhub or the internet). I am having trouble creating a model for this. As you know every restaurant menu has sections(I.e Appetizers, Chicken, Steak) and entries under each section(I.e under Appetizers: Mozzarella Sticks, Nachos, etc.) I am trying to create a Menu model so that each section of the menu and all of its entries can automatically fill a template:
<h1>{{section}}</h1> <!--I.e:"Appetizers"-->
<p>{{food}} </p><!--I.e:"Mozzarella Sticks"-->
<p>{{ food_details }}</p>
With the above template, I can use a loop to loop through each section, then another inner loop to loop through each food and food_details belonging to that specific section, but I am not sure how to model this properly:
from django.db import models
class Restaurant(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
phoneNumber = models.CharField(max_length=10)
def __str__(self):
return "%s the place" % self.name
class Menu(models.Model):
restaurant = models.OneToOneField(
Restaurant,
on_delete=models.CASCADE,
primary_key=True,
)
# not sure how to build menu fields
#if I do the following each menu will only have one of these fields, which will not work:
section = models.CharField(max_length=50)
food = models.CharField(max_length=50)
food_details = models.CharField(max_length=200)
How can I create a model of a menu that has multiple section's and multiple food and food_details entries under each section? I hope this made sense, let me know if there is anything I can add and thanks in advance for any help.
You could try something like this:
# models.py
FOOD_TYPES = (
('appetizer', 'appetizer'),
('entree', 'entree'),
('dessert', 'dessert'),
)
class FoodItem(models.Model):
name = models.CharField(max_length=30)
description = models.CharField(max_length=100)
type = models.CharField(max_length=100, choices=FOOD_TYPES)
class Menu(models.Model):
restaurant = models.OneToOneField(
Restaurant,
on_delete=models.CASCADE,
primary_key=True,
)
food_items = models.ManyToManyField(FoodItem)
In a view:
# views.py
class Restaurant(TemplateView):
model = Restaurant
template_name = 'name'
...
def get_context_data
context = super(Menu, self).get_context_data(**kwargs)
restaurant = Restaurant.objects.get(name='McDonalds')
context['restaurant'] = Restaurant.objects.get(name='McDonalds')
context['menu'] = Menu.objects.get(restaurant=restaurant)
return context
In the template:
# template.html
<h1>{{ restaurant.name }}</h1>
<h2>Menu</h2>
{% for item in menu.food_items %}
{% if item.type = 'appetizer' %}
<p>
{{ item.name }}
{{ item.description }}
{{ item.type }}
</p>
{% else %}
<p>No appetizers</p>
{% endif %}
{% if item.type = 'entree' %}
<p>
{{ item.name }}
{{ item.description }}
{{ item.type }}
</p>
{% else %}
<p>No entrees</p>
{% endif %}
{% if item.type = 'dessert' %}
<p>
{{ item.name }}
{{ item.description }}
{{ item.type }}
</p>
{% else %}
<p>No dessert</p>
{% endif %}
{% endfor %}
I'm wrinting a Django project.
In courses/models.py
class Category(models.Model):
title = models.CharField(max_length=50)
class Language(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
title = models.CharField(max_length=50)
class Course(models.Model):
name = models.CharField(max_length=250)
language = models.ForeignKey(Language, on_delete=models.CASCADE)
I want to get list of all Category and then loop through each Language of specified category.
class Courses(ListView):
template_name = 'courses/index.html'
model = Course
context_object_name = 'courses'
def get_context_data(self, **kwargs):
context = super(Courses, self).get_context_data(**kwargs)
categories = Category.objects.all()
context['categories'] = categories
return context
in template courses/index.html I want to show the list of languages based on category
{% for category in categories %}
{{ category.title }}
<li>lis of languages in this category</li>
{% endfor %}
How to loop on backward associated data?
Django creates a relation that is accessible in the templates through the modelname_set key.
In your case, you'd have to iterate over:
category.language_set.all
{% for category in categories %}
{{ category.title }}
{% for language in category.language_set.all %}
<li>{{ language.title }}</li>
{% endfor %}
{% endfor %}
_set does this work.
eg. in your case this code must work:
{% for language in category.language_set.all %}
{{ language.title }}
{% endfor %}
I have 2 model objects, Business & BusinessImage as so, listed with views and index.html. I am trying to list the business's featured image, but it's not happening. I am getting the following error:
'QuerySet' object has no attribute 'businessimage_set'
How can I get the business featured image for a list?
Business
class Business(models.Model):
name = models.CharField("Name", max_length=70, default="Business Name")
slug = models.SlugField()
description = models.TextField("About", max_length=400)
category = models.ManyToManyField(Category, verbose_name="Categories", blank=True)
order = models.IntegerField("Order", default=0)
claimed = models.BooleanField("Claimed", default=False)
featured = models.BooleanField("Featured", default=False)
class Meta:
ordering = ['order']
verbose_name = "Business"
verbose_name_plural = "Businesses"
def __str__(self):
return self.name
BusinessImage
class BusinessImage(models.Model):
business = models.ForeignKey(Business)
image = models.ImageField(upload_to="images/business")
title = models.CharField(max_length=120)
featured = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return self.title
view.py
from .models import Business, BusinessImage
def index_view(request):
latest_business_list = Business.objects.all()
images = latest_business_list.businessimage_set.all()
template = loader.get_template('index.html')
context = RequestContext(request, {
'latest_business_list': latest_business_list,
'images': images,
})
return HttpResponse(template.render(context))
index.html
{% block content %}
<div class="text-center business_title">
<h2>Featured</h2>
</div>
{% if latest_business_list %}
{% for business in latest_business_list|slice:":4" %}
{% if business.active %}
<div class="col-sm-6 col-md-3">
<li>{{ business.name }}</li>
{% for image in latest_business_list.businessimage_set.all %}
{% if image.featured %}
<a href="{% url 'single_product' product.slug %}">
<img src="{{MEDIA_URL}}{{image.image}}" alt="{{image}}">
</a>
{% endif %}
{% endfor %}
</div>
{% endif %}
{% endfor %}
{% endif %}
{% endblock %}
businessimage_set is an attribute of a Business instance, but you're trying to access it as an attribute of a queryset (i.e. list of businesses). If your goal is just to be able to access the images for each business in a template, you can leave out images entirely. Instead your template would have:
{% for image in business.businessimage_set.all %}
(Though look into prefetch_related for efficiency.)
I'm working on multi-user rss reader. I want to limit display of posts only to those which are unread. I've managed to do this in my single "feed" view as below, but I can't figure out how to do the same in multiple feed aka "category" view.
I've been trying something like here https://docs.djangoproject.com/en/1.5/topics/db/queries/#spanning-multi-valued-relationships but it didn't work for me
Should I change my "category" view code or template code? and if so how would you go about it?
thanks!
-S
models
class UserCategory(models.Model):
name = models.CharField(unique=False, max_length=64)
user = models.ForeignKey(User)
slug = AutoSlugField(populate_from='name', always_update='True', unique_with='user')
class Feed(models.Model):
feed_url = models.URLField(unique=True)
default_title = models.CharField(max_length=64, blank=True)
link = models.URLField(blank=True)
class UserFeed(models.Model):
feed = models.ForeignKey(Feed)
title = models.CharField(max_length=64)
category = models.ForeignKey(UserCategory)
user = models.ForeignKey(User)
slug = AutoSlugField(populate_from='title', always_update='True', unique_with='user')
class Post(models.Model):
feed = models.ForeignKey(Feed)
title = models.CharField(max_length=256)
content = models.TextField()
link = models.URLField(max_length=512)
class ReadPost(models.Model):
user = models.ForeignKey(User)
post = models.ForeignKey(Post)
views
def feed(request, user_feed_slug):
user_feed = get_object_or_404(UserFeed.objects.filter(slug=user_feed_slug, user=request.user))
read_post = ReadPost.objects.filter(user=request.user).values_list('post')
posts = Post.objects.select_related().filter(feed=user_feed.feed).exclude(id__in=read_post)
def category(request, user_category_slug):
user_category = get_object_or_404(UserCategory.objects.filter(slug=user_category_slug, user=request.user))
templates
feed
{% for post in posts %}
{{ post.title }}
{% endfor %}
category
{% for feed in user_category.userfeed_set.all %}
{{ feed.title }}
{% for post in feed.feed.post_set.all %}
{{ post.title }}
{{ post.content }}
{% endfor %}
{% endfor %}
You can write custom template filter, i.e:
#register.filter
def unread(posts, read_posts):
return posts.exclude(id__in=read_posts)
(before you must pass read_post to category template context).
Try this queryset:
def category(request, user_category_slug):
user_category = get_object_or_404(UserCategory, slug=user_category_slug,
user=request.user))
feeds = UserFeed.objects.filter(category__slug=user_category_slug, user=request.user)\
.prefetch_related('feed__post_set')
then in your template:
{% for feed in feeds %}
{{ feed.title }}
{% for post in feed.feed.post_set.all %}
{{ post.title }}
{{ post.content }}
{% endfor %}
{% endfor %}
I have a simple setup of InventoryItems and Categories. I have a formset of InventoryItems but want to split up the items based on the FK Category, I don't need or want an inline form set.
Simplified version of what I have
class Category(models.Model):
name = models.CharField(max_length=255)
inventory = models.BooleanField(default=False)
class Inventory(models.Model):
name = models.CharField(max_length=255)
quantity = models.IntegerField()
category = models.ForeignKey(Category)
def viewOfForm(request):
categories = Category.objects.filter(inventory=True)
InventoryFormset = modelformset_factory(Inventory, can_delete=True, extra=1)
formset = InventoryFormset(request.POST or None, queryset=Inventory.objects.filter(category__inventory=True))
return render_to_response('template.html', locals())
What I would like to do in the template
{% for category in categories %}
<fieldset class="collapse">
<h2>{{ category.name }}</h2>
{% for form in formset %}
{% if form.category == category %}
{{ form }}
{% endif %}
{% endfor %}
</fieldset>
{% endfor %}
You only need a small change to get this working; use form.instance.category in your if template tag:
{% if form.instance.category == category %}