I'm getting a NoReverseMatch error in my home page - django

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>

Related

Page not found (404) adding a Django page

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'),
]

Django: NoReverseMatch at

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.

trying to use username in urlpattern to give every user a unique link

this my approach if you know how to do it please help
my views.py
def profile(request, username):
return render(request, 'profile.html')
my urls.py
from django.conf.urls import url
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
# Template Urls!
app_name = 'accounts'
urlpatterns = [
path('Skolar/',views.base, name= 'base'),
path('Register/',views.register,name='register'),
path('login/', views.my_login_view, name='login'),
path('logout/',views.user_logout,name='logout'),
path('<slug:username>',views.profile, name='profile'),
path('EditProfile/',views.update_profile,name='editprofile'),
]
error showing
Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['(?P<username>[-a-zA-Z0-9_]+)$']
in my html i use
<a class="dropdown-item" href="{% url 'accounts:profile' %}">My Account</a>
adding profile html which i want ot show user after clickin gon that link
{% extends 'masteraccount.html' %}
{% block content %}
{% load static %}
<link rel="stylesheet" href="{% static 'css/accountscss/profile.css'%}">
<div class="">
<div class="page-content">
<label class="name" for="NAME">NAME:</label>
<p>{{user.first_name}} {{user.last_name}}</p>
<label for="Email">Email:</label>
<p>{{user.email}}</p>
<label for="Twitter">Twitter:</label>
<p>{{user.profile.twitter}}</p>
<label for="Facebook">Facebook:</label>
<p>{{user.profile.Facebook}}</p>
<label for="Facebook">About:</label>
<p>{{user.profile.about}}</p>
<label for="Facebook">Date of Birth:</label>
<p>{{user.profile.dob}}</p>
</div>
<button type="button" class="btn btn-primary btn-lg">Edit Profile</button>
</div>
{% endblock %}
views.py let us assume your model is 'Profile' and your have 'user' related to one-to-one to User you should use something like:
from django.shortcuts import render,get_object_or_404
def profile(request, username):
profile = get_object_or_404(Profile,user = username)
return render(request, 'profile.html',{'profile':profile})
urls.py:
from django.conf.urls import url
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
# Template Urls!
app_name = 'accounts'
urlpatterns = [
path('Skolar/',views.base, name= 'base'),
path('Register/',views.register,name='register'),
path('login/', views.my_login_view, name='login'),
path('logout/',views.user_logout,name='logout'),
path('<slug:username>/',views.profile, name='profile'),
path('EditProfile/',views.update_profile,name='editprofile'),
]
html
<a class="dropdown-item" href="{% url 'accounts:profile' request.user.username %}">My Account</a>
Note:it is always better to use pk for the profile.but slug it is also fine

Django 2.1.5 Authentication (login/logout) breaks on Browser Back-button

I created a simple login logout app using the Out of the box django LoginView and LogoutView. In my app, I can signup using CreateView, list the users using ListView and get user details using DetailView.
I am seeing issues with login and logout when I click the browser's back button.
Issues:
Upon login, I am redirected to index page. However when I click the back button, I land back at login page and can login with other valid user.
Upon logout, I am redirected to index page. However when I click the back button, I can view the logged-in data such as the list page and details page.
The code for my app (accounts) is :
settings.py
<code>
LOGIN_REDIRECT_URL = "/accounts/"
LOGOUT_REDIRECT_URL = "/accounts/"
project urls.py
<code>
urlpatterns = [
path("admin/", admin.site.urls),
path("accounts/", include("django.contrib.auth.urls")),
path("accounts/", include("accounts.urls")),
]
app urls.py
<code>
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts_app'
urlpatterns = [
path("", views.IndexPage_cview.as_view(), name="index_curl"),
path("login/", auth_views.LoginView.as_view(),name='login'),
path("logout/", auth_views.LogoutView.as_view(), name="logout"),
path("signup/", views.SignUp_cview.as_view(), name="signup_curl"),
path("super/", views.adminlist_cview.as_view(), name="super_curl"),
path("superdetail/<int:pk>", views.admindetail_cview.as_view(),
name="super_detail_curl"),
]
app views.py
<code>
from django.contrib.auth import login, logout
from django.urls import reverse_lazy
from django.views.generic import TemplateView,CreateView, ListView,
DetailView
from django.contrib import auth
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import get_object_or_404
from . import forms
class IndexPage_cview(TemplateView):
template_name = "accounts/index.html"
class SignUp_cview(CreateView):
form_class = forms.UserCreate_cform
success_url = reverse_lazy("login") #redirect to /accounts/login/
template_name = "accounts/signup.html"
class adminlist_cview(LoginRequiredMixin,ListView):
template_name = 'accounts/super_list.html'
model= auth.models.User
def get_queryset(self):
return auth.models.User.objects.order_by('username')
class admindetail_cview(LoginRequiredMixin,DetailView):
template_name = 'accounts/super_detail.html'
model= auth.models.User
def get_object(self):
return get_object_or_404(auth.models.User, pk=self.kwargs.get("pk"))
app model.py
<code>
from django.contrib import auth
from django.db import models
class User_cmodel(auth.models.User):
def __str__(self):
return "#{}".format(self.username)
app form.py
<code>
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
class UserCreate_cform(UserCreationForm):
class Meta:
fields = ("username", "email", "password1", "password2")
model = get_user_model()
base.html
<div class="container">
Home
<ul >
{% if user.is_authenticated %}
{% if request.user.is_superuser %}
<li><a href="{% url 'admin:index' %}" >Admin</a></li>
<li><a href="{% url 'accounts_app:super_curl' %}>Db List</a></li>
{% endif %}
<li><a href="{% url 'accounts_app:logout' %}>Log out</a></li>
{% else %}
<li><a href="{% url 'accounts_app:login'%}" >Log in</a></li>
<li>Sign up</li>
{% endif %}
</ul>
</div>
<div class="container mycontent">
{% block content %}
{% endblock %}
</div>
login.html
{% extends "base.html" %}
{% block content %}
<div class="container">
<h1>Login</h1>
<form method="POST" >
{% csrf_token %}
{% form %}
<input type="submit" value="Login" >
</form>
</div>
{% endblock %}
No where in the code, you are making the views available only for logged in user. All your views are accessible by anybody.
If you are using custom Auth backend you can use #login_required decorator from django.contrib.auth.decorators. To ensure the user is logged in before going to the view.
You should read this. https://docs.djangoproject.com/en/2.1/topics/auth/default/#authenticating-users

CSRF token missing or incorrect explanation

i am just a beginner and starting with some tutorials on web, i can not understand why this isn't working for me:
my views.py
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.core.context_processors import csrf
class MainPage(View):
def get(self, request):
return render_to_response("helloworld.html")
class TestHandler(View):
def post(self, request):
q = {}
q.update(csrf(request))
#return render_to_response('test.html', q)
return render_to_response('test.html', {'q':q}, context_instance=RequestContext(self.request))
def get(self, request):
q = self.request.GET.get('q')
return HttpResponse(q)
and my urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from views import MainPage, TestHandler
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^hello$', MainPage.as_view(), name='home'),
url(r'^testform/', TestHandler.as_view()),
url(r'^admin/', include(admin.site.urls)),
helloworld.html
>->-<html>
>->->-<head>
>->->->-<title>Hello, World!</title>
>->->-</head>
>->->-<body>
>->->->-<form method="post" action="/testform/" >
{% csrf_token %}
>->->-<input name="q">
<input type="submit">
</form>
>->->-</body>
>->-</html>
test.html
>-<body>
>-Hello {{q}}
>-</body>
This is running on django 1.6, I read most of post and still can't figure it out.
Unfortunately what you have pasted is a bit of a mess, you are using Class Based Views but yet you have mixed them with function based views (also half of the declarations are missing).
Enable the CSRF Middlware in your settings.py
MIDDLEWARE_CLASSES = (
...
'django.middleware.csrf.CsrfViewMiddleware',
...
)
Fix your views to proper Class Based Views, what you have pasted is totally wrong:
from django.views.generic import CreateView, TemplateView
from django.core.urlresolvers import reverse_lazy
# Create the form in your forms.py
from .forms import (
MyTestForm,
)
class MainPage(TemplateView):
template_name = "test.html"
class TestHandler(CreateView):
form_class = MyTestForm
template_name = "helloworld.html"
success_url = reverse_lazy('home')
Create your form template:
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<form method="post" action="/testform/">
{% csrf_token %}
<input name="q">
<input type="submit">
</form>
</body>
</html>