Django Blog APP comes with an out of the box index.html where it shows a list of all posts.
I need to show this list in a new URL, when I somply copy the html code from index.html and paste onto planoacao.html it doesn´t show anything.
This is the index.html:
{% for post in post_list %}
<div class="card mb-4" style="width: 18rem; ">
{% if post.get_finalizado_display == 'Não' %}
<!--<p class="card-text text-muted h6"> NOK </p>-->
<div class="card-body" style="background-color:#FF0909;">
{% else %}
<!--<p class="card-text text-muted h6"> ok </p>-->
<div class="card-body">
{% endif %}
{% endfor %}
This is my views.py:
from django.views import generic
from .models import Post
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'index.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
class Calendar(generic.DetailView):
model = Post
template_name = 'calendar.html'
class Planoacao(generic.DetailView):
model = Post
template_name = 'planoacao.html'
This is my urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
url(r'^planoacao/', TemplateView.as_view(template_name="planoacao.html")),
url(r'calendar', TemplateView.as_view(template_name="calendar.html")),
url(r'^admin/', admin.site.urls),
url(r'^', include('blog.urls'), name="Blog"),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
How can I show a list of all posts in a different URL? xxx/planoacao.html ? Simply copying the html from index.html doesn´t work.
Note that I don´t want to change the regular index.html post list, I just want to add a second post list page.
It seems you want to show your PostList view at /planoacao, so in urls.py you can hook this path up to that view:
url(r'^planoacao/', PostList.as_view()),
Note that in Django there is no direct link between the path of a view and the template used. You can use any template with any path, all you have to do is define which template to use in the view.
Related
views.py
class CommentCreatView(LoginRequiredMixin, CreateView):
model = Comment
fields = ['text']
template_name = 'home/add-comment.html'
success_url = 'homepage'
def form_valid(self,form):
form.instance.user = self.request.user
post = self.get_object()
form.instance.post = post
return super().form_valid(form)
urls.py
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
from .views import PostCreateView, PostsListView, PostDetailView, CommentCreatView
urlpatterns = [
path('', PostsListView.as_view(), name='homepage'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-and-comments'),
path('post/<int:pk>/comment', CommentCreatView.as_view(), name='add-comment'),
path('creat', PostCreateView.as_view(), name='creat-post')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
add-comment.html
{% extends "home/base.html" %}
{% load crispy_forms_tags %}
<!-- allow us to use crispy filter on any of our forms -->
{% block content %}
<div class="content-section">
<form method="POST">
<!--this method post is to protect our form fromcertain attacks -->
{% csrf_token %}
{{form|crispy}}
<button class="btn btn-outline-danger mt-1 mb-1 mr-1 ml-1" type="submit">Add Comment</button>
</div>
</form>
</div>
{% endblock content %}
So I opens it home/post/6/comment , I see the form and when I submit it. I get this error and the comment isnt saved error screenshot
The .get_object(…) [Django-doc] method will try to find a Comment with as primary key the one you specified in the path (here 6). You do not want to find a comment but the Post with that primary key. You thus should rewrite this to:
class CommentCreatView(LoginRequiredMixin, CreateView):
model = Comment
fields = ['text']
template_name = 'home/add-comment.html'
success_url = 'homepage'
def form_valid(self,form):
form.instance.user = self.request.user
form.instance.post_id = self.kwargs['pk']
return super().form_valid(form)
I have a problem with my class bases views and i can't resolve it! i try to render a web page that show a detailed post. But when i try to route http://127.0.0.1:8000/post/1/ i get this
While when i try get http://127.0.0.1:8000/ is work perfectly fine.
I dont completely don't understand this!
my urls.py
from django.urls import path
from .views import PostListView, PostDetailView
from .models import Post
from . import views
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('about/', views.about, name='blog-about'),
]
my view.py
# pylint:disable=no-member
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post
def home(request):
context = Post.objects.all()
return render(request, {'posts': context})
class PostListView(ListView):
model = Post
context_object_name = 'posts'
ordering = ['-date_posted']
class PostDetailView(DetailView):
model = Post
def about(request):
return render(request, 'blog/about.html', {'title': 'About'})
my post_detail.html
{% extends "blog/base.html" %}
{% block content %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<img class="img-profile" src="{{ object.author.profile.image.url }}" />
<a class="mr-2" href="#">{{ object.author }}</a>
<small class="text-muted">{{ object.date_posted | date:"d F, Y " }}</small>
<hr />
</div>
<h2 class="article-title">{{ object.title }}</h2>
<p class="article-content">{{ object.content }}</p>
</div>
</article>
{% endblock content %}
thanks:)
I think as per my analysis you are writing post_detail.py instead of post_detail.html
This is .html file but my mistake you wrote it .py. That's why it will try to find post_datail.html but it will can't able to find this file and throw 404 page not found error
Nethermin it was a stupid mistakes!!
I just make a request on http://127.0.0.1:8000/post/4/ and it's work;
So post/1-3 just dont dont exit.
Sorry for my stupidity
Why am I getting an error when trying to run my server to access the database to see if my code works? While in my projects folder in Terminal, I ran sudo python manage.py runserver to try to run the server but it doesn't work because of the aforementioned error. I've looked around SO but can't find one directly related to my problem.
I'm guessing my if() statement is the problem.
The error I'm getting says:
RuntimeError: maximum recursion depth exceeded while calling a Python object
Here's my views.py file:
from .models import Album
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.core.urlresolvers import reverse_lazy
from django.views import generic
from django.views.generic import View
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .forms import UserForm
class IndexView(generic.ListView):
template_name = 'music/index.html'
context_object_name = 'all_albums'
def get_queryset(self):
return Album.objects.all()
class DetailView(generic.DeleteView):
model = Album
template_name = 'music/detail.html'
class AlbumCreate(CreateView):
model = Album
fields = ['artist', 'album_title', 'genre', 'album_logo']
class AlbumUpdate(UpdateView):
model = Album
fields = ['artist', 'album_title', 'genre', 'album_logo']
class AlbumDelete(DeleteView):
model = Album
success_url = reverse_lazy('music:index')
class UserFormView(View):
form_class = UserForm
template_name = 'music/registration_form.html'
# display blank form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
#cleaned normalized data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
Here's the error:
File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/urls/resolvers.py", line 255, in check
warnings.extend(check_resolver(pattern))
File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/core/checks/urls.py", line 26, in check_resolver
return check_method()
File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/urls/resolvers.py", line 172, in check
warnings = self._check_pattern_startswith_slash()
File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/urls/resolvers.py", line 140, in _check_pattern_startswith_slash
regex_pattern = self.regex.pattern
Here's my forms.py file:
from django.contrib.auth.models import User
from django import forms
class UserForm(forms.ModelForm): # UserForm inherits from forms.
passwords = forms.CharField(widget=forms.PasswordInput)
class Meta: # Information about your class.
model = User # whenevr a creates sign up to your site it's gonna go in same table
fields = ['username', 'email', 'password']
Here's my urls.py file:
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
app_name = 'music'
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^music/', include('music.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT)
Here's my album_form.html file:
{% extends 'music/base.html' %}
{% block title %}Add a New Album{% endblock %}
{% block album_active %}active{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
<form class="horizontal" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'music/form-template.html' %}
<div class="form-group">
<div class="col-sum-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
Here's my index.html file:
{# loads path to static file #}
{% extends 'music/base.html' %}
{% block body %}
<ul>
{% for album in all_albums %}
<li>{{ album.album_title }}</li>
{% endfor %}
</ul>
{% endblock %}
I suspect you have a recursive reference from your include in music.urls to urls.py since the error that django throws is specific to URL resolver.
Your if statement has no error. 'music:index' refers to namespaced url names and still need named url statements in urls.py. Since in simple projects, there is only one application, the namespace is redundant. So in most cases, 'index' should be used instead, just like what I have show below.
In your urls.py, there is a include to music.urls, and it seems to be recursive reference to itself. 'music.urls' refers to the file urls.py in music directory.
If you do not have a valid python object for 'music.urls', then your include statement is wrong.
I do not use include urls in my project, so there will need to be a statement for each view defined in views.py. To test whether your server starts correctly, I would try the following urlpatterns. Don't forget to import IndexView and DetailView. Add more url statements for you other views after testing out 1 or 2 first.
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^music/index/$', IndexView.as_view() , name='Index'),
url(r'^music/detail/(?P<pk>[0-9]+)/$', DetailView.as_view() , name='Detail'),
]
I use named url, and the statement in index.html should be written as follows:
{{ album.album_title }}
The namespace 'music:' is omitted since it is implicit and will look simpler. You should leave it out for simple applications as it may be confusing for beginners.
Hi everybody!
Im just starting a way of django programming so sometimes really get confused.
I`m trying to display all my objects from DB, but when opening the page its simply empty.
There are content added and I tried ListView previously and it worked for me. But now I need to dislpay objects like a grid and here is an issue with this method.
Will be very thanksfull for any help!
models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=140)
body = models.TextField()
date = models.DateField()
image = models.ImageField(upload_to='bons_images/%Y/%m/%d')
def __str__(self):
return self.title
views.py
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from django.views import generic
from blog.models import Post
def image(request):
post = Post()
variables = RequestContext(request, {
'post': post
})
return render_to_response('blog/post.html', variables)
# class IndexView(generic.ListView):
# template_name = 'blog/blog.html'
# context_object_name = 'all_posts'
#
# def get_queryset(self):
# return Post.objects.all()
def index(request):
posts = Post.objects.all()
return render(request, 'blog/blog.html', {'posts': posts})
urls.py
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post
from blog import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<pk>\d+)$', DetailView.as_view(model=Post, template_name='blog/post.html')),
]
blog.html
{% extends 'base.html' %}
{% block content %}
{% if all_posts %}
{% for post in all_posts %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-lg-4">
<div class="thumbnail">
<a href="/blog/{{ post.id }}">
<h5>{{ post.date|date:'Y-m-d' }} {{ post.title }}</h5>
<img src="{{ post.image.url }}" style="width: 50%; height: 50%"/>
</a>
</div>
</div>
</div>
</div>
{% endfor %}
{% endif %}
{% endblock %}
And by the way, how its possible to display your objects like in grid, not list, using Bootstrap or so on.
Thank you!
You're iterating over something called all_posts in your template. But your view doesn't send anything called all_posts; it only sends posts. You need to use consistent names.
UPDATE #1:
I'm still having some issues, I'm getting some of the content using tags like {{object.title}}, but content that I've included using {% include "sidebar.html" %} and {% include "slider.html" %} are not showing up.
Part of my sidebar.html looks like this:
<div class="navItem">
<div class="overlay">
</div><!-- /.overlay -->
<img src="{{article.relatedImage}}" alt="" class="navPicture">
<p class="navTitle">{{article.title|truncatewords:"4"}}</p>
</div><!-- /.navItem -->
I'm doing a class assignment and I'm using the same tags as I have on my main page on my detailed page in Django, but the actual content on the detailed page is not showing up when I use the {{tags}}.
Snippet of detailed.html
<p class="date">{{article.pubDate|date:"l, F j, Y" }}</p> | {{article.author}}
<img src="{{article.heroImage}}" alt="" class="largeImage">
<div class="contentBlock">
<img src="{{article.relatedImage}}" alt="" class="relatedImage">
views.py
from django.views import generic
from . import models
# Create your views here.
class BlogIndex(generic.ListView):
queryset = models.FullArticle.objects.published()
template_name = "list.html"
class BlogDetail(generic.DetailView):
model = models.FullArticle
template_name = "detailed.html"
urls.py
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.BlogIndex.as_view(), name="list"), url(r'^(?P<slug>\S+)$', views.BlogDetail.as_view(), name="detailed"),
)
Screenshot of list.html: http://imgur.com/vygVAkj
Screenshot of detailed.html: http://imgur.com/umnCE27
You are using {{ article }} in your template. Which is undefined. Either user {{ object }}, either specify context_object_name = 'article' in your Detail View.
Moreover, you are using white spaces for identifying your objects??? i.e. you are doing stuff like models.FullArticle.objects.get(pk=' ') which is really weird.
Mihai zamfir was right.
Here's the full code - this should be in your views.py
class FoodDetail(DetailView)
model = FoodPost
context_object_name = 'post'
template_name = 'views/detail-views/food-details.html'
for urls.py
path('posts/<str:link>/<int:pk>', FoodDetail.as_view(), name="food-detail")
and inside details view
<h1>{{post.pk}}</h1>
and the template from which you are referring should be
read more