I have an app that has a list of projects, and each project has a number of posts, and when you click on a project, it shows all of the posts in that project, but I can't figure out how to make it display what project the user is currently on, sample of it not working It should say "Posts for project 1" for example. Here is the relevant code of what I have so far.
<h1 class="mb-3">Posts for {{ post.project.title }}</h1>
{% for post in posts %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
</div>
<h2><a class="article-title">{{ post.title }}</a></h2>
<p class="article-content">{{ post.description }}</p>
</div>
</article>
{% endfor %}
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(default='')
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('project-detail', kwargs = {'pk': self.pk})
class Post(models.Model):
def get_default_action_status():
return Project.objects.get(title="bruh")
project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='posts', default=get_sentinel_exam_id)
title = models.CharField(max_length=100)
description = models.TextField(default='')
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
LOW = '!'
MED = '!!'
HIGH = '!!!'
YEAR_IN_SCHOOL_CHOICES = [
(LOW, '!'),
(MED, '!!'),
(HIGH, '!!!'),
]
severity = models.CharField(
max_length=3,
choices=YEAR_IN_SCHOOL_CHOICES,
default=LOW,
)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs = {'pk': self.pk})
urlpatterns = [
path('', ProjectListView.as_view(), name='blog-home'),
path('user/<str:username>', UserProjectListView.as_view(), name='user-projects'),
path('project/<str:title>', ProjectPostListView.as_view(), name='project-posts'),
path('post/<int:pk>/', ProjectDetailView.as_view(), name='project-detail'),
path('post/new/', ProjectCreateView.as_view(), name='project-create'),
path('post/<int:pk>/update/', ProjectUpdateView.as_view(), name='project-update'),
path('post/<int:pk>/delete/', ProjectDeleteView.as_view(), name='project-delete'),
path('about/', views.about, name='blog-about'),
]
class ProjectPostListView(ListView):
model = Post
template_name = 'blog/project_posts.html'
context_object_name = 'posts'
paginate_by = 10
def get_queryset(self):
project = get_object_or_404(Project, title=self.kwargs.get('title'))
return Post.objects.filter(project=project).order_by('-date_posted')
Apologies if some of that code wasn't needed, I am new to Django.
I figured it out by making the model of "ProjectPostListView" into a Project, and then changing that to a DetailView so I could just use all of the post objects associated with that project.
Related
I'm working on a blog and I was following instructions but now I don't understand why I have problem with pk.
This is my views.py
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Category, Post
def post_list(request):
posts = Post.objects.filter(created_at__lte=timezone.now()).order_by('created_at')
latest_posts = Post.objects.filter(created_at__lte=timezone.now()).order_by('created_at')[:9]
context = {'posts': posts, 'latest_posts': latest_posts}
return render(request, 'home.html', context)
def post_detail(request, post, pk):
latest_posts = Post.objects.filter(created_at__lte=timezone.now()).order_by('created_at')[:9]
post = get_object_or_404(Post, pk=pk)
context = {'post': post, 'latest_posts': latest_posts}
return render(request, 'post_detail.html', context)
This is blog/urls.py
urlpatterns = [
path('', views.post_list, name='home'),
path('<slug:post>/', views.post_detail, name='post_detail'),
]
This is models.py
class Post(models.Model):
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at")
updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at")
is_published = models.BooleanField(default=False, verbose_name="Is published?")
published_at = models.DateTimeField(null=True, blank=True, editable=False, verbose_name="Published at")
title = models.CharField(max_length=200, verbose_name="Title")
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey('auth.User', verbose_name="Author", on_delete=models.CASCADE)
category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE)
body = RichTextField(blank=True, null=True)
image = StdImageField(upload_to='featured_image/%Y/%m/%d/', variations={'standard':(1170,820),'banner':(1170,530),'thumbnail':(500,500)})
status = models.IntegerField(choices=STATUS, default=0)
def get_absolute_url(self):
return reverse('post_detail', args=[self.slug])
class Meta:
verbose_name = "Post"
verbose_name_plural = "Posts"
ordering = ['-created_at']
def publish(self):
self.is_published = True
self.published_at = timezone.now()
self.save()
def __str__(self):
return self.title
Also, I'm adding a list of post, it might be connected with get_absolute_url
{% extends "base.html" %}
{% load static %}
{% block content %}
<!-- Main Wrap Start -->
<main class="position-relative">
<div class="post-carausel-1-items mb-50">
{% for post in latest_posts %}
<div class="col">
<div class="slider-single bg-white p-10 border-radius-15">
<div class="img-hover-scale border-radius-10">
<!--<span class="top-right-icon bg-dark"><i class="mdi mdi-flash-on"></i></span>-->
<a href="{{ post.get_absolute_url }}">
<img class="border-radius-10" src="{{ post.image.standard.url }}" alt="post-slider">
</a>
</div>
<h6 class="post-title pr-5 pl-5 mb-10 mt-15 text-limit-2-row">
{{ post.title }}
</h6>
<div class="entry-meta meta-1 font-x-small color-grey float-left text-uppercase pl-5 pb-15">
<span class="post-by">By {{ post.author }}</span>
<span class="post-on">{{ post.created_at}}</span>
</div>
</div>
</div>
{% endfor %}
</div>
</main>
{% endblock content%}
I have an error...
post_detail() missing 1 required positional argument: 'pk'
Everything was working until I was started working on post detail. Any ideas why this is happening?
You seem to be confused with what the primary key for your model is. The primary key is the auto-generated id (pk) but according to your urls.py you want to use slug for fetching records.
First, change your path to:
path('<slug:slug>/', views.post_detail, name='post_detail'),
then your view signature to:
def post_detail(request, slug):
and finally, fetch your record using:
post = get_object_or_404(Post, slug=slug)
I want to put a filter on a page which shows videos selecting an album shows up on album page not all the videos but my current filter is showing all the published videos. I couldn't find a way to put a filter based on slug that if an album's slug is matching with the current url then shows the video selecting that album. For example:- Videos created by Gaurav should only visible on Gaurav’s album not anyone else. I am all confused help me.
models.py
from django.db import models
from django.urls import reverse
STATUS = (
(1, "Publish"),
(0, "Draft")
)
class WatchCategory(models.Model):
title = models.CharField(max_length=20)
slug = models.SlugField(max_length=2000, unique=True)
def __str__(self):
return self.title
class Genre(models.Model):
title = models.CharField(max_length=20)
slug = models.SlugField(max_length=2000, unique=True)
def __str__(self):
return self.title
class Album(models.Model):
title = models.CharField(max_length=2000)
slug = models.SlugField(max_length=2000, unique=True)
image = models.CharField(max_length=2000, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('Watch:album', kwargs={
'slug': self.slug
})
class Video(models.Model):
title = models.CharField(max_length=2000)
slug = models.SlugField(max_length=2000, unique=True)
thumbnail = models.CharField(max_length=2000, unique=True)
updated_on = models.DateTimeField(auto_now=True)
file = models.CharField(max_length=2000)
time = models.CharField(max_length=2000, blank=True)
about = models.TextField(blank=True)
category = models.ManyToManyField(WatchCategory)
album = models.ManyToManyField(Album)
genre = models.ManyToManyField(Genre)
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=1)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('Watch:video', kwargs={
'slug': self.slug
})
views.py
class Album(ListView):
queryset = Video.objects.filter(status=1).order_by('-created_on')
template_name = 'Watch/album.html'
paginate_by = 6
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = 'Explore & Watch your favourite'
return context
album.html
{% extends "Watch/layout.html" %}
{% load static %}
{% block content %}
<div class="video-block section-padding">
<div class="row">
{% for video in video_list %}
<div class="col-xl-3 col-sm-6 mb-3">
<div class="video-card">
<div class="video-card-image">
<a class="play-icon" href="{% url 'Watch:video' video.slug %}"><i class="fas fa-duotone fa-circle-play"></i></a>
<img class="img-fluid" src="{{ video.thumbnail }}" alt="">
<div class="time">{{ video.time }}</div>
</div>
<div class="video-card-body">
<div class="video-title">
{{ video.title }}
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
I have the following conceptual error which I am not undertstanding:
Please have a look at the thrown error:
NoReverseMatch at /watchlist
Reverse for 'auction' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<auction_id>[0-9]+)$']
Request Method: GET
Request URL: http://127.0.0.1:8000/watchlist
This is my urls.py file:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("<int:auction_id>", views.auction, name="auction"),
path("new", views.newItem, name="newItem"),
path("watchlist", views.watchlist, name="watchlist"),
path("addwatchList/<int:auction_id>", views.add_watchlist, name="add_watchlist"),
path("remwatchList/<int:auction_id>", views.rem_watchlist, name="rem_watchlist"),
]
And the views.py file fragment where the errors occurs is this:
#login_required
def watchlist(request):
u = User.objects.get(username=request.user)
return render(request, "auctions/watchlist.html", {
"watcher": u.watchingAuction.all()
})
Assigning the "watcher" variable makes the application brake and show the error message.
Can you please help me out? Where is the conceptual mistake?
Thnkass
This is my Watchlist.html file:
{% extends "auctions/layout.html" %}
{% block body %}
<h2 style="text-align: center;">My Watchlist!</h2>
<hr>
{% if watcher%}
<div class="row">
{% for item in watcher %}
<div class="card" style="width: 18rem;">
<img src="{{item.watchingAuction.url}}" class="card-img-top" alt="..." style="max-height: 200px; min-height: 200px; max-width: 180px; min-width: 180px;">
<div class="card-body">
<h5 class="card-title">{{item.watchingAuction.name}}</h5>
<h6 class="card-title">Price: ${{item.watchingAuction.startBid}}</h6>
<h6 class="card-title">{{item.watchingAuction.owner}}</h6>
<p class="card-text">{{item.watchingAuction.description}}</p>
To Auction
</div>
</div>
{% endfor %}
{% else %}
<h3 style="text-align: center; color:darkslateblue;">No auctions watched so far</h3>
{% endif %}
</div>
{% endblock %}
This is my models.py file:
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class Auction(models.Model):
NOCAT = 'NO'
SURF = 'SU'
KITESURF = 'KI'
WINDSURF = 'WI'
SKI = 'SK'
BASE = 'BA'
CATEGORY_CHOICES = [
(NOCAT, 'Nocat'),
(SURF, 'Surf'),
(KITESURF, 'Kitesurf'),
(WINDSURF, 'Windsurf'),
(SKI, 'Ski'),
(BASE, 'Base'),
]
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="auctionOwner")
name = models.CharField(max_length=64)
description = models.TextField(max_length=200)
startBid = models.FloatField()
currentBid = models.FloatField(blank=True, null=True)
url = models.URLField(blank=True)
watching = models.ManyToManyField(User, blank=True, related_name="watchingAuction")
category = models.CharField(
blank=True,
max_length=2,
choices=CATEGORY_CHOICES,
default=SURF )
def __str__(self):
return f"{self.name} {self.startBid} {self.category}"
def snippet(self):
return self.description[:25] + "..."
class Bids(models.Model):
item = models.ForeignKey(Auction, on_delete=models.CASCADE, related_name="itemBid")
bidder = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bidMan")
bid = models.FloatField()
def __str__(self):
return f"{self.bidder} {self.bid}"
class Comments(models.Model):
comment = models.TextField(max_length=300)
commenter = models.ForeignKey(User, on_delete=models.CASCADE, related_name="userComment")
item = models.ManyToManyField(Auction,blank=True, related_name="speech")
def __str__(self):
return f"{self.commenter} says: {self.comment}"
I found the bug, I was accessing the wrong attributes of each element in the for loop. Now it is solved
I'm building a news web site as a part of a task I was given, homework.
I have a "articles.html" template which renders all of my news articles by publish date.
I added a for loop in the template to loop over the Category model and display Categories as a list.
What I'm trying to do now is to filter my articles by category, so when I click "sports" on the list, my site now displays only sports related articles.
I have read so much online, and I just got confused, I'm supposed to do this today but I'm having a rough day and would appreciate some guidance !
Here are my models.py :
from django.db import models
from datetime import datetime
from autoslug import AutoSlugField
class Category(models.Model):
category_title = models.CharField(max_length=200, default="")
def __str__(self):
return self.category_title
class Article(models.Model):
title = models.CharField('title', max_length=200, blank=True)
slug = AutoSlugField(populate_from='title', default="",
always_update=True, unique=True)
author = models.CharField('Author', max_length=200, default="")
description = models.TextField('Description', default="")
is_published = models.BooleanField(default=False)
article_text = models.TextField('Article text', default="")
pub_date = models.DateTimeField(default=datetime.now, blank=True)
article_image = models.ImageField('Article Image')
article_category = models.ForeignKey(Category, on_delete="models.CASCADE", default="")
img2 = models.ImageField('Article Image 2', default="", blank=True)
img3 = models.ImageField('Article Image 3', default="", blank=True)
img4 = models.ImageField('Article Image 4', default="", blank=True)
img5 = models.ImageField('Article Image 5', default="", blank=True)
img6 = models.ImageField('Article Image 6', default="", blank=True)
def __str__(self):
return self.title
My views.py :
from django.shortcuts import render, reverse, get_object_or_404
from django.views import generic
from news.models import Article, Category
from .forms import CommentForm
from django.http import HttpResponseRedirect
class IndexView(generic.ListView):
template_name = 'news/index.html'
context_object_name = 'latest_article_list'
def get_queryset(self):
return Article.objects.order_by("-pub_date").filter(is_published=True)[:6]
class CategoryView(generic.ListView):
template_name = 'news/categories.html'
context_object_name = 'category'
def get_queryset(self):
return Category.objects.all()
def article(request, article_id):
article = get_object_or_404(Article, pk=article_id)
context = {'article': article}
return render(request, 'news/article.html', context)
class ArticlesView(generic.ListView):
context_object_name = 'latest_article_list'
template_name = 'news/articles.html'
queryset = Article.objects.order_by("-pub_date")
def get_context_data(self, **kwargs):
context = super(ArticlesView, self).get_context_data(**kwargs)
context['category'] = Category.objects.all()
return context
def add_comment_to_article(request, pk):
article = get_object_or_404(Article, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = article
comment.save()
return HttpResponseRedirect(reverse('news:article', kwargs={"article_id": article.pk}))
else:
form = CommentForm()
return render(request, 'news/add_comment_to_article.html', {'form': form})
my urls.py :
from django.urls import path, include
from . import views
app_name = "news"
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:article_id>/', views.article, name='article'),
path('articles/', views.ArticlesView.as_view(), name='articles'),
path('search/', include('haystack.urls')),
path('<int:pk>/comment/', views.add_comment_to_article, name='add_comment_to_post'),
path('category/<int:category_id>', views.CategoryView.as_view(), name="category")
]
And the template im trying to render everything in, articles.html:
<div class="container">
{% block articles %}
<!-- ***************************************** -->
<ul>
<li>Categories:</li>
{% for category in category %}
<li>
<h1>{{ category.id}}</h1>
{{ category.category_title }}
</li>
{% endfor %}
</ul>
<!-- ***************************************** -->
<hr class="hr-style1">
<h2 class="article-list-title">Article List :</h2>
<hr class="hr-style2">
<div class="container list-wrapper">
{% for article in latest_article_list %}
<div class="container">
<div class="well">
<div class="media">
<a class="pull-left" href="{% url 'news:article' article.id %}">
<img class="media-object" src="{{ article.article_image.url }}">
</a>
<div class="media-body">
<h4 class="media-heading">{{ article.title }}
</h4>
<p class="text-right">{{ article.author }}</p>
<p>{{ article.description }}</p>
<ul class="list-inline list-unstyled">
<li><span><i class="glyphicon glyphicon-calendar"></i> {{ article.pub_date }} </span></li>
<li>|</li>
<span><i class="glyphicon glyphicon-comment"></i> 2 comments</span>
<li>|</li>
<li>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star-empty"></span>
</li>
<li>|</li>
<li>
<span><i class="fa fa-facebook-square"></i></span>
<span><i class="fa fa-twitter-square"></i></span>
<span><i class="fa fa-google-plus-square"></i></span>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
Apologies for the messy code, still trying to learn.
Thank you for taking the time to read this !
I'm not asking you to do this for me, an explanation will be enough ! Thanks !
You can override the get_queryset method on your ArticlesView by passing a filter param as follow:
class ArticlesView(generic.ListView):
context_object_name = 'latest_article_list'
template_name = 'news/articles.html'
def get_context_data(self, **kwargs):
context = super(ArticlesView, self).get_context_data(**kwargs)
# It would be best to rename the context to categories
# as you are returning multiple objects
context['categories'] = Category.objects.all()
return context
def get_queryset(self):
# Note you do not have to use the article PK you can use any
# article field just update the template argument accordingly
category_pk = self.request.GET.get('pk', None)
if category_pk:
return Article.objects.filter(article_category__pk=category_pk).order_by("-pub_date")
return Article.objects.order_by("-pub_date")
In your template you can then update the category links as follow:
<ul>
<li>Categories:</li>
{% for category in categories %}
<li>
<h1>{{ category.id}}</h1>
{{ category.category_title }}
</li>
{% endfor %}
<ul>
Give this a try and let me know if it works
How can i render my variables from models in a html file, they was rendering a time ago before I made html link slug with class(DetailView) in my views.py
HTML FILE (product.html)
<h2 class="heading">{{ product.name }}</h2>
<div style="clear: both;"><br></div>
<div class="block">
<div class="img_preview">
<img src="{{ product.img }}">
<div class="categ">
{% for category in product.category.all %}
<span>{{ category }}</span>
{% endfor %}
{# <div style="clear: both"><br></div> #}
</div>
</div>
<div id="links">
{% for link in links %}
<div class="download_link">
<span>DOWNLOAD MIRROR NUMBER {{ links.number }}</span>
</div>
{% endfor %}
</div>
<div style="clear: both"></div>
<div id="games">
<div id="video_trailer">
<iframe width="560" height="317" src="{{ product.video_trailer }}" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe>
<div id="description">
<span class="title">Description</span>
<p>{{ product.description }}</p>
</div>
</div>
<div style="clear: both"><br></div>
<div id="system_requirements">
<span class="title">System Requirements</span><br>
<p>Processor: {{ product.processor }}<br>
<br>
Graphic Card: {{ product.video }}<br>
<br>
Memory: {{ product.ram }}<br>
<br>
Disk Space: {{ product.disk_space }}<br>
<br>
OS: {{ product.oS }}
</p>
</div>
</div>
<div id="screenshots">
{% for image in product_images %}
<div class="screenshot">
<img width="1920px" height="1080px" src="{{ image.image }}" >
</div>
{% endfor %}
</div>
</div>
</div>
<aside>
<div id="news">
<h2 class="heading">News</h2>
<div style="clear: both"><br></div>
{% for articles in news_articles %}
<div id="articles">
<div class="article">
<a href="{{ articles.article.get_absolute_url }}">
<img src="{{ articles.image }}">
<div style="clear: both"></div>
<span></span><div style="clear: both"></div>
</a>
<em>{{ articles.article.created }}</em>
views.py
from django.shortcuts import render
from products.models import *
from news.models import *
from django.shortcuts import get_object_or_404
from django.views.generic.detail import DetailView
class GameLink(DetailView):
# model = Product
# context_object_name = 'product'
def get_object(self):
return get_object_or_404(Product, slug__iexact=self.kwargs['slug'])
class ArticleLink(DetailView):
model = Article
context_object_name = 'article'
def get_object(self):
return get_object_or_404(Article, slug__iexact=self.kwargs['slug'])
def product(request, product_id):
product = Product.objects.get(id=product_id)
product_images = ProductImage.objects.filter(is_active=True, is_main=False, id=product_id)
links = ProductDownload.objects.filter(is_active=True, product=product_id)
news_articles = NewsImage.objects.filter(is_active=True, is_main=True)
return render(request, 'products/product.html', locals())
urls.py
from django.contrib import admin
from django.conf.urls import *
from products import views
from products.views import *
urlpatterns = [
# url(r'^games/(?P<product_id>\w+)/$', views.product, name='product'),
url(r'^games/(?P<slug>[-\w]+)/$', GameLink.as_view(template_name = 'products/product.html'), name='product'),
url(r'^articles/(?P<slug>[-\w]+)/$', ArticleLink.as_view(template_name = 'news/article.html'), name='article')
]
models.py
`
from django.db import models
from django.urls import reverse
class ProductCategory(models.Model):
name = models.CharField(max_length=128, blank=True, null=True, default=None)
is_active = models.BooleanField(default=True)
def __str__(self):
return '%s' % self.name
class Meta:
verbose_name = 'Category'
verbose_name_plural = 'Categories'
class Product(models.Model):
name = models.CharField(max_length=128, blank=True, null=True, default=None)
description = models.TextField(default=None)
processor = models.CharField(max_length=300, blank=True, null=True, default=None)
video = models.CharField(max_length=300, blank=True, null=True, default=None)
ram = models.CharField(max_length=300, blank=True, null=True, default=None)
disk_space = models.CharField(max_length=300, blank=True, null=True, default=None)
oS = models.CharField(max_length=300, blank=True, null=True, default=None)
video_trailer = models.CharField(max_length=10000, blank=True, null=True, default=None)
img = models.CharField(max_length=10000, blank=True, null=True, default=None)
category = models.ManyToManyField(ProductCategory, blank=True, default=None)
is_active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
slug = models.SlugField(primary_key=True, max_length=250, unique=True, default=None)
def __str__(self):
return '%s' % self.name
def get_absolute_url(self):
return reverse('product', args=[str(self.slug)])
class Meta:
verbose_name = 'Game'
verbose_name_plural = 'Games'
class ProductDownload(models.Model):
product = models.ForeignKey(Product, blank=True, null=True, default=None, on_delete=False)
link = models.CharField(max_length=10000, blank=True, null=True, default=None)
is_active = models.BooleanField(default=True)
number = models.PositiveIntegerField(blank=True, default=True)
def __str__(self):
return '%s' % self.product.name
class Meta:
ordering = ['number']
class Meta:
verbose_name = 'Download Link'
verbose_name_plural = 'Download Links'
class ProductImage(models.Model):
product = models.ForeignKey(Product, blank=True, null=True, default=None, on_delete=False)
image = models.CharField(max_length=10000, blank=True, null=True, default=None)
is_main = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
def __str__(self):
return '%s' % self.product
class Meta:
verbose_name = 'Image'
verbose_name_plural = 'Images'
HTML file show only Product variables that are called with {{ product.___ }} but doesn't renders the rest like my links called with :
{% for link in links %}
{{ link.link }}
{% endfor %}
or like my articles...
How should I proceed to render on my page needed models.
Image of file paths
here
There are different forms to add adicional 'variables' using a DetailView (link)
For example:
class GameLink(DetailView):
def get_object(self):
return get_object_or_404(Product, slug__iexact=self.kwargs['slug'])
def links(self):
return ProductDownload.objects.filter(is_active=True, product=self.object)
And in product.html:
{% for link in view.links %}
<div class="download_link">
<span>DOWNLOAD MIRROR NUMBER {{ links.number }}</span>
</div>
{% endfor %}
IF you don't want to change HTML, instead of declaring the "def links(self)":
class GameLink(DetailView):
def get_object(self):
return get_object_or_404(Product, slug__iexact=self.kwargs['slug'])
def get_context_data(self, **kwargs):
context = super(GameLink, self).get_context_data(**kwargs)
context['links'] = ProductDownload.objects.filter(is_active=True, product=self.object)
return context