How can I render the data in from the model to the html? The way they describe it in the docs doesn´t work for me. Here is what I have:
class Thema(models.Model):
title = models.CharField(max_length=70, help_text="The title of the Post")
publication_date = models.DateField(verbose_name="Date the Post was published.")
text = models.TextField(max_length=5000,default='kein Textinhalt vorahnden')
category = models.ForeignKey(Category, on_delete=models.CASCADE)
bilder = models.ForeignKey(Bilder, on_delete=models.CASCADE)
links = models.ManyToManyField(Link)
files = models.ManyToManyField(File)
tags = models.ManyToManyField(Tag)
def __str__(self):
return self.title
The View:
from .models import Thema
from django.views.generic import TemplateView
class HomePageView(TemplateView):
model = Thema
context_object_name = 'themas'
template_name = "home/home.html"
And the template:
<h2>THEMAS</h2>
<ul>
{% for thema in themas %}
<li>{{ thema.title }}</li>
{% endfor %}
</ul>
How can I render the many to many fields?
thanks for answers
Your template assumes that themas is a list. But themas is actually only one model instance of Thema.
class HomePageView(TemplateView):
model = Thema # model is Thema
context_object_name = 'thema' # 'themas' is missleading --> change to 'thema'
# because this view only passes ONE Thema to the view
template_name = "home/home.html"
<h1>Thema: {{ thema.title }}</h1>
<h3>Links:</h3>
{% for link in thema.links.all %}
<li>{{ link }}</li>
{% endfor %}
<h3>Tags:</h3>
{% for tag in thema.tags.all %}
<li>{{ tag }}</li>
{% endfor %}
Related
I have created a productForArt and albomForArt model
From producForArt I inherit to albomForArt
Making a view based on generic.ListView
And I output it in the template,
Can I access the number Of Pages field in the template
albomForArt models, or in this case Django returns an object of the albomForArt model, but with properties that were inherited from albomForArt?
models
from django.db import models
class productForArt(models.Model):
class Meta:
verbose_name = u'товар'
verbose_name_plural = u'товары'
price = models.IntegerField(verbose_name="цена", default=0)
title = models.CharField(max_length=300, verbose_name="название товара", null=True)
description = models.CharField( max_length=1000,verbose_name="Описание товара", null=True)
type = models.ForeignKey('typeProductForArt', on_delete=models.PROTECT)
def getType(self):
return self.type
def __str__(self):
return str(self.title) + ' по цене' + str(self.price) + ' шт'
class albomForArt(productForArt):
numberOfPages = models.IntegerField(default=10,verbose_name="количество станиц" )
class typeProductForArt(models.Model):
title = models.CharField(max_length=200, default="none")
def __str__(self):
return self.title
vievs
from django.views import View, generic
from .models import productForArt
class startPage(generic.ListView):
model = productForArt
template_name = "startPage.html"
context_object_name = "productForArt_list"
queryset = productForArt.objects.all()[:20]
templates
{% if productForArt_list %}
<section class="productsStartpage">
{% for productForArt in object_list %}
<article class="productForArtStartpage">
<h1>{{productForArt.title}}</h1>
<p>{{productForArt.description}}</p>
{% endif %}
</article>
{% endfor %}
</section>
{% else %}
<p>товара нету</p>
{% endif %}
You can use One-to-one relationships
class albomForArt(productForArt):
product_for_art = models.OneToOneField(productForArt, on_delete=models.CASCADE)
numberOfPages = models.IntegerField(default=10,verbose_name="количество станиц" )
Then in Template
{% if productForArt_list %}
<section class="productsStartpage">
{% for productForArt in object_list %}
<article class="productForArtStartpage">
<h1>{{productForArt.product_for_art.title}}</h1>
<p>{{productForArt.product_for_art.description}}</p>
{% endif %}
</article>
{% endfor %}
</section> {% else %} <p>товара нету</p>{% endif %}
i am trying to add objects from my model into my CBV, i have a model created so i am trying to pass them to my views, but its not working,tho i have 2 classes created which are Pricing and Pricingservice, i want an inline for a field in Pricingservice which i did, but i dont know how to add both to my view in CBV in the view so as to access them in my template, here is my code below, kindly help me out because i have been battling with this for days, thanks
model.py
class Pricing(models.Model):
plans = models.CharField(max_length=250)
amount = models.CharField(max_length=250)
services = models.CharField(max_length=250)
def __str__(self):
return self.plans
class Pricingservice(models.Model):
pricing = models.ForeignKey(Pricing, default=None, on_delete=models.CASCADE)
services = models.CharField(max_length=250)
def __str__(self):
return self.pricing.plans
admin.py
class PricingserviceAdmin(admin.StackedInline):
model = Pricingservice
#admin.register(Pricing)
class PricingAdmin(admin.ModelAdmin):
inlines = [PricingserviceAdmin]
class Meta:
model = Pricing
views.py
class HomePageView(TemplateView):
template_name = 'pages/home.html'
def get_context_data(self, **kwargs):
context = super(HomePageView, self).get_context_data(**kwargs)
context['Pricing'] = Pricing.objects.all()
return context
template.html
<div class="row">
{% for p in Pricing %}
<div class="col-md-3 ftco-animate">
<div class="pricing-entry pb-5 text-center">
<div>
<h3 class="mb-4">{{ p.plans }}</h3>
<p><span class="price">#{{ p.amount }}</span> <span class="per">/ Month</span></p>
</div>
<ul>
<li>{{ p.services }}</li>
</ul>
<p class="button text-center">Get Offer</p>
</div>
</div>
{% endfor %}
</div>
[] 1
Try this solution:
class HomePageView(ListView):
model = Pricing
template_name = 'pages/home.html'
And then try this template:
{% for pricing in object_list %}
{{pricing.plans}}<br>
{% for service in pricing.pricingservice_set.all %}
{{ service.services }}<br>
{% endfor %}
{% endfor %}
Please add some styling yourself. :)
It would be better to use a ListView. You would need to tell Django what the relevant model for your view is, i.e.:
class HomePageView(ListView):
model = Pricingservice
template_name = 'pages/home.html'
And then in your template, you can use:
{% for pricingservice in pricingservice_list %}
{{ pricingservice.pricing }}
{% endfor %}
I am not sure exactly how your two models differ, but maybe it would be better to merge them?
try this
views.py
class HomePageView(TemplateView):
template_name = 'pages/home.html'
def get_context_data(self, **kwargs):
context = super(HomePageView, self).get_context_data(**kwargs)
context['Pricing'] = Pricing.objects.all()
return context
class PricePageView(ListView):
model = Pricingservice
template_name = 'pages/home.html'
urls.py
path('', HomePageView.as_view(), name='home'),
path('price/', PricePageView.as_view(), name='price'),
template.html
{% for pricingservice in Pricingservice_list %}
<ul>
<li>{{ pricingservice }}</li>
</ul>
{% endfor %}
am not sure this will work but try this if that answer does not work for you
I have two Models, reseller and customer. I can generate Tree hierarchy for reseller, But I want to list down Customers under their immediate parent reseller.
models.py
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
# Create your models here.
class Reseller(MPTTModel):
reseller_name = models.CharField(max_length=40)
reseller_email = models.EmailField(max_length=70,blank=True)
reseller_code = models.CharField(max_length=40)
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
class MPTTMeta:
order_insertion_by = ['reseller_name']
def __str__(self):
return self.reseller_name
class Customer(models.Model):
customer_name = models.CharField(max_length=40)
customer_email = models.EmailField(max_length=70,blank=True)
customer_code = models.CharField(max_length=40)
reseller = models.ForeignKey(Reseller, on_delete=models.CASCADE, null=True, blank=True, related_name='cust_children')
def __str__(self):
return self.customer_name
This is the view :
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from .forms import *
# Create your views here.
def index(request):
return render(request, 'main/login.html')
def home(request):
resellers = Reseller.objects.all()
customers = Customer.objects.all()
context = { 'resellers' : resellers, 'customers' : customers }
return render(request, 'main/home.html', context)
This the recursetree tag that is been cited in mptt docs.
home.html
{% recursetree resellers %}
<li>
{{ node.reseller_name }}
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
Here is the order I'm aiming to:
reseller1
-reseller2
-customer1
--reseller3
----customer2
The reason it doesn't work is because customers aren't part of the resellers tree, you need to get them manually. Something like this will give you a start:. If customers aren't always at a lead node you'll need to make some changes, though.
{% recursetree resellers %}
<li>
{{ node.reseller_name }}
{% if node.cust_children.all %}
<ul>
{% for customer in node.cust_children.all %}
<li>{{ customer.customer_name }}</li>
{% endfor %}
</ul>
{% endif %}
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
I'm trying to display a photographic session with all of it photos, so I have the session name in one model and I have the pictures in
another model linked by a foreign key. I'm not able to display it in
the HTML I'm not sure if I'm using the ListView get_context_data
correctly and I'm certainly sure the the html code is not correct but
I have not found how to do it.
views.py
class SessionPictures(generic.ListView):
model = PostSession
template_name = 'photoadmin/gallery.html'
def get_context_data(self, **kwargs):
context = super(SessionPictures, self).get_context_data(**kwargs)
context['picture'] = Images.objects.all()
return context
models.py
class PostSession(models.Model):
session_name = models.CharField(max_length=25)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return str(self.session_name)
class Images(models.Model):
name = models.ForeignKey(
PostSession, related_name='images', on_delete=models.CASCADE, null=True, blank=True)
picture = models.ImageField(upload_to='pictures')
html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<h2>Images</h2>
<ul>
{% for session in object_list %}
<li>{{ session.session_name }}</li>
<ul>
<li>{{session.picture_set.all.url}}</li>
</ul>
{% endfor %}
</ul>
{% endblock %}
I'm expecting this:
Woods
picture1.url
picture2.url
picture3.url
Beach
Picture4.url
picture5.rul
As you already defined related_name="images" in Images model, so, session.images_set attribute won't work with PostSession.
class Images(models.Model):
name = models.ForeignKey(
PostSession,related_name='images', on_delete=models.CASCADE, null=True, blank=True)
Instead, use session.image.all in template(FYI: it returns a queryset, so you need to iterate through it to get the image object):
{% for session in object_list %}
<li>{{ session.session_name }}</li>
<ul>
{% for i in session.images.all %}
<li> i.picture.url </li>
{% endfor %}
</ul>
{% endfor %}
More information on reverse relation can be found in documentation.
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 %}