I'm using Django with MySQL. I have a Post model. If I execute Post.object.all() in python shell, it shows all the Post objects.
However, when I add
posts = Post.objects.all()
return render(request, 'index.html', {'posts': posts})
in views.py
and
{% for post in posts %}
{{ post.title }}
{% endfor %}
in index.html
I simply can't see the post names on my index page. What's wrong with my codes ? How can I know if I have passed posts to the template successfully?
Related
I'm trying to print my products from sqlite
the problem is that the result in the browser is the code itself and not the value.
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Product
def index(request):
products = Product.objects.all()
return render(request, 'index.html', {'dict': products})
index.html:
<ul>
{% for prod in dict %}
<li>{{ prod.name }}</li>
{% endfor %}
</ul>
The result in the browser is:
{% for prod in dict %}
{{ prod.name }}
{% endfor %}
In order to fix this you need to check index.html by running the server
python manage.py runserver
and going to the url that leads to index.html
if the result in the browser is like the one you said, are you opening the HTML file directly? because if Django rendered the template it wouldn't show this. even if the data is wrong or there is nothing, it'll just display nothing
Goal:
Display POST data on Django-based website as it is received via webhooks from Github
If possible, to continually append new events one after the other on the website
Where I'm at:
I have the github POST data, I can print it on the terminal, but cannot display on my html page.
Currently a beginner with Django but any advice would be much appreciated!
Here's a peak at my views.py:
#csrf_exempt
def home(request):
if request.method == "POST":
event = request.META['HTTP_X_GITHUB_EVENT']
body = json.loads(request.body)[event]
context = {
'event': event,
'body': body,
}
print(context)
return render(request, 'home.html', context)
return render(request, 'home.html')
Here is my home.html
{% extends "base.html" %}
{% block content %}
<div>
<h3><b>fudge</b></h3>
{% if event %}
<p>Event: {{ event }}</p>
<p>Body: {{ body }}</p>
{% endif %}
</div>
{% endblock %}
Ideally, I'd like to re-render my home.html page as soon as a POST is received, but don't know how to keep it persistent. As for my urls.py, I only have ^$, views.home, name='home'. Let me know if you'd like to see anything else!
I got an error,
TemplateDoesNotExist at /app/detail/3/ app/post_detail.html.
I wrote the following:
def top(request):
content = POST.objects.order_by('-created_at')[:5]
page = _get_page(blog_content, request.GET.get('page'))
return render(request, 'top.html',{'content':content,"page":page})
class DetailView(generic.DetailView):
model = POST
def detail(request, pk):
content = POST.objects.get(id=pk)
return render(request, 'detail.html',{'content': content})
in top.html
<div>
{% for content in page %}
<h2>{{ content.title }}</h2>
<p>SHOW DETAIL</p>
{% endfor %}
</div>
in detail.html
<h2>{{ content.title }}</h2>
<p>{{ content.text }}</p>
When I access top.html, ordinary web site is shown, so it is ok. But when I put SHOW DETAIL links the error happens.
I did not write post_detail.html anywhere in my code, so I really cannot understand why post_detail.html causes the mistake.
As a test,I made post_detail.html in same directory with top.html and detail.html, but the same error happens. I want to make a system when I put SHOW DETAIL links, the content's detail is shown.
How should I fix this? What is wrong in my code?
After reading answer,I rewrote DetailView of views.py
class DetailView(generic.DetailView):
model = POST
template_name = 'detail.html'
but when I put SHOW DETAIL links, nothing is shown there.I wrote in detail.html
<h2>{{ post.title }}</h2>
<p>{{ post.text }}</p>
Am I wrong to write the way of detail.html or views.py?How can I show detail's content?
You are using a generic detail view for the POST detail. Generic views do not expect or use a detail() method, and either look for a template as specified in the template_name class attribute or the default which is modelname_detail.html.
You should either make your view a standard function view - like the "top" one - by moving the detail method out of that class; or, remove the method altogether (because it just does what the generic view does already) and either rename your template to post_detail.html or set template_name = 'detail.html'.
I'm getting a NoReverse match error. I've read several posts about this to find the answer, but I'm not seeing a solution.
This is a simple blog webapp for displaying posts in chronological order. The error is related to the edit_post function in "views.py." My suspicion is that the error has to do with trying to store the posts.id as an argument when modifying the post. I've tried removing the post.id in the offending line below and it will load the page. The problem is that if I do that, I cannot load the page for editing specific posts after that.
I don't understand what am I missing. I've looked at a number of posts dealing with this error, and I cannot identify the problem with my specific scenario. Any help is very much appreciated.
My error:
NoReverseMatch at /
Reverse for 'edit_posts' with arguments '('',)' and keyword arguments '{}' >not found. 1 pattern(s) tried: ['edit_posts(?P\d+)/']
Here is the offending line in the home page, "index.html":
<p>
edit post
</p>
Index view:
def index(request):
"""The home page for Blog."""
posts = BlogPost.objects.order_by('date_added')
context = {'posts': posts}
return render(request, 'blogs/index.html', context)
My "urls.py":
urlpatterns = [
# Home page
url(r'^$', views.index, name='index'),
# url(r'^posts/$', views.posts, name='posts'),
# Page for adding a new post.
url(r'^new_post/$', views.new_post, name='new_post'),
# Page for editing posts.
url(r'^edit_posts(?P<posts_id>\d+)/$', views.edit_posts,
name='edit_posts'),
]
edit_posts view:
def edit_posts(request, posts_id):
"""Edit an existing post."""
posts = BlogPost.objects.get(id=posts_id)
if request.method != 'POST':
# Initial request; pre-fill form with the current entry.
form = PostForm(instance=posts)
else:
# POST data submitted; process data.
form = PostForm(instance=posts, data=request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('blogs:index',
args=[posts.id]))
context = {'posts': posts, 'form': form}
return render(request, 'blogs/edit_posts.html', context)
Template for the "edit_posts.html" page:
{% extends "blogs/base.html" %}
{% block content %}
<p>Edit an existing post:</p>
<form action="{% url 'blogs:edit_posts' post.id %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name="submit">save changes</button>
</form>
{% endblock content %}
In your template, posts - as the name implies - is a queryset, ie a list of BlogPost objects. That queryset doesn't have an id attribute; only the individual posts within that list do.
If you want to link to a specific post, you need to loop through that list, and use the id of each post in the loop:
{% for post in posts %}
<p>
edit post
</p>
{% endfor %}
I want to loop data taken from database in rendered template. Using cms plugin.
I dont have problem looping data in html template. But if i use CMSPlugin to insert new app in placeholder, nothing shows.
If i run url localhost:port/test.html.I got input what i want. But rendered template doesnt loop data.
{% for post in posts %}
{{ post.firstoption }}
{% endfor %}
if I use code below, nothing shows in my rendered template. Values are passed in rendered template. Because, if i try {{instance.firstoption}} i get value shown in template. Problem is i cant loop data with tag instance.
{% for post in instance.posts %}
{{ post.firstoption }}
{% endfor %}
I also tried {% for post in instance.posts_set.all %}
and {% for post in instance.posts.all %}
cms_plugins.py
class pricing(CMSPluginBase):
model = mymodel
name = _("myplugin")
render_template = "template.html"
cache = False
def render(self, context, instance, placeholder):
context.update({'instance': instance})
return context
models.py
class mymodel(CMSPlugin):
firstoption = models.CharField(max_length=200)
def __str__(self):
return self.firstoption
It is probably because you need to call all on your posts
{% for post in instance.posts.all %}
{{ post.firstoption }}
{% endfor }