So I am trying to link up a page on my blog. I have created the template, view and URL for the page but it keeps throwing a 404 error. Could someone please look over my code and help me figure out the issue?
add_post.html:
{% extends "base.html" %}
{% block content %}
<header>
<div class="post-caption mt-4">
<div class="text-center-caption">
<h1 class="display-5 fw-bolder text-shadow">Add Your Post</h1>
<p class="lead text-shadow fw-bold">Tell us about your favourite game</p>
</div>
</div>
</header>
{%endblock%}
views.py:
from django.shortcuts import render, get_object_or_404, reverse
from django.views.generic import View, CreateView, ListView
from django.http import HttpResponseRedirect
from .models import Post
from .forms import CommentForm
class AddPost(CreateView):
model = Post
template_name = 'add_post.html'
fields = '__all__'
urls.py:
from .views import AddPost, PostList, PostDetail, PostLike
from django.urls import path
urlpatterns = [
path('', PostList.as_view(), name='home'),
path('<slug:slug>/', PostDetail.as_view(), name='post_detail'),
path('like/<slug:slug>/', PostLike.as_view(), name='post_like'),
path('add_post/', AddPost.as_view(), name='create_post'),
]
The order of the URL pattern is sensitive. You have a "catchall" URL defined with path('<slug:slug>/', PostDetail.as_view(), name='post_detail'),.
Therefor add_post could be a valid slug for a post, which is causing the conflict.
Just change the order of your URL patterns to the following:
from .views import AddPost, PostList, PostDetail, PostLike
from django.urls import path
urlpatterns = [
path('', PostList.as_view(), name='home'),
path('like/<slug:slug>/', PostLike.as_view(), name='post_like'),
path('add_post/', AddPost.as_view(), name='create_post'),
path('<slug:slug>/', PostDetail.as_view(), name='post_detail'),
]
Related
So when I go to the url: http://127.0.0.1:8000/post/2/. instead of showing me the post detail view, it gives me an error. I am so confused about it. However I can see it in list view and in profile page.
Edited: added error image and detail.html
posts views.py
class PostDetailView(LoginRequiredMixin, DetailView):
model = Posts
template_name = 'posts/detail.html'
models.py
class Posts(models.Model):
caption = models.CharField(max_length=2200)
date_posted = models.DateTimeField(default=timezone.now())
image = models.ImageField( upload_to='PostsImages')
user = ForeignKey(User, on_delete=models.CASCADE ,related_name='userposts')
def __str__(self):
return f"Post {self.id} ({self.user.username})'s"
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.image.path)
img.save(self.image.path)
the main urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('posts.urls')),
path('user/', include('users.urls')),
path('comments/', include('comments.urls'))
]
posts urls.py
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import PostsListView, PostCreatView, PostDeleteView, PostDetailView
urlpatterns = [
path('', PostsListView.as_view(), name='homepage'),
path('delete/<int:pk>/', PostDeleteView.as_view(), name='delete-post'),
path('creat-post', PostCreatView.as_view(), name='create-post'),
path('post/<int:pk>/', PostDetailView.as_view(), name='detail-post')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
users urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
from .views import ProfileDetailView
from .views import SignUp, LogOut
urlpatterns = [
path('signup/', SignUp, name='signup'),
path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), #template_name'xx' tells it where to find the log in url
path('logout/', LogOut, name='logout'),
path('<int:pk>/profile', ProfileDetailView.as_view(), name='profile')
]
detail.html
{% extends "posts/base.html" %}
{% block content %}
{{object.user.username}}
<div>
<img class="rounded-circle article-img" src="{{ objetc.user.profile.picture.url }}" />
</div>
{% if user == object.user %}
<div>
Delete Post
</div>
{% endif %}
<img src="{{ object.image.url }}" />
<div>
{{object.user.username}}
</div>
<p>{{object.caption}}</p>
<h6>Comments</h6>
{% for comment in object.comments.all %}
<hr class="bg-danger border-2 border-top border-primary">
{{comment.user.username}}
<p>{{comment.text}}</p>
{% if user == comment.user %}
Delete
Edit
{% endif %}
{% endfor %}
<div>
Add Comment
</div>
{% endblock %}
Change this
{{object.user.username}}
to
{{object.user.username}}
that should work.
I'm getting a NoReverseMatch error in my home page. It is from the html that I injected from my announcement app. It says that the reverse of the link is cannot be found. When I removed that line It shows the card but the text with template tag.
_announcement_home.html:
<div class="container">
<div class="card announcement-card" style="width: 18rem;">
<h5 class="card-header">Announcement</h5>
<div class="card-body">
<h5 class="card-title">{{announcement.title}}</h5>
<p class="card-text">{{announcement.text}}</p>
<span class="announcement-date">{{announcement.date}}</span>
{% if user.is_authenticated %}
Change
{% endif %}
</div>
</div>
<br>
</div>
index.html:
{% extends 'base.html' %}
{% block content %}
<div class="w3-container w3-teal">
<h1>BANNER HERE</h1>
<p>Dito yung banner</p>
</div>
{% include 'announcement/_announcement_home.html' %}
{% endblock %}
urls.py:
from django.urls import path
from . import views
app_name = 'announcement'
urlpatterns = [
path('create/', views.AnnouncementCreateView.as_view(), name='create'),
path('', views.AnnouncementListView.as_view(), name='list'),
path('posts/<int:pk>/', views.AnnouncementDetailView.as_view(), name='single'),
path('delete/<int:pk>/', views.AnnouncementDeleteView.as_view(), name='destroy'),
path('edit/<int:pk>/', views.AnnouncementUpdateView.as_view(), name='edit')
]
main urls.py:
"""urcipro URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from home import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.Home.as_view(), name='home'),
path('bod/', views.BOD.as_view(), name='bod'),
path('announcement/', include('announcement.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
views.py:
from django.shortcuts import render
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy, reverse
from django.contrib import messages
from . import forms
from . import models
# Create your views here.
class AnnouncementListView(LoginRequiredMixin, generic.ListView):
model = models.Announcement
class AnnouncementDetailView(LoginRequiredMixin, generic.DetailView ):
model = models.Announcement
class AnnouncementUpdateView(LoginRequiredMixin, generic.UpdateView):
model = models.Announcement
form_class = forms.AnnouncementForm
class AnnouncementCreateView(LoginRequiredMixin, generic.CreateView ):
model = models.Announcement
form_class = forms.AnnouncementForm
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
class AnnouncementDeleteView(LoginRequiredMixin, generic.DeleteView ):
model = models.Announcement
def get_success_url(self):
return reverse('home')
def delete(self, *args, **kwargs):
messages.success(self.request, "Post Deleted")
return super().delete(*args, **kwargs)
home app views.py:
from django.shortcuts import render
from django.views.generic import TemplateView
# Create your views here.
class Home(TemplateView):
template_name = 'index.html'
class BOD(TemplateView):
template_name = 'bod.html'
This is what I see when I remove the a tag:
Error traceback:
It looks like the context has announcement to display this information, and then you used self in the url tag which isn't defined.
So change the url param to announcement.pk which we can assume will exist because that's the object in use with this block.
<div class="card-body">
<h5 class="card-title">{{announcement.title}}</h5>
<p class="card-text">{{announcement.text}}</p>
<span class="announcement-date">{{announcement.date}}</span>
{% if user.is_authenticated %}
Change
{% endif %}
</div>
I see there are a lot of examples of this error, but I cannot figure out why my code is not working. I am using Django 3.0.3 and I get an error that says NoReverseMatch at /browse/ 'browse' is not a registered namespace in my browse app. It looks to me like I have everything i need, do I need to add a reference to browse somewhere else?
views.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('register', views.register, name='register'),
]
urls.py:
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, "browse/index.html")
def register(request):
return render(request, "browse/register.html")
layout.html:
<a class="dropdown-item" href="{% url 'browse:register' %}">Register</a>
project-wide urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('browse/', include('browse.urls')),
]
remove browse you can do directly like this
<a class="dropdown-item" href="{% url 'register' %}">Register</a>
if you want to use it like
<a class="dropdown-item" href="{% url 'browse:register' %}">Register</a>
then you have to add app_name = 'browse' in urls.py
app_name = 'browse'
urlpatterns = [
path('', views.index, name='index'),
path('register', views.register, name='register'),
]
I am trying to show up my image in django template. But the image is not showing. There is a headline tag which is working fine. I don't know where I am stuck. I searched it here and got a lot of solution, but none of this are not solving my issue.
Here is my views.py:
from django.shortcuts import render
from .models import Post
from django.utils import timezone
# Create your views here.
def home(request):
posts = Post.objects.order_by('id')
return render(request, 'home.html')
Here is my urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from Picture import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.home, name='home')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And this is home.html:
{% load static %}
<html>
<head>
<title>Home Page</title>
<meta charset='utf-8'>
</head>
<body>
<h1>{{ posts.title }}</h1>
<img src="{{ posts.image.url }}" alt="image-{{ post.title }}">
</body>
Images are in the media directory. Please help me to fix my problem.
I see two problems with your code
return render(request, 'home.html') does not have posts context parameter
In your template file posts object is likely to be a queryset, you need to loop through it to render its properties
def home(request):
posts = Post.objects.order_by('id')
return render(request, 'home.html', {"posts":posts})
/deneme.html
<!DOCTYPE html>
<html>
<head>
<title>Doktor Ekleme</title>
<link rel="stylesheet" type="text/css" href="/dosyalar/base.css" />
</head>
<body>
<h1>Doktor Ekle</h1>
<form action="/deneme/" method="POST">
{% csrf_token %}
<input maxlength="50" name="adi" type="text" value=""/>
<input type="submit" value="Gönder" class="default" name="save">
</form>
</body>
</html>
/views.py
from django.http import *
from django.template import RequestContext
def deneme(request):
if request.method=='POST':
adi=request.POST.get('adi')
kaydet=doktor(adi=adi)
kaydet.save()
return render_to_response('deneme.html',context_instance = RequestContext(request))
thats code is not error but not saving
/models.py
from django.db import models
class doktor(models.Model):
adi = models.CharField(max_length='50')
def __str__(self):
return 'adi :%s' %(self.adi)
not error but not saving
/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
import portal_site.views
import yonetim.views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'DernekPortali.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'', include('portal_site.urls')),
url(r'', include('yonetim.urls')),
url(r'^deneme/',yonetim.views.deneme),
)
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
where is error ? that's code. not save database !!
help me plsss
help me plsss
help me plsss
that's code not error but code not saving
dissolved :))))
/.views.py
def deneme(request):
replace
def xx(request):
/.urls.py
url(r'^deneme/',yonetim.views.deneme),
replace
url(r'^deneme/',yonetim.views.xx),
that's error => same variable