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')
Related
I recently started learning Django. I want to display one news item, but when I open on the link I get an error message:
Cannot resolve keyword 'slug' into field. Choices are: NewsTitles, NewsContent, NewsSlug
Request Method: GET
Request URL: http://127.0.0.1:8000/news/nam-gravida-purus-non/
Django Version: 4.0
Exception Type: FieldError
views.py
from django.views.generic import DetailView
from .models import News
class GetNews(DetailView):
model = News
slug_url_kwarg = 'NewsSlug'
template_name = 'news/single_news.html'
context_object_name = 'single_news'
allow_empty = False
urls.py
from django.urls import path
from .views import GetNews
urlpatterns = [
path('news/<str:NewsSlug>/', GetNews.as_view(), name='news'),
]
models.py
from django.db import models
from django.urls import reverse_lazy
class News(models.Model):
NewsTitles = models.CharField(max_length=120)
NewsContent = models.TextField(max_length=255)
NewsSlug = models.SlugField(max_length=255)
def __str__(self):
return self.NewsTitles
def get_absolute_url(self):
return reverse_lazy('news', kwargs={'NewsSlug': self.NewsSlug})
What am I doing wrong?
First of all do not call your slug "NewSlug" with uppercase but all lower case "newslug" or even better "new_slug", the name itself should be more descriptive as well.
Finally you need to tell your view which field to use, you can define that with the following attribute :
slug_field = "NewSlug"
Note : Attribute of a class should not be camel case but snake case
I am learning to develop and trying to develop a screen in django 1.1 and I am getting this error below. I already took a look at some stacks I already looked at httpresponse, however, I was not successful
could someone help me and explain what could be wrong?
I'm getting this error on the console:
Internal Server Error: /gerencia-margem/list
Traceback (most recent call last):
File "/home/murilo/virtualenv/intranet_erp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 131, in get_response
response = middleware_method(request, response)
File "/home/murilo/virtualenv/intranet_erp/local/lib/python2.7/site-packages/django/middleware/locale.py", line 38, in process_response
if (response.status_code == 404 and not language_from_path and
AttributeError: 'HistoricoComissao' object has no attribute 'status_code'
[18/Nov/2020 13:30:06] "GET /gerencia-margem/list HTTP/1.1" 500 77145
This is models,
# -*- coding: utf-8 -*-
from django.db import models
class HistoricoComissao(models.Model):
class Meta:
verbose_name = u'Historico Comissão'
verbose_name_plural = u'Historico Comissões'
pednum = models.CharField(max_length=40, blank=True)
margem = models.DecimalField(decimal_places=4, max_digits=15, null=True, blank=True)
data = models.DateTimeField()
historico = models.TextField((u'Historico HTML'), blank=True)
status = models.PositiveSmallIntegerField(choices=[(1, 'Em Aberto'),
(3, 'Pendente'),
(4, 'Finalizado'),])
def __unicode__(self):
return str(self.pednum)
this is the views
from django.views import View
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from ..models import HistoricoComissao
def listview(request):
template_name = 'comissao/margenslist.html'
comissoes = HistoricoComissao.objects.all
context = {
'comissoes': comissoes
}
return render(request,template_name,context)
this is urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^list$', views.HistoricoComissao, name='historico_comissao'),
]
In your urls.py you use as view HistoricoComissao, but that is a re-export of a Django model, not of a view. You should use the listview:
from django.conf.urls import url
from . import views
urlpatterns = [
# link to a view function ↓
url(r'^list$', views.listview, name='historico_comissao'),
]
I am learning to develop and trying to develop a screen in django 1.1.
Please upgrade. Django-1.1 was end of life before 2013. Furthermore a lot of things have changed in the meantime (and often improved).
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.
I'm creating a simple blog application and I am trying to convert django rest api. But, I got this error
TypeError at /user/api/ hasattr(): attribute name must be string
Exception Type: TypeError at /user/api/
Exception Value: hasattr(): attribute name must be string
this is my models.py file
from django.conf import settings
from django.db import models
from django.urls import reverse
class BlogPost(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
blog_title=models.CharField(max_length=200)
blog_description=models.TextField()
blog_pub=models.DateTimeField(auto_now_add=True)
blog_update=models.DateTimeField(auto_now=True)
def __str__(self):
return self.blog_title
def get_absolute_url(self):
return reverse('blog:blog_post', kwargs={'pk': self.pk})
this is my serializers.py file
from rest_framework import serializers
from blog.models import BlogPost
class BlogPostSerializer(serializers.ModelSerializer):
class Meta:
fields=(
'author',
'blog_title',
'blog_description',
),
model=BlogPost
This is views.py file
from blog.models import BlogPost
from .serializers import BlogPostSerializer
from rest_framework import generics
from . import serializers
from . import serializers
class BlogPostListAPI(generics.ListCreateAPIView):
queryset=BlogPost.objects.all()
serializer_class=BlogPostSerializer
class BlogPostListAPIDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = BlogPost.objects.all()
serializer_class = serializers.BlogPostSerializer
this is urls.py file
from django.urls import path,include
from .views import SignUpForm, UserProfiles
from .api.views import *
urlpatterns = [
path('signup/', SignUpForm.as_view(), name='signup'),
path('profile/', UserProfiles.as_view(), name='profile'),
path('api/', BlogPostListAPI.as_view(), name='asad'),
path('api/<int:pk>', BlogPostListAPIDetail.as_view()),
]
this is screenshot
As #MaNKuR pointed out in a comment to the question, you have an additional comma in your serializer definition at the end of Meta.fields:
class BlogPostSerializer(serializers.ModelSerializer):
class Meta:
fields=(
'author',
'blog_title',
'blog_description',
),
Because of this, Meta.fields is now a "tuple of tuple of strings" instead of just a "tuple of strings".
When iterating over fields, instead of the expected three string elements
1. 'author'
2. 'blog_title'
3. 'blog_description'
you get only one element that is not a string
1. ('author', 'blog_title', 'blog_description')
Hence, the internal code of the Serializer complains that it did not get a string like it is supposed to get.
I'm making a blog and learning django as I go. I'm trying to incorporate urls that include both sluglines and post ids.
When I click on the "view on site" link in the admin panel, I get this error:
NoReverseMatch at /admin/r/7/2/ Reverse for 'article' with arguments '(u'test-post-3', '2')' and keyword arguments '{}' not found. 0 pattern(s) tried: []
When I manually enter the url, I get this error:
TypeError at /articles/test-post-3,2/ get_object_or_404() takes at least 1 argument (0 given)
Here's my code:
views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
# Create your views here.
from articles.models import Content
class IndexView(generic.ListView):
template_name = 'articles/index.html'
context_object_name = 'latest_articles_list'
def get_queryset(self):
return Content.objects.filter(
published_date__lte=timezone.now()
).order_by('-published_date')[:5]
def detail(request, slugline, id):
article = get_object_or_404(pk=id)
return render(request, 'articles/detail.html', {'article': article})
urls.py:
from django.conf.urls import patterns, url
from articles import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name = 'index'),
#url(r'^(?P<slugline>[-\w\d]+), (?P<pk>\d+)/$', views.DetailView.as_view(), name='detail')
url(r'^(?P<slugline>[-\w\d]+),(?P<id>\d+)/$', view=views.detail, name='article'),
)
models.py:
from django.db import models
from django.db.models import permalink
from django.utils import timezone
import datetime
# Create your models here.
class Content(models.Model):
title = models.CharField(max_length=100, unique=True)
slugline = models.SlugField(max_length=100, unique=True)
body = models.TextField()
published_date = models.DateTimeField('date published')
def __unicode__(self):
return self.title
#permalink
def get_absolute_url(self):
# return ('article', (), {
# 'slugline': self.slugline,
# 'id': self.id,
# })
from django.core.urlresolvers import reverse
return reverse('article', args=[self.slugline, str(self.id)])
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.published_date <= now
was_published_recently.admin_order_field = 'published_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
main urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'the_Bluntist.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^articles/', include('articles.urls', namespace="articles")),
url(r'^admin/', include(admin.site.urls)),
)
You have a bad usage of get_object_or_404:
Docstring:
get_object_or_404(klass, *args, **kwargs)
Uses get() to return an object, or raises a Http404 exception if the object
does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
Note: Like with get(), an MultipleObjectsReturned will be raised if more than one
object is found.
You can make as following:
article = get_object_or_404(Article, pk=id)
article = get_object_or_404(Article.objects, pk=id))
article = get_object_or_404(Article.objects.all(), pk=id))
article = get_object_or_404(Article.objects.filter(pk=id))
article = get_object_or_404(pk=id)
You must pass the model and the filter to the call. Documentation here.
article = get_object_or_404(klass, pk=id)