Nothing renders on Django Template - python

building a news aggregator. I am collecting reddit and twitter posts using their APIs, and then I create a model object for each post, which is stored in my database. I'm then passing in these post objects as context into my template, looping through the context in the template with the hope to display the posts 'html' attribute (A model field I created) onto the page, which in turn embeds the post onto the screen.
However, I can't figure out why my template page is still blank. No errors are thrown, and the model objects are being created because I can see them in the admin panel. I'll provide my models.py, views.py, and template to be taken a glance at. I appreciate and am grateful for any help/advice.
models.py
class Post(models.Model):
post_type = models.CharField(
max_length=20, null=True, blank=True)
root_url = models.CharField(max_length=200, default="")
html = models.TextField(default="")
created_at = models.DateTimeField(auto_now_add=True)
views.py
def main(request):
all_posts = Post.objects.all
context = {'posts': all_posts}
return render(request, "test.html", context)
template
{% block content %} {% autoescape off %}
<div class="container">
<div class="row">
<div class="col-6">
<h3 class='text-center'>Twitter News</h3>
{% for post in posts %}
{% if post.post_type == 'twitter' %}
<div class="mdl-card__media" id="timeline"></div>
{{ post.html }}
{% endif %}
<br>
{% endfor %}
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>
<div class="col-6">
<h3 class='text-center'>Reddit News</h3>
{% for post in posts %}
{% if post.post_type == 'reddit' %}
<div class="mdl-card__media" id="timeline"></div>
{{ post.html }}
{% endif %}
<br>
{% endfor %}
<script async src="//embed.redditmedia.com/widgets/platform.js" charset="UTF-8"></script>
</div>
</div>
</div>
{% endautoescape %}{% endblock %}
<script async src="//embed.redditmedia.com/widgets/platform.js" charset="UTF-8"></script>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>

In your views.py, your attempt to create a queryset is missing the parenthesis on the all method:
all_posts = Post.objects.all()
You have mentioned in the comments that the <br> tags within the {% for %} loops are being rendered. This would indicate that when you check for {% if post.post_type == 'twitter' %} (and the equivalent for reddit), there are no matches.
Check your Post model in Django admin to ensure you have records with post_type values that equal 'twitter' and 'reddit'.

Related

Django , models object not displayed in views

im newbie in django. I have some question related to models. So, i was trying to display the model name and date to the views by iterating to all of them. But somehow they dont show up in the views, i tried to search in google but none fixed my problem. Im sorry if i asked some ridiculous question, but here is my code.
And also i already checked my models and theyre valid
Models
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
class Post(models.Model):
title = models.CharField(max_length=30)
body = models.TextField()
time_post = models.DateTimeField(auto_now_add=True)
time_edit = models.DateTimeField(editable=False,blank = True)
slug = models.SlugField(editable=False, blank=True)
def save(self):
self.slug = slugify(self.title)
self.time_edit = timezone.now()
super(Post, self).save()
def __str__(self):
return "{}. {}".format(self.id, self.title)
urls
from django.shortcuts import render
from .models import Post
def blog(request):
posts = Post.objects.all(),
context = {
'title':'Blog ',
'contributor':'Chris',
'img':'blog/img/BlogBanner.jpg',
'Post':posts,
'nav': [
['/blog/recent','Recent'],
['/blog/news','News'],
['/blog','Blog'],
['/about','About'],
['/', 'Index']
]
}
return render(request,'blog/blog.html',context)
My blog.html
{% extends "base.html" %}
{% load static %}
{% block app_css %} <!-- Custom CSS per app !-->
<link rel="stylesheet" types="text/css" href = "{% static "blog/css/styleblog.css" %}"> <!-- CSS OVERIDE !-->
{% endblock app_css %}
{% block header %}
<h1 class="display-4">Welcome to {{title}} | ChrisDjango</h1>
<p class="lead">This was made in Django by {{contributor}}</p>
{% endblock header %}
{% block content1 %}
{% for post in Post %}
<h2>{{post.title}}</h2> #THE TITLE AND TIMEPOST DIDNT SHOW UP
<p>{{post.time_post}}</p>
{% endfor %}
{% endblock content1 %}
base.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
{%include "snippets/styles.html"%} <!--Bootstrap!-->
{% block app_css %}
<link rel="stylesheet" types="text/css" href = "{% static "blog/css/styleblog.css" %}"> <!-- Custom CSS per app !-->
{% endblock app_css %}
<title>{{title}} | ChrisDjango</title>
<img id="banner" style="border-bottom: 15px solid #343A40;" src="{% static img %}" alt="Blog Banner">
</head>
<body>
{%include "snippets/navbar.html"%}
<div class="jumbotron">
<div class="container text-white text-center">
{% block header %}
{% endblock header %}
<hr class="my-4">
</div>
</div>
<div class="container-fluid">
<div class="container bg-white text-dark shadow" style="margin-top:-150px" id="myBody">
{% block content1 %}
{% endblock content1 %}
</div>
<div class="container bg-secondary text-white shadow">
{% block content2 %}
{% endblock content2 %}
</div>
</div>
{%include "snippets/scripts.html"%}
</body>
</html>
Sorry if my code looks really weird
Thank you
Let's start with this edit in urls:
posts = Post.objects.all(),
should be
posts = Post.objects.all()
Note the dropped comma.
I have made that mistake MANY times and it is really hard to spot sometimes. Here is what happens when you have a trailing comma (you get an iterable wrapper)
If you still have a problem LMK.
There is a trailing comma at the end of:
posts = Post.objects.all(),
# trailing comma ^
this means you wrap the item in a singleton tuple. It is thus a tuple with one element, the collection of object.
You should remove the comma at the end:
posts = Post.objects.all()
I would furthermore rename 'Post' to posts, since this gives a hit that it is a collection of items.

Not being able to display comments in template

I'm making a Post and Comment model by taking reference from internet. i created and Post and Comment model and it looks ok in django admin panel. i can add post and also a comment to any particular post. but getting trouble when I'm trying to display the comment under the post in templates(under post detail views). PLEASE HELP
models.py
class Post(models.Model):
author = models.ForeignKey(User,on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = RichTextField()
tags = models.CharField(max_length=50,blank=True,null=True)
date_posted = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail',kwargs={'pk':self.pk})
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE)
author = models.ForeignKey(User,max_length=50,on_delete=models.CASCADE)
text = models.TextField()
create_date = models.DateTimeField(default=timezone.now)
def get_absolute_url(self):
return reverse('discuss')
views.py
class PostDetailView(DetailView):
model = Post
def add_comment_to_post(request,pk):
return get_object_or_404(Post,pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post= post
comment.save()
return redirect('post-detail',pk=post.pk)
else:
form = CommentForm()
return render(request, 'discuss/comment_form.html',{'form':form})
def comment_remove(request,pk):
comment = get_object_or_404(Comment,pk=pk)
post_pk = comment.post.pk
comment.delete()
return redirect('post-detail', pk=post_pk)
post_detail.html
{% extends 'index.html' %}
{% block content %}
<article class="media content-section">
<div class="medaia-body">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}" alt="image not found">
<div class="article-metedata">
<a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{object.author}}</a>
<small class="text-muted">{{ object.date_posted|date:"F d, Y"}}</small>
</div>
<h2 class="article-title">{{ object.title }}</h2>
<img class="query-img" src="{{ object.image.url }}" alt="image not found">
<p class="article-content">{{ object.content|safe }}</p>
</div>
</article>
{% if object.author == user %}
<div class="post-update-delete">
<button class="btn btn-outline-primary">Edit Post</button>
<button class="btn btn-outline-primary">Delete Post</button>
</div>
{% endif %}
<hr>
<a class="btn btn-primary btn-comment" href="{% url 'add_comment_to_post' pk=post.pk %}">Add Comment</a>
<!-- ############################### ABOVE CODE IS WORKING ############################# -->
<!-- ########################## GETTING PROBLEM IN BELLOW CODE ######################### -->
{% for comment in object.comments.all %}
{% if user.is_authenticated %}
{{ comment.create_date }}
{{ comment.text|safe|linebreaks }}
{{ comment.author }}
{% endif %}
{% empty %}
<p>No Comment</p>
{% endfor %}
{% endblock %}
in post_deatil.html i also tried {% for comment in post.comments.all %} but it is also not working
Since you did not specify a related_name=… parameter [Django-doc], the related_name is by default comment_set, so you iterate over the comments with:
{% for comment in object.comment_set.all %}
…
{% endfor %}
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

django - How to check choices of an object and display corresponding item on html

I am working on a photo app, which allows one to upload images. From there, there are choice options for each photo -- either "PUBLIC" or "PRIVATE"--. For images that are "PUBLIC", the image will be shown on the home page without need for user authorisation. However, I am finding difficulty in filtering the images based on the choices and display the relevant object on the home page.
I am new to coding and Django, would appreciate some advice here. Thanks in advance!
This is my models.py file:
class Images(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='images/')
PRIVATE ='PR'
PUBLIC = 'PU'
PUBLISH_CHOICES = [
(PRIVATE, 'Private'),
(PUBLIC, 'Public'),]
publish = models.CharField(max_length=7,
choices=PUBLISH_CHOICES,
default=PRIVATE)
def __str__(self):
return self.title
This is my views.py file
class HomePageView(ListView):
model = Images
template_name = 'index.html'
def my_view(request):
myimages = Images.objects.all()
for entry in myimages:
publish_status = entry.get_publish_display()
return publish_status
This is my index.html file:
{% for images in images_list %}
{% if publish_status == Public %}
<div class="container">
<h3>{{images.title}}</h3>
<img src="{{images.image.url}}" alt=" {{images.title}}">
</div>
{% endif %}
{% endfor %}
The generic ListView returns a list of all Images, you can the pass them to the template - as you rightfully did - and then filter by publish field could be PU for Public or PR for Private.
views.py becomes:
class HomePageView(ListView):
model = Images
template_name = 'index.html'
index.html becomes:
{% for images in images_list %}
{% if images.publish == 'PU' %}
<div class="container">
<h3>{{images.title}}</h3>
<h2>{{ images.image.url }}</h2>
<img src="{{ images.image.url }}" alt="{{images.title}}">
</div>
{% endif %}
{% endfor %}
Cheers.
You can get all images, pass them to template and then filter based on publish_status. Below is how it might look like.
views.py:
class HomePageView(ListView):
model = Images
template_name = 'index.html'
index.html:
{% for image in object_list %}
{% if image.publish_status == 'Public' %}
<div class="container">
<h3>{{images.title}}</h3>
<img src="{{images.image.url}}" alt=" {{images.title}}">
</div>
{% endif %}
{% endfor %}
{% for image in object_list %}
{% if image.publish_status == 'Public' %}
<div class="container">
<h3>{{images.title}}</h3>
<img src="{{images.image.url}}" alt=" {{images.title}}">
</div>
{% endif %}
{% endfor %}
Try this. Edit your index.html file

Django: can't access OneToOneField after rendering TemplateView Form

I am new to Django and don't understand what really is causing this:
I have a Model Company which has an OneToOneField, creator.
# models.py
class Company(models.Model):
class Meta:
verbose_name = 'Company'
verbose_name_plural = 'Companies'
creator = models.OneToOneField(User, related_name="company", on_delete=models.CASCADE, unique=False, null=True)
name = models.CharField(max_length=50)
I have a TemplateView class to handle get and post requests for creating a Company model:
# views.py
class create_company(TemplateView):
def get(self, request):
form = CompanyCreateForm()
title = "Some form"
return render(request, "form.html", {"form": form, "title": title})
def post(self, request):
form = CompanyCreateForm(request.POST)
if form.is_valid():
comp = form.save(commit=False)
comp.creator = request.user
comp.save()
return redirect('index')
The form is showing correctly also storing when I submit, the problem I am facing is with base.html where I show {% user.company %}; the form template extends it like:
{% extends "account/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
<form method="post" action="">
{% csrf_token %}
{{form|crispy}}
<button class="btn btn-success" type="submit">Save</button>
</form>
<br>
</div>
<br>
{% endblock %}
and in base.html I access
{% if user.is_authenticated %}
{% user.company %}
{% endif %}
But user.company is not showing even it is set; it shows only when I redirect to index but not when I render the form.
Can someone help me understand what causes this?
{% if request.user.is_authenticated %}
{% request.user.company %}
{% endif %}
you are not sending any context to the base.html, thus only user wont work.
This was the error when I simulated your code.
Error during template rendering
In template /home/user/django/drf_tutorial/snippets/templates/base.html, error at line 2
Invalid block tag on line 2: 'user.company', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?
1 {% if user.is_authenticated %}
2 {% user.company %}
3 {% endif %}
4 {% block content %}{% endblock %}
It gives hint that the code to show company should be variable {{ }} instead of tag {% %}. So the base.html template should be as below.
{% if user.is_authenticated %}
{{ user.company }}
{% endif %}
{% block content %}{% endblock %}

Django: Query Selected Info in Model Within Class Based Views

I created some link with model-slug. But When I click my link, go to the page but return the empty value. I want to When I click any link, It will query value from the selected field like class_name or slug field.
this class list html page
{% extends "result/base.html" %}
{% block title %}Class List Name{% endblock title %} {% block content %}
<div class="row">
<div class="col-md-12 col-xs-offset-4">
<h2>Class List</h2>
{% for object in object_list %}
{{object.class_name}}
{% endfor %}
</div>
</div>
{% endblock %}
this is models.py file
class ClassName(models.Model):
class_name=models.CharField('Class Name', max_length=10)
class_added=models.DateTimeField(auto_now_add=True)
class_updated=models.DateTimeField(auto_now=True)
slug=models.SlugField(max_length=200, unique=True)
def __str__(self):
return self.class_name
this is views.py file
class ClassListView(ListView):
model=ClassName
slug_field = 'slug'
template_name='result/class_list.html'
class ClassDetailView(DetailView):
model=ClassName
slug_field = 'slug'
template_name='result/class_detail.html'
def get_context_data(self,*args, **kwargs):
context = super(ClassDetailView, self).get_context_data(*args,**kwargs)
context['class_wise_std'] = StudentInfo.objects.filter(
student_class_name__class_name__startswith=self.model.slug)
return context
this is class details html page
{% extends "result/base.html" %}
{% block title %}Class Detail's List{% endblock title %}
{% block content %}
<div class="row">
{% for object in class_wise_std %}
<div class="col-lg-12 col-sm-offset-4" style="margin:20px 10px">
<p>Name: {{object.student_name}}</p>
<p>Class: {{object.student_class_name}}</p>
<p>Father's Name: {{object.student_father_name}}</p>
<p>Mother's Name: {{object.student_mother_name}}</p>
<p>Roll: {{object.student_roll}}</p>
</div>
{% endfor %}
</div>
{% endblock content %}
this code
def get_context_data(self,*args, **kwargs):
context = super(ClassDetailView, self).get_context_data(*args,**kwargs)
context['class_wise_std'] = StudentInfo.objects.filter(
student_class_name__class_name__startswith=self.model.slug)
return context
I found this problem happen with this code. I want to filter with class_name field in ClassName Model.
StudentInfo.objects.filter(student_class_name__class_name__startswith=self.model.slug)
But I can successfully query my targeted info this way.
StudentInfo.objects.filter(student_class_name__class_name__startswith='One')
But It is not an efficient way. Now, How can I implement dynamically this?

Categories

Resources