Django , models object not displayed in views - python

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.

Related

Nothing renders on Django Template

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'.

Making search bar in django

Im trying to make a search bar in django and watched several youtube totorials and none of those worked. What im trying to do is either make a search bar that redirects to articles/what_you_searched_for or if not possible show up results that include search. If someone has enough time they can tell me how to do both :).
in views.py:
def index(request):
queryset = article.objects.all()
number_of_records = article.objects.count()
random_page = random.randint(1,number_of_records)
context = {
"object_list": queryset,
"random_page": random_page
}
# query = ""
# if request.GET:
# query = request.GET['q']
# context['query'] = str(query)
entries = util.list_entries()
return render(request, "encyclopedia/index.html", context)
#{
#"entries": util.list_entries(),
#"random_page": random_page,
#})
def dynamic_articles_view(request, my_id):
obj = article.objects.get(id= my_id)
number_of_records = article.objects.count()
random_page = random.randint(1,number_of_records)
context = {
"object": obj,
"random_page": random_page
}
return render(request, "encyclopedia/article_detail.html", context)
in index.html:
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia
{% endblock %}
{% block body %}
<h1 id="demo" onclick="add_article()">Article</h1>
<ul>
{% for instance in object_list %}
<li>{{instance.title}}</li>
{% endfor %}
</ul>
{% endblock %}
layout.html: ------------ SEARCH BAR HERE ---------
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet">
</head>
<body>
<div class="row">
<div class="sidebar col-lg-2 col-md-3">
<h2>Wiki</h2>
<form action = "/articles/{{q}}"> __________EXACTLY HERE ________
<input class="search" type="text" name="q" placeholder="Search...">
</form>
<div>
Home
</div>
<div>
<a href = "/new_article" >Create New Article</a>
</div>
<div>
Random Page
</div>
{% block nav %}
{% endblock %}
</div>
<div class="main col-lg-10 col-md-9">
{% block body %}
{% endblock %}
</div>
</div>
</body>
</html>
urls:
from django.contrib import admin
from django.urls import include, path
from encyclopedia import views
from encyclopedia.views import index, new_article, dynamic_articles_view
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("encyclopedia.urls")),
path('new_article/', new_article),
path('home/', index, name = 'home'),
path('articles/<int:my_id>/', dynamic_articles_view, name = 'articless')
]
encyclopedia urls (other folder):
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("", views.new_article, name="new_article")
]
if needed i will comment models and forms but i dont want to make my question to long.
Simplest way is to add a GET form in your template with a search input without setting the action of the form:
<form action="">
<input type="text" name="search" placeholder="Search by title" value="{{request.GET.title}}">
<input type="submit" value="Search">
</form>
Then in the views.py in the you get the value. If it's given, you filter by it:
def dynamic_articles_view(request):
context['object_list'] = article.objects.filter(title__icontains=request.GET.get('search'))
return render(request, "encyclopedia/article_detail.html", context)

Django - Problem with Implementing Models and Views in My PhoneReview Application

I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models. I have already created models for:
Brand – details on brand, such as, name, origin, manufacturing since, etc
Model – details on model, such as, model name, launch date, platform, etc
Review – review article on the mobile phone and date published, etc
Many-to-many relationship between Review and Model.
Now, I have to create views for the following:
a. An index page that display all Brands available for mobile phone in the
database
b. A phone model page that display model when a brand is selected.
c. A detail page when a model is selected that contain reviews and newslink
I have managed to create view for "a. An index page that display all Brands available for mobile phone in the database." However, I am stuck with "b. A phone model page that display model when a brand is selected."
I have managed to display the phone model page. However, the name of the phone model is not being displayed. So, I feel that there is a problem with either the views or templates. But I don't get any error while running the server. So, I am a bit confused.
Here are the codes of models.py of the PhoneReview app.
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Brand(models.Model):
brand_name = models.CharField(max_length=100)
origin = models.CharField(max_length=100)
manufacturing_since = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return self.brand_name
class PhoneModel(models.Model):
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
model_name = models.CharField(max_length=100)
launch_date = models.CharField(max_length=100)
platform = models.CharField(max_length=100)
def __str__(self):
return self.model_name
class Review(models.Model):
phone_model = models.ManyToManyField(PhoneModel, related_name='reviews')
review_article = models.TextField()
date_published = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, null=True, blank=True)
def __str__(self):
return self.review_article
Here are the codes of urls.py of the PhoneReview app:
from . import views
from django.urls import path
urlpatterns = [
path('index', views.BrandListView.as_view(), name='brandlist'),
path('phonemodel/<int:pk>/', views.ModelView.as_view(), name='modellist'),
]
Here are the codes of views.py of the PhoneReview app:
from django.views import generic
from .models import Brand, PhoneModel
class BrandListView(generic.ListView):
template_name = 'PhoneReview/brandlist.html'
context_object_name = 'all_brands'
def get_queryset(self):
return Brand.objects.all()
class ModelView(generic.DetailView):
model = PhoneModel
template_name = 'PhoneReview/phonemodel.html'
Here are the codes of base.html file. As the name suggests, this is the base page. It will be extended for being used by the other pages, like brandlist.html for showing phone brand list and phonemodel.html for showing phone models. It is located inside templates > GameReview folder:
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %} {% endblock %}</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<style>
/* Remove the navbar's default margin-bottom and rounded borders */
.navbar {
margin-bottom: 0;
border-radius: 0;
}
/* Add a gray background color and some padding to the footer */
footer {
background-color: #f2f2f2;
padding: 25px;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Phone Radar</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active">#</li>
<li>Add Phone</li>
<li>Add Review</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-log-in"></span> Login</li>
</ul>
</div>
</div>
</nav>
<div class="jumbotron">
<div class="container text-left">
{% block content %} {% endblock %}
</div>
</div>
</body>
</html>
Here are the codes of brandlist.html file, which displays the list of the phone brands. It located inside templates > GameReview folder. I have managed to display the phone brands at http://127.0.0.1:8000/index.
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Brand List
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Brand List Page</h1>
<ul>
{% for brand in all_brands %}
<li>{{ brand.brand_name }}</li>
{% endfor %}
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
Here are the codes of phonemodel.html file, which is supposed to display the phone brands. However, I can't display the output of {{ phonemodel.model_name }} at http://127.0.0.1:8000/phonemodel/1/. It just shows the H1 heading. The file is located inside templates > GameReview folder.
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Phone Model Page
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Phone Model Page</h1>
<ul>
{% for phonemodel in all_phonemodel %}
<li>{{ phonemodel.model_name }}</li>
{% endfor %}
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
I am stuck here. The phonemodel.html is supposed to display the phone brands. However, I can't display the output of {{ phonemodel.model_name }} at http://127.0.0.1:8000/phonemodel/1/. It just shows the H1 heading. There are no errors showing. I tried several hours to fix it. But being a Django beginner, I am facing a hard time fixing it.
Your phonemodel template is totally wrong. Not only do you not have anything called all_phonemodel in the template context, even if you did it wouldn't be iterable because this is a detail view, not a list view.
Remove the loop and just access object:
<ul>
<li>{{ object.model_name }}</li>
</ul>
Add this to your "class ModelView":
context_object_name = 'all_phonemodel'
def get_queryset(self):
return PhoneModel.objects.all()

render page is wrong

When I accessed upload_save method,basic.html was showed.
I wrote(changed into) in view.py like
def upload_save(request):
photo_id = request.POST.get("p_id", "")
if (photo_id):
photo_obj = Post.objects.get(id=photo_id)
else:
photo_obj = Post()
files = request.FILES.getlist("files[]")
photo_obj.image = files[0]
photo_obj.save()
return render(request, "registration/accounts/photo.html")
photos = Post.objects.all()
context = {
'photos': photos,
}
return render(request, 'registration/accounts/photo.html', context)
So,I naturally thought when I accessed upload_save method,photo.html would be showed.
In photo.html,I wrote
{% extends "registration/accounts/base.html" %}
{% block body %}
<div class="container">
{% for photo in photos %}
<h2 class="page-header">{{ photo.title }}</h2>
<div class="row">
<div class="col-xs-4">
<img class="img-responsive" src="/media/{{ photo.image1 }}">
</div>
<div class="col-xs-4">
<img class="img-responsive" src="/media/{{ photo.image2 }}">
</div>
<div class="col-xs-4">
<img class="img-responsive" src="/media/{{ photo.image3 }}">
</div>
</div>
<a class="btn btn-primary" href="{% url 'accounts:upload' photo.id %}">UPLOAD</a>
{% endfor %}
</div>
{% endblock %}
I wrote
base.html in photo.html ,but I cannot understand why photo.html's content is not show.
By Google Verification,I found only base.html was showed in my page.(So,photo.html could not be read)
How can I fix this?
You did not provide photos to your template. The {% for photo in photos %} is trying to loop over something that has not been provided. You need to add photos to the template context like so:
# ... rest of your view
photos = Post.objects.all()
context = {'photos': photos}
return render(
request, "registration/accounts/photo.html", context=context
)
Reference: render()
I think you did not include block body in base.html. if not included add these lines in base.html where you want to add photo.html content
{% block body %}
{% endblock %}
base.html should be look like this
{% load staticfiles %}
<html>
<head>
<title>Hello</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="{% static 'css/blog.css' %}">
</head>
<body>
<div class="page-header">
<h1>Photo list</h1>
</div>
<div class="content container">
<div class="row">
<div class="col-md-8">
{% block body %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>

Django Form is not visible in Inherited template

I am using template inheritance in my django project. I used form in my base html page and submit button, When i inherit base template to another template form get disappeared but submit button is still there. I have below templates.
base.html
<head>
{% load static from staticfiles %}
<link rel="stylesheet" href="{% static "bootstrap.css" %}">
</script>
</head>
<body>
{% block option %}
<div class="row">
<div class="col-lg-3">
<form method = "post" action="">
{% csrf_token %}
{{form}}
<input type="submit" value="Submit" />
</form>
</div>
</div>
{% endblock %}
<div class="row">
{% block content %}{% endblock %}
</div>
</body>
chart.html
{% extends 'base.html' %}
{% block content %}
<head>
{% load static from staticfiles %}
<link rel="stylesheet" href="{% static "bootstrap.css" %}">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
</script>
</head>
<div id="container" align="center">
{{ column_chart.as_html }}
{% endblock %}
How can i make form visible there in chart html??
EDIT: Added Views
views.py
def select_chart_form(request):
form = SelectChart(request.POST)
if form.is_valid():
if (str(form.cleaned_data['status']) == '1'):
#print "Hello Naresh reverse('chart1')"
return HttpResponseRedirect('/chart1/')
if (str(form.cleaned_data['status']) == '2'):
return HttpResponseRedirect('/chart2/')
context = {
'form' : form
}
return render(request, 'base.html', context)
def video_by_user(request):
analysis = VideoData.objects.annotate(watches_count = Count('user')).order_by('-watches_count')[:10]
data_source = ModelDataSource(analysis,fields=['video_name', 'watches_count'])
column_chart = gchart.ColumnChart(data_source,options={'title': "Top 10 Videos watched by No. Of Users"})
context = {
"data_source": data_source,
"column_chart": column_chart,
}
return render_to_response('chart.html', context)
I am calling video_by_user method..after click on submit button.
The select_chart_form and video_by_user views are completely separate. The first one renders just base.html, and supplies the form variable when it does so. The second one renders chart.html, which inherits from base.html, but it only supplies the variables needed for chart.html itself: it doesn't provide the form needed for base.html. You will need to supply that in video_by_user.

Categories

Resources