For loop on Django Template - python

I'm having a huge issue on making for loop on django templates,for some reasone it dont show on the page the categories that i create on database
urls.py
app_name = 'statenews'
urlpatterns = [
path('', views.home, name="home"),
path('', views.category, name = 'category'),]
models.py
class Category(models.Model):
name = models.CharField(max_length=65)
...
class News(models.Model):
...
category = models.ForeignKey(
Category, on_delete=models.SET_NULL, null=True, blank=True,
default=None,
)
views.py
def category(request):
categories = Category.objects.all()
return render(request,'partials/footer.html',{
'categories': categories
})
html template
<div class="col-lg-3 col-md-6 mb-5">
<h4 class="font-weight-bold mb-4">Tags</h4>
{% for category in categories %}
<div class="d-flex flex-wrap m-n1">
({category.name})
</div>
{% endfor %}
</div>

You have two url paths with same url. Change it to:
urlpatterns = [
path('', views.home, name="home"),
path('categories', views.category, name = 'category')
]
Then enter via yourdomain.com/categories. Otherwise it will always show home view.
EDIT:
In you homepage you can simply see home view as it is set in url with ''. If you want to see categories as footer part, then you have to change your home template, render it with {% include 'partials/footer.html' %}. Then you have to pass categories in home view context.

Related

Output is not rendered on Django template for the same model whose output is rendered on another template

I am really new to Django and I am building a website while learning it. As per requirements, I have to show some news articles on both the home page and on another page that I navigate from the navbar. I have shown the articles list and individual details with the loop in my template files. Problem is, although I have written the for loop for rendering the news article on the home page, nothing is showing up. Following are my models.py, views.py, app/urls.py, and project/urls.py files :
#models.py
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from taggit.managers import TaggableManager
from ckeditor.fields import RichTextField
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
# slug = models.SlugField(max_length=250, unique_for_date='publish')
slug = models.CharField(_("Slug"), max_length=200)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
body = RichTextField()
# image_header = models.ImageField(unique=True, default=timezone.now)
publish = models.DateTimeField(default=timezone.now)
# created = models.DateTimeField(auto_now_add=True)
# updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:details', args=[self.slug])
class News(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
news_title = models.CharField(max_length=250) unique_for_date='nw_publish', unique=True, null=True)
slug = models.SlugField(max_length=300, unique_for_date='nw_publish')
news_author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='news_posts')
news_body = RichTextField()
image_header = models.ImageField(upload_to='featured_image/%Y/%m/%d/', null=True, blank=True)
nw_publish = models.DateTimeField(default=timezone.now)
nw_status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
news_tags = TaggableManager()
class Meta:
ordering = ('nw_publish',)
def __str__(self):
return self.news_title
def get_absolute_url(self):
return reverse('news:news_detail', args=[self.slug])
#views.py
from django.views import generic
from django.views.generic import ListView, DetailView
from django.http import Http404
from .models import Post, Report, News, Member, Project
class Home(ListView):
model = Post
context_object_name = 'home'
template_name = 'blog/home.html'
class HomeDetail(generic.DetailView):
model = Post
context_object_name = 'details'
template_name = 'blog/details.html'
class NewsListView(ListView):
model = News
context_object_name = 'newss'
template_name = 'blog/news.html'
class NewsDetailView(DetailView):
model = News
context_object_name = 'news'
template_name = 'blog/news_detail.html'
#app/urls.py
from django.urls import path, re_path
from . import views
from .views import Home, HomeDetail, Contact, ReportListView, ReportDetailView, NewsListView, NewsDetailView
app_name = 'blog'
urlpatterns = [
# post views
path('', Home.as_view(), name='home'),
path('home/<slug:slug>/', HomeDetail.as_view(), name='details'),
path('news/', NewsListView.as_view(), name='news_list'),
path('news/<slug:slug>/', NewsDetailView.as_view(), name='news_detail'),
path('contact/', Contact.as_view(), name='contact'),
]
#project/urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls', namespace='blog')),
path('ckeditor/', include('ckeditor_uploader.urls')),
path('members/', include('blog.urls', namespace='members')),
path('news/', include('blog.urls', namespace='news')),
path('contact/', include('blog.urls', namespace='contact')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Now my template file for new list has the following block of codes and the objects are rendered :
<div class="row">
{% for news in newss %}
<div class="col-lg-4 wow fadeInUp" data-wow-delay="100ms">
<!--News Two Single-->
<div class="news-two__single">
<div class="news-two__img-box">
<div class="news-two__img">
{% if news.image_header %}
<img src={{ news.image_header.url }} alt="{{ news.news_title }}">
{% endif %}
<a href={{ news.get_absolute_url }}>
<i class="fa fa-plus"></i>
</a>
</div>
<div class="news-two__date">
<p>{{ news.nw_publish |date:"M d, Y" }}</p>
</div>
</div>
<div class="news-two__content">
<ul class="list-unstyled news-two__meta">
<li><i class="far fa-user-circle"></i> {{ news.news_author }}</li>
</ul>
<h3>
<a href={{ news.get_absolute_url }}>{{ news.news_title }}</a>
</h3>
<p class="news-two__text">{{ news.news_body | truncatechars:110 | safe }}</p>
</div>
</div>
</div>
{% endfor %}
</div>
On my home page, I need to achieve something like the following:
news page
I added the following code to render the object, but it's blank:
<div class="row">
<div class="col-xl-6 col-lg-6">
{% for news in newss %}
<div class="news-one__left">
<div class="news-one__img">
<img src={% static "assets/images/blog/news-one-img-1.jpg" %} alt="">
<a href="{{news.get_absolute_url}}">
<i class="fa fa-plus"></i>
</a>
</div>
<div class="news-one__bottom">
<ul class="list-unstyled news-one__meta">
<li>20 Jan, 2021</li>
<li><span>/</span></li>
</ul>
<h3 class="news-one__title">
{{ news.news_title }}
</h3>
</div>
</div>
{% endfor %}
</div>
</div>
The output looks like this:
homepage
My Django version is 3.27.2 and my python version is 3.6.8.
Sorry for such a silly question. I am trying to achieve:
All the news articles both on the home page and news page as a list
Show the first news in the left box and the rest of the 3 or 4 news in the right side box
But the output of the loop is not visible as per the attached image. Please point me to what I am doing wrong here. I am stuck for a while. Thanks in advance.

Why my URL doesn't activate view in django?

Here is the thing i'm trying to do:
There are few tv channels as image links and they will have some information inside channels.
I managed to create tv channels as a list, they look like a link but they don't work like link.
I've created slug area for each channel that takes from it's own name and generates slug auto. And with get_absolute_url i take it's url in the below code you'll see;
This is my model :
class Channels(models.Model):
name = models.CharField(max_length=50, null=False, blank=False, verbose_name="Tv Kanalı")
logo = models.ImageField(upload_to="channels/images/", verbose_name="Tv Logosu", blank=False)
slug = models.SlugField(null=True, unique=True, editable=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Channels, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('channel-list:campaigns', kwargs={'page_slug': self.slug})
This is my main urls:
urlpatterns = [
path('admin/', admin.site.urls),
url(r'', include(('tvekstra.apps.core.urls', 'home'), namespace='home')),
url(r'^user/', include(('tvekstra.apps.user.urls', 'login'), namespace='user')),
url(r'^channels/', include(('tvekstra.apps.tvchannels.urls', 'main'), namespace="channel-list")),
This is channels urls:
urlpatterns = [
url(r'', views.channel_list, name='channels'),
url(r'^(?P<page_slug>[-\w]+)/$', views.campaign_list, name='campaigns'),
]
This is my views:
def channel_list(request):
channels = Channels.objects.all()
return render(request, 'channel.list.html', {'channels': channels})
def campaign_list(request, page_slug):
channel = get_object_or_404(Channels, slug=page_slug)
return render(request, 'campaign.list.html', {'channel': channel})
And this is my template:
{% for channel in channels %}
<div class="col-3 text-center channels">
<a href="{{ channel.get_absolute_url }}">
<img src="{{ channel.get_image }}" alt="Channel Image" class="ch-img">
{{ channel.name }}
</a>
</div>
{% endfor %}
As you can see, a href is channel's getabsoluteurl method. It creates the html but it doesn't go forward page.
I think view is not working for some reason, requesting aid...
url(r'', matches '', but it also matches /channels/fox/ and /something-else/.
You can fix it by adding ^$ to the regex.
url(r'^$', views.channel_list, name='channels'),
In Django 2.0+, it would be better to use re_path, because url is deprecated in Django 3.1:
re_path(r'^$', views.channel_list, name='channels'),
And it would be simpler to use path:
path('', views.channel_list, name='channels'),

Including an Item Context to a Post Model to activate if statement in Django

I am trying to add an Item to a list view, the UserPost list view has already a Post context.
In my project, a user can add a post and add an item each is a different app with different models.
So In my UserPost list view, I have my Posts looped related to a specific user related to it.
What I am trying to do is check if this post.user has an item filtered by the same user and if it does exist a button show appears in the page linking to another page with this list of items related to this user.
To be more descriptive I want to check for Item for the designer__post and link to this page which is {% url 'core:designer-posts' item.designer %}
I hope this clears my question if there are any more clarifications required or code please let me know to add it.
I tried to use make use of an Exists subquery [Django-doc] but I didn't succeed it perfecting it
Here is the models.py
class Post(models.Model):
designer = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
Here is the views.py
class UserPostListView(ListView):
model = Post
template_name = "user_posts.html"
context_object_name = 'posts'
queryset = Post.objects.filter(admin_approved=True)
paginate_by = 6
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return Post.objects.filter(designer=user, admin_approved=True).order_by('-date_posted')
Here is the template user_posts.html
{% if item %}
<a class="primary btn-lg" href="{% url 'core:designer-posts' item.designer %}" role="button">Go to items</a>
{% else %}
<a href="{% url 'core:designer-posts' item.designer %}">
<button type="button" class="btn btn-primary btn-lg btn-block">Go to items</button>
</a>
{% endif %}
here is the item models.py
class Item(models.Model):
designer = models.ForeignKey(
User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
here is the designerlist views.py that I am trying to link to from the user post view if it is available
class DesignerPostListView(ListView):
model = Item
template_name = "designer_posts.html"
context_object_name = 'items'
paginate_by = 6
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return Item.objects.filter(designer=user).order_by('-timestamp')
Here are the views related to the post model
app_name = 'score'
urlpatterns = [
path('', PostListView.as_view(), name='score'),
path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
]
Here are the views related to the item model
app_name = 'core'
urlpatterns = [
path('', HomeView.as_view(), name='home'),
path('user/<str:username>', DesignerPostListView.as_view(),
name='designer-posts'),
]
Projects URLs
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')),
path('', include('core.urls', namespace='core')),
path('score/', include('score.urls', namespace='score')),
path('register/', user_views.register, name='register'),
]
First, you need to pass one context variable by overriding the get_context_data(...) method, that decides whether the user has Items or not
class UserPostListView(ListView):
# rest of your code
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
has_items = Item.objects.filter(designer__username=self.kwargs['username']).exists()
context['has_items'] = has_items
return context
Then in your template, use this has_items variable by,
{% if has_items %}
<a class="primary btn-lg" href="{% url 'core:designer-posts' username=view.kwargs.username %}" role="button">Go to items</a>
{% endif %}
Also, you were not passing the username to the url tag, it should be
{% url 'core:designer-posts' username=view.kwargs.username %}
here, I used view.kwargs.username to get the username from the URL
References
ListView.get_context_data(...)
url tag with kwargs
in {% url %} item.designer passes a user object you have to provide id for that like this
<a href="{% url 'core:designer-posts' item.designer.id %}">

How to display image from model in Django

To be clear, I have tried researching this on my own but since I'm still very new to Django I am unable to understand the solutions here. I also have read the documentation and I don't understand what I'm doing wrong. I cannot get the images located in the "ad_pictures" directory to display in the HTML.
Here's my code:
settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py (project)
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('accounts.urls')),
url(r'^classifieds/', include('classifieds.urls')),
] +static(settings.MEDIA_URL, document_ROOT=settings.MEDIA_ROOT)
urls.py (classifieds app)
from django.conf.urls import url
from . import views
app_name = 'classifieds'
urlpatterns = [
url(r'^create/', views.create, name='create'),
url(r'^latestads/', views.latestads, name='latestads'),
]
models.py
class Post(models.Model):
title = models.CharField(max_length=150)
price = models.CharField(max_length=100)
body = models.TextField()
pub_date = models.DateTimeField(null=True)
author = models.ForeignKey(User, null=True)
category = models.CharField(max_length=150, null=True)
picture = models.ImageField(upload_to='ad_pictures', default='')
latestads.html
{% for post in posts.all %}
<div class="advertisements">
<div class="a-title">
<h3>{{ post.title }}</h3>
</div>
<div class="a-image">
<img src="{{ post.picture.url }}">
</div>
<div class="a-content">
<p>{{ post.body }}</p>
</div>
<div class="a-date">
<p>{{ post.pub_date }} by {{ post.author }}</p>
</div>
</div>
<img src="{{ post.image.url }}">
{% endfor %}
Picture of directory structure:
here
Html output:
here
I'm sure part of the problem is the "post.picture.url" in the HTML.
Any insight is greatly appreciated.
Thanks
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('accounts.urls')),
url(r'^classifieds/', include('classifieds.urls')),
] +static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
please change document_ROOT to document_root

Reverse for 'details' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['entry\\/(?P<pk>[0-9]+)$']

I have this error:
Reverse for 'details' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['entry\/(?P[0-9]+)$']
On line number 7:
From _calender_entry.html
<div class="calender_entry col-lg-4">
<h2> {{ entry.name }} </h2>
<h4> {{ entry.date }} </h4>
<p>
{{ entry.description }}
</p>
<button onclick="window.location='{% url 'details' pk=entry.id %}'" class="btn btn-primary"> View Details </button>
</div>
This is from my urls.py file:
urlpatterns = [
path('', views.index, name='index'),
path('entry/<int:pk>', views.details, name='details'),
path('admin/', admin.site.urls),
]
And here is method from views.py :
def index(request):
entries = Entry.objects.all()
return render(request, 'myapp/index.html', {'entries' : entries})
def details(request, pk):
entry = Entry.objects.get(id=pk)
return render(request, 'myapp/details.html', {'entry' : entry})
Here is models.py
class Entry(models.Model):
name = models.CharField(max_length=100)
date = models.DateTimeField()
description = models.TextField()
created = models.DateTimeField( auto_now_add = True )
def __str__(self):
return f'{self.name} {self.date}'
The _calender_entry.html is included in index.html file as follows:
{% block content %}
<div class="container">
<div class="row">
{% for entry in entries %}
{% include 'myapp/_calender_entry.html' %}
{% endfor %}
</div>
</div>
Could anyone be able to tell me how could I fix this problem?
now django forces you that each app has its own urls.py.
Create the urls.py file in the myapp/ directory
# myapp/urls.py
from django.urls import path
from myapp import views
urlpatterns = [
path('', views.index, name='index'),
path('entry/<int:pk>/', views.details, name='details'),
]
the urls.py of the project has to be as follows
# calenderproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(('myapp.urls', 'myapp'), namespace='myapp')),
]
use in the template as follows
# myapp/_calender_entry.html
View Details
that's how it works, I've checked
I found the error, delete this code from the template _calender_entry.html
<!-- {% include 'myapp/_calender_entry.html' %} -->
although this commented with html django equal it executes it to comment in the template uses {# {% include 'myapp / _calender_entry.html'%} #} in this way django does not execute it

Categories

Resources