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
Related
I am having trouble working with models and forms in Django. A little clarification and help will be highly appreciated!
I am really confused because I do not see the form in my html url page. I see everything else but not the form. I assume, I'm missing something.
This is my forms.py
from django import forms
from .models import TwitterContainer
class TwitterUpdateForm(forms.ModelForm):
class Meta:
model = TwitterContainer
fields = ["Twitter_API_key", "Twitter_API_key_secret", "Twitter_API_token", "Twitter_API_token_secret"]
This is my models.py
from django.db import models
from django.contrib.auth.models import User
class TwitterContainer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
Twitter_API_key = models.fields.CharField(max_length=100)
Twitter_API_key_secret = models.fields.CharField(max_length=100)
Twitter_API_token = models.fields.CharField(max_length=100)
Twitter_API_token_secret = models.fields.CharField(max_length=100)
def __str__(self):
return f'{self.user.username} Twitter Container'
This is my views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import TwitterUpdateForm
#login_required
def twitter(request):
tw = TwitterUpdateForm(request.POST, instance=request.user)
if tw.is_valid():
tw.save()
messages.success(request, f'NICE!')
return redirect ('home')
else:
tw = TwitterUpdateForm(request.POST, instance=request.user)
context = {'tw': tw}
return render(request, 'twitter_container/twitter_container.html', context=context)
And last but not least, this is my html file.
{% extends 'home/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
</div>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset="form-group">
<legend class="border-bottom mb-4">Profile Information</legend>
{{ u_form|crispy }}
{{ p_form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update</button>
</div>
</form>
</div>
{% endblock content %}
Oh, and my urls.py as well.
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('home.urls')),
path('register/', user_views.register, name='register'),
path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
path('profile/', user_views.profile, name='profile'),
path('twitter/', twitter_views.twitter, name='twitter'),
]
The issue, I'm facing is that I'm unable to display the form fields from the model to the html. I want to be able to import information into the fields and update it to the database.
Please, do not judge me hard, I am completely newbie.
Thanks in advance.
First of all, you need to add action attribute in your form tag to call the view function when form gets submitted.
It should be like this:
<form method="POST" action ="{% url 'twitter' %}" enctype="multipart/form-data">
Second thing that i found wrong in your html code is, why did you use u_form and p_form as a context variable? it should be 'tw' as per your view.
Try it out with above changes, it might help you out with your requirements.
I have been facing this issue. And I have a url name post-page-detail but then also getting error please
See the error screenshot below.
My singlepost.html html page
<a href="{% url "post-detail-page" slug=post.slug %}">
<h2>{{post.tractor_company}} || {{post.tractor_model}}</h2>
<pre><h5>{{post.implimentaion}}</h5>
{{post.farmer}}
Uplode Date : {{post.date}}</pre>
</a>
</div>
URLs.py
from . import views
urlpatterns = [
path("",views.starting_page,name = "starting-page"),
path("posts",views.posts,name = "post-page"),
path("posts/<slug:slug>",views.post_detail,name="post-detail-page"),
]
View.py
from django import forms
from django.contrib.auth.models import User
from django.shortcuts import render, redirect ,get_object_or_404
from .models import Post, Farmer
# Create your views here.
from django.http import HttpResponseRedirect
# Create your views here.
def starting_page(request):
return render(request,"tractor/index.html")
def posts(request):
qs = Post.objects.all()
context = {"posts":qs}
return render(request,"tractor/all-post.html",context)
def add_post(request):
pass
def post_detail(request,slug):
indentified_post = get_object_or_404(Post,slug=slug)
return render(request,"blog/post-detail.html",{'post':indentified_post})
i am iterating through posts and using the post-detail.html page
all-post.html.
{% load static %}
{% block title %}
All Tractors
{% endblock %}
{% block content%}
<section id="all_events">
<br>
<h1 style="text-align:center;">All Tractors</h1>
<ul>
{% for post in posts %}
<br>
{% include "tractor/includes/singlePost.html" %}
{% endfor %}
</ul>
</section>
{% endblock %}
Root urls.py
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path("",include(("tractor.urls","tractor"))),
]
The 'tractor' part in the path('', include(('tractor.urls', 'tractor'))) in the include(…) function [Django-doc] specifies the app_namespace. This means that for all URLs you use in the tractor.urls urls, you should prefix this with tractor::
<a href="{% url 'tractor:post-detail-page' slug=post.slug %}">
…
</a>
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.
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.
I started coding with Python and Django last week and now I start getting desperate about it.
I have to work on a To-Do-List and want to delete ToDo task by clicking on a button next to the task.
Now I always get a
NoReverseMatch at /delete/1
error :(
The delete_confirm.html:
{% extends "base_page.html" %}
{% block title %}Confirm Todo delete{% endblock %}
{% block content %}
<form action="" method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ object }}"?</p>
<input type="submit" value="Confirm" />
</form>
{% endblock %}
My Urls.py:
from django.conf.urls import patterns, url
from todolist import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^add', views.AddView.as_view(), name='add'),
url(r'^impressum', views.ImpressumView.as_view(), name='impressum'),
url(r'^edit/(?P<pk>\d+)$', views.UpdateView.as_view(), name='todo_edit'),
url(r'^delete/(?P<pk>\d+)', views.DeleteView.as_view(), name='todo_delete'),
)
The views.py:
from django.shortcuts import render
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse
from django.views import generic
from django.views.generic import TemplateView, ListView, CreateView, UpdateView, DeleteView
from todolist.models import Todo
# Create your views here.
class IndexView(ListView):
template_name = 'index.html'
model = Todo
class ImpressumView(TemplateView):
template_name = 'impressum.html'
class AddView(CreateView):
template_name = 'add.html'
model = Todo
fields = ['title','deadline','progress']
success_url = '/'
class UpdateView(UpdateView):
template_name = 'edit.html'
model = Todo
fields = ['title','deadline','progress']
success_url = '/'
class DeleteView(DeleteView):
template_name = 'delete_confirm.html'
model = Todo
success_url = reverse_lazy('/')
The interesting part of the index.html:
<!--Table content-->
{% for todo in object_list %}
<tr>
<td class="text-left">{{todo.title}}</td>
<td> {{todo.deadline}}</td>
<td>
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="{{todo.progress}}" aria-valuemin="0" aria-valuemax="100" style="width: {{todo.progress}}%">
{{todo.progress}}%
</div>
</div>
</td>
<td >
<div class="btn-group">
Edit
Delete
<button class="btn btn-default" data-toggle="tooltip" title="Done?" data-placement="right"><span class="glyphicon glyphicon-check"></button>
</div>
</td>
{% endfor %}
Would be great if some of your guys could help a newbie :)
The problem is this line in your delete view.
class DeleteView(DeleteView):
...
success_url = reverse_lazy('/')
You can either provide the url:
success_url = '/'
or use reverse_lazy with the url name that you wish to reverse:
success_url = reverse_lazy('index')