Page not found (404) Request Method: GET Request URL:
http://127.0.0.1:8000/like/?csrfmiddlewaretoken=UJ6I7mm2cjjSXK0MeuOLqm4E7OfMKTKtO461mCAsnTPdXT0UVw1z3JfMqijyIJAM&blog_id=
Raised by: blog.views.like_post
No Blog matches the given query.
I was making a like section for my blog app and this error is displayed below are my views, models and urls files
views.py
from django.shortcuts import render,get_object_or_404
from django.views.generic import ListView
from .models import Blog
class BlogsList(ListView):
model=Blog
template_name='blog/home.html'
context_object_name='blogs'
ordering=['-date_posted']
def like_post(request):
post= get_object_or_404(Blog, id=request.POST.get('blog_id'))
post.likes.add(request.user)
return HttpResponseRedirect(Blog.get_absolute_url())
models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Blog(models.Model):
title=models.CharField(max_length=100)
content=models.TextField()
date_posted=models.DateTimeField(default=timezone.now)
author=models.ForeignKey(User, on_delete=models.CASCADE)
likes=models.ManyToManyField(User,related_name='likes',blank=True)
def __str__(self):
return self.title
urls.py
from django.urls import path
from . import views
from django.conf.urls import url
urlpatterns=[
path('',views.BlogsList.as_view(),name='blog-home'),
url(r'^like/$', views.like_post, name='like_post')
]
Your view function like_post is the culprit here.
The like_post should be called with a POST method and passed a request parameter blog_id. I don't see where do you do this.
I suggest you to rewrite the view function:
def like_post(request, blog_id):
post = get_object_or_404(Blog, id=blog_id)
# the rest can stay unchanged
and in the urls.py change the following line:
url(r'^like/$', views.like_post, name='like_post')
to:
path('<int:blog_id>/like/', views.like_post, name='like_post')
Mixing the new path and the old url doesn't look very nice to me. Now you can pass the blog_id in the URL and the view will take care to return 404 NOT FOUND if a blog doesn't exist.
Related
Hi i am trying to make blog website but while i fetch model with blogpost function in views.py its shows error that 404 page not found like ||Using the URLconf defined in mac.urls, Django tried these URL patterns, in this order: admin/ shop/ blog/ [name='BlogHome'] blog The current path, blog/blogpost, didn't match any of these. ||
-until i don't create model it works fine but after creating model and trying to fetch articles through post_id it throws error as page not found!
-what am i missing?
-Here is the codes i am using.
code of blog/urls.py ->
from django.urls import path
from . import views
urlpatterns = [
path(" ", views.index, name="ShopHome"),
path("blogpost/<int:id>/", views.blogpost, name="blogpost")]
code of blog/Views.py ->
from django.shortcuts import render
from .models import Blog
# Create your views here.
from django.http import HttpResponse
def index(request):
return render(request, 'blog/index.html')
def blogpost(request,id):
post= Blog.objects.filter (post_id=id)[0]
print(post)
return render(request, 'blog/blogpost.html',{'post':post})
code of blog/adminpy ->
from django.contrib import admin
from .models import Blog
admin.site.register(Blog)
code of blog/models.py ->
from django.db import models
# Create your models here.
class Blog(models.Model):
post_id = models.AutoField(primary_key= True)
title = models.CharField(max_length=50)
title0 = models.CharField(max_length=500,default='')
title1= models.CharField(max_length=500,default='')
title2= models.CharField(max_length=500,default='')
Content_title= models.CharField(max_length=500,default='')
Content_title0= models.CharField(max_length=500,default='')
Content_title1= models.CharField(max_length=500,default='')
Content_title2= models.CharField(max_length=500,default='')
pub_date = models.DateField()
image = models.ImageField(upload_to='shop/images', default="")
def __str__(self):
return self.title
You are passing an /<int:id>/ (btw always include the last trailing slash in your urls /) but your path says /blog/blogpost with a str parameter where it should be an int representing the id of an existing Blogpost instance.
I'm very new to Django and a bit overwhelmed by the documentation. I think my problem is pretty simple but everything i've found just confused me more.
I am building a little news app with a model NewsItem:
from django.db import models
from django.utils import timezone
# Create your models here.
class NewsItem(models.Model):
title = models.CharField(max_length=50)
newsText = models.TextField()
dateEntered = models.DateTimeField('date entered')
datePublished = models.DateTimeField('date published', blank=True, null=True)
user = models.CharField(max_length=30) #temporary field. will be changed to user foreign key
def __str__(self):
return self.title
def publish(self):
if (self.datePublished == None):
self.datePublished = timezone.now()
def published(self):
return self.datePublished != None
two views (technically 3) index and detail
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.views import generic
from .models import NewsItem
# Create your views here.
class IndexView(generic.ListView):
template_name = 'news/index.html'
context_object_name = 'latestNewsList'
def get_queryset(self):
return NewsItem.objects.order_by('-datePublished')[:5]
#todo
class DetailView(generic.DetailView):
model = NewsItem
template_name = 'news/detail.html'
def publish(request, itemId):
newsItem = get_object_or_404(NewsItem, pk=itemId)
newsItem.publish()
newsItem.save()
return HttpResponseRedirect(reverse('news:detail', args=(newsItem.id,)))
and an urlconf like this
from django.urls import path
from . import views
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:itemId>/publish', views.publish, name='publish'),
]
In the detail view i have a link Publish which just triggers the function views.publish. This view is supposed to redirect back to the detail view.
What i'm trying to do now is to display a little message (like article successfully published) in detail view when it was redirected by the publish view. But i have no idea what would be a good aproach
I could just render the details template in the publish view, but then it would still say news/publish in the URL instead of news/detail
Thanks in advance for your help
Have a look at the messages framework. You could add a success message before redirecting, which will be displayed on the next page.
from django.shortcuts import redirect
from django.contrib import messages
def publish(request, itemId):
newsItem = get_object_or_404(NewsItem, pk=itemId)
newsItem.publish()
newsItem.save()
messages.success(request, "The post has been published")
return redirect('news:detail', newsItem.id)
Note that I've simplified the return statement to use redirect(...) instead of HttpResponseRedirect(reverse(...)).
Hi Everyone i make a blog with django but i need to register use and always i get this error:
AttributeError at /register/
'register' object has no attribute 'get'
i already search too many times but i don't get correct answer so make sure don't mark as a duplicate
Here is my Views.py
from django.shortcuts import render , get_object_or_404,redirect
from django.utils import timezone
from blog.models import *
from blog.forms import *
from django.contrib.auth.decorators import login_required
from django.urls import reverse_lazy
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.\
def user_register(request):
if request.method == "POST":
reg = register(data=request.POST)
if reg.is_valid():
user = reg.save()
user.set_password(user.password)
user.save()
else:
print(register.errors)
else:
reg = register()
return render(request,'register.html',{'reg':reg})
Here is my Models.py
class register(models.Model):
user = models.OneToOneField(User,on_delete="Cascade")
Here is my Forms.py
class register(forms.ModelForm):
class Meta():
model = User
fields = ('username','email','password')
I'm Wating For Your Answers!
Providing yoururls.py file would be helpful, but for the time being I'm going to assume it looks something like this:
urls.py
urlpatterns = [
path('register/', views.user_register, name='register'),
]
Either way, the issue is that your user_register function does not know how to handle GET requests (i.e. when you visit the URL which calls this function). You should define logic within user_register to handle a GET request. Something like this:
def user_register(request):
if request.method == "POST":
reg = register(data=request.POST)
if reg.is_valid():
user = reg.save()
user.set_password(user.password)
user.save()
else:
print(register.errors)
>if request.method=='GET':
> # do something
return render(request,'register.html',{'reg':reg})
I'm new to Django and have used generic views for all my projects so far. I've called them in the url.py code with
patterns(r'^url$',DetailView.as_view())
However, now I'm trying to make my own class based views and am having trouble at it. I tried making a simple test where I call a model.py function from my view, but I get an error that I haven't instantiated an instance of the class. How should I instantiate the view class? Also, how come I don't get the same error when calling DetailView.as_view() the DetailView class isn't instantiated either, right?
My code:
models.py
class Post(models.Model):
title = models.CharField(max_length=140)
body = models.TextField()
def __unicode__(self):
return self.title
def getBody(self):
return self.body
view.py
class RatingView(generic.DetailView):
model = Post
template_name = "like.html"
def __init__(self):
model = Post
template_name = "like.html"
def modelFuncTest(self):
return HttpResponse(self.model.getBody())
url.py
from django.conf.urls import patterns, include, url
from django.views.generic import ListView, DetailView
from blog.views import RatingView
from blog.models import Post
urlpatterns = patterns('',
url(r'^(?P<pk>\d+)/like/$', RatingView.modelFuncTest()),
)
Change your views.py to be just:
class RatingView(generic.DetailView):
model = Post
template_name = "like.html"
and change urls.py to be:
from django.conf.urls import patterns, url
from blog.views import RatingView
urlpatterns = patterns('',
url(r'^(?P<pk>\d+)/like/$', RatingView.as_view()),
)
and that should get you started, let me know if there are errors after making these changes.
There are some good examples in the django docs if you haven't seen them yet.
EDIT: Also, in the template, you should get your body like this:
{{ post.body }}
The beauty of the Class-based views is that the context of your object gets passed for you.
You still need to call the as_view() function on your class in your urlpatterns:
urlpatterns = patterns('',
url(r'^(?P<pk>\d+)/like/$', RatingView.as_view()),
)
As for this:
Also, how come I don't get the same error when calling DetailView.as_view() the DetailView class isn't instantiated either, right?
The as_view() function is a class method, which returns an instance of the view class that can be called when your URL pattern is hit.
I'm a amature django web developer. I have a problam with Django. this error is "cats() got an unexpected keyword argument 'pk'".
please see my codes and help me.
Request Method: GET
Request URL: http://127.0.0.1:8000/1
Django Version: 1.6.5
Exception Type: TypeError
Exception Value:
cats() got an unexpected keyword argument 'pk'
Exception Location: /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response, line 112
Python Executable: /usr/bin/python
Python Version: 2.7.6
models.py
from django.db import models
from taggit.managers import TaggableManager
class Category(models.Model):
title = models.CharField(max_length=40)
def __unicode__(self):
return self.title
class Post (models.Model):
title = models.CharField(max_length=150)
body = models.TextField()
date = models.DateTimeField()
tags = TaggableManager ()
cats = models.ManyToManyField(Category)
def __unicode__ (self):
return self.title
urls.py
from django.conf.urls import include, url, patterns
from django.views.generic import ListView, DetailView
from blog.models import Post, Category
urlpatterns = patterns('blog.views',
url(r'^$',ListView.as_view(
queryset = Post.objects.all().order_by("-date")[:2],
template_name="index.html")),
url(r'^(?P<pk>\d+)$', 'cats', name='cats'),
)
views.py
from blog.models import Post,Category
from django.shortcuts import render_to_response
from django.template import RequestContext
def cats(request):
queryset = Post.objects.all().order_by("-date")
navitem = Category.objects.all().order_by("title")
return render_to_response('post.html',{'queryset':queryset,'navitem':navitem},context_instance=RequestContext(request))
The problem is in this line in urls.py:
url(r'^(?P<pk>\d+)$', 'cats', name='cats')
You are sending to the view an argument that it doesn't need.
You can include the pk argument in the view parameters, like this:
def cats(request, pk):
or this:
def cats(request, pk=None):
Or, even better, you can use a different pattern in your URL, without capturing it (because you are not using that pk value at all in your view, you don't need to create a variable for it), like this:
url(r'^(\d+)$', 'cats', name='cats')