由于python?或JSON,在/object\u post//处发生KeyError?
你好,由于某种原因,我在object_post收到keyrerror。 我相信keyError意味着它没有正确导入数据,但我不知道代码出了什么问题。如果有人有主意,我将不胜感激。我猜我的python代码是错的,但我在谷歌搜索了一下,有人说这是JSON的问题。我不是JSON方面的专家(如果是这样的话,问题会更大)…我会发布我的代码,假设我的代码有问题 错误消息:在/'object\u list'处出现KeyError 代码: views.py 头版 Models.py由于python?或JSON,在/object\u post//处发生KeyError?,python,json,django,Python,Json,Django,你好,由于某种原因,我在object_post收到keyrerror。 我相信keyError意味着它没有正确导入数据,但我不知道代码出了什么问题。如果有人有主意,我将不胜感激。我猜我的python代码是错的,但我在谷歌搜索了一下,有人说这是JSON的问题。我不是JSON方面的专家(如果是这样的话,问题会更大)…我会发布我的代码,假设我的代码有问题 错误消息:在/'object\u list'处出现KeyError 代码: views.py 头版 Models.py class Post(mod
class Post(models.Model):
category = models.ForeignKey(Category)
created_at = models.DateTimeField(auto_now_add = True)
title = models.CharField(max_length = 100)
content = FroalaField()
url = models.URLField(max_length=250, blank=True)
moderator = models.ForeignKey(User, default="")
rank_score = models.FloatField(default=0.0)
with_votes = PostVoteCountManager()
views = models.IntegerField(default=0)
image = models.ImageField(upload_to="images",blank=True, null=True)
slug = models.CharField(max_length=100, unique=True)
objects = models.Manager() # default manager
def save(self, *args, **kwargs):
self.slug = uuslug(self.title, instance=self, max_length=100)
super(Post, self).save(*args, **kwargs)
def __unicode__(self):
return self.title
# for redirecting URL so slug is always shown
def get_absolute_url(self):
return '/%s/%s' % (self.id, self.slug)
def set_rank(self):
# Based on HN ranking algo at http://amix.dk/blog/post/19574
SECS_IN_HOUR = float(60*60)
GRAVITY = 1.2
delta = now() - self.submitted_on
item_hour_age = delta.total_seconds() // SECS_IN_HOUR
votes = self.votes - 1
self.rank_score = votes / pow((item_hour_age+2), GRAVITY)
self.save()
class Vote(models.Model):
voter = models.ForeignKey(User)
post = models.ForeignKey(Post)
def __unicode__(self):
return "%s voted %s" % (self.voter.username, self.post.title)
完全错误:
键错误在/
“对象列表”
请求方法:获取
请求URL:
Django版本:1.8.4
异常类型:KeyError
异常值:
“对象列表”
异常位置:/home/younggue/Desktop/ebagu0.2/rclone/main/views.py,在get\u context\u数据中,第25行
Python可执行文件:/home/younggue/Desktop/ebagu0.2/env/bin/Python
编辑3:
我修改过的观点
class IndexListView(ListView):
model = Post
queryset = Post.with_votes.all()
template_name = 'main/index.html'
def get_context_data(self, **kwargs):
context = super(IndexListView, self).get_context_data(**kwargs)
if self.request.user.is_authenticated():
voted = Vote.objects.filter(voter=self.request.user)
posts_in_page = [post.id for post in context["object_list"]]
voted = voted.filter(post_id__in=posts_in_page)
voted = voted.values_list('post_id', flat=True)
context.update({
'voted' : voted,
'latest_posts': Post.objects.all().order_by('-created_at'),
'popular_posts': Post.objects.all().order_by('-views'),
'hot_posts': Post.objects.all().order_by('-score')[:25],
'categories': Category.objects.all(),
})
从此处发生错误
@login_required
def add_category(request):
if request.method == 'POST':
form = CategoryForm(request.POST)
if form.is_valid():
form.save(commit=True)
return IndexListView(request)
else:
print form.errors
else:
form = CategoryForm()
return render(request, 'main/add_category.html', {'form':form})
I provided one argument request and the error says I provided two: TypeError at /add_category/
""__init__() takes exactly 1 argument (2 given).
So I googled it and people say it's from urls.py
urls.py """
urlpatterns = [
url(r'^$', IndexListView.as_view(), name='index'),
#url(r'^add_post/', views.add_post, name='add_post'),
url(r'^add_post/$', PostCreateView.as_view(), name='post-add'),
url(r'^(?P<slug>[\w|\-]+)/edit/$', PostUpdateView.as_view(), name='post-edit'),
url(r'^(?P<slug>[\w|\-]+)/delete/$', PostDeleteView.as_view(), name='post-delete'),
url(r'^add_category/', views.add_category, name='add_category'),
url(r'^(?P<slug>[\w|\-]+)/$', views.post, name='post'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/$', CategoryDetailView.as_view(), name='category'),
]
I have IndexListView.as_view().
why is this error happening?
@需要登录\u
def添加_类别(请求):
如果request.method==“POST”:
表单=类别表单(request.POST)
如果form.is_有效():
保存(commit=True)
返回IndexListView(请求)
其他:
打印表单错误
其他:
表单=类别表单()
返回呈现(请求'main/add_category.html',{'form':form})
我提供了一个参数请求,错误是我提供了两个:TypeError at/add_category/
“”\uuuu init\uuuuuu()正好接受1个参数(给定2个)。
所以我在谷歌上搜索了一下,人们说它来自url.py
URL.py”“”
URL模式=[
url(r'^$',IndexListView.as_view(),name='index'),
#url(r“^add\u post/”,views.add\u post,name='add\u post'),
url(r“^add”\u post/$”,PostCreateView.as\u view(),name='post-add'),
url(r'^(?P[\w | \-]+)/edit/$',PostUpdateView.as\u view(),name='post-edit'),
url(r'^(?P[\w | \-]+)/delete/$,PostDeleteView.as\u view(),name='post-delete'),
url(r“^add\u category/”,views.add\u category,name='add\u category'),
url(r'^(?P[\w | \-]+)/$',views.post,name='post'),
url(r'^category/(?P[\w\-]+)/$),CategoryDetailView.as_view(),name='category'),
]
我有IndexListView.as_view()。
为什么会发生这种错误?
您的视图继承自模板视图
,因此没有人在上下文中填充对象列表
条目
相反,您可能希望从ListView
或其他填充此类上下文键的文件继承
如上所述:
此模板将根据包含变量的上下文呈现
调用包含所有发布者对象的对象列表
您可以在列表视图中看到它
def get(self, request, *args, **kwargs):
self.object_list = self.get_queryset()
...
def get_context_data(self, **kwargs):
"""
Get the context for this view.
"""
queryset = kwargs.pop('object_list', self.object_list)
page_size = self.get_paginate_by(queryset)
context_object_name = self.get_context_object_name(queryset)
if page_size:
paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)
context = {
'paginator': paginator,
'page_obj': page,
'is_paginated': is_paginated,
'object_list': queryset
}
else:
context = {
'paginator': None,
'page_obj': None,
'is_paginated': False,
'object_list': queryset
}
if context_object_name is not None:
context[context_object_name] = queryset
context.update(kwargs)
return super(MultipleObjectMixin, self).get_context_data(**context)
如您所见,get
方法将self.object\u list
设置为检索到的查询集,然后get\u context\u data
方法使用它来更新模板的上下文
相反,不执行以下步骤:
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
if 'view' not in kwargs:
kwargs['view'] = self
return kwargs
因此,object\u list
键在上下文目录中不存在
当然,如果出于某种原因您不想使用Listview
,您仍然可以在代码中执行这些步骤,覆盖get
和get\u context\u data
方法或从适当的混合继承,例如
class IndexView(TemplateResponseMixin, MultipleObjectMixin , View):
鉴于您最近的编辑:
在添加类别中
您可以
return IndexListView(request)
这没有什么意义(即返回视图的实例)
我假定您正在尝试重定向到索引页,这样就可以通过
return redirect(reverse_lazy('index'))
你能发布完整的错误跟踪吗?你的视图继承自TemplateView
,因此没有人在上下文中填写object\u列表
条目。你可能想继承自ListView
或其他@TarunBehal我编辑过的完整错误,知道吗?啊,这就是为什么。但随后它在/add\u category/\u init给了我另一个错误类型error__()只接受1个参数(给定2个),这是一个与上面的问题不同的问题。我必须为此创建一个新线程,不是吗?但这有点相关。这个错误很奇怪,因为我只有一个参数请求,它说我提供了两个。我用谷歌搜索了它,它说问题发生在我刚刚切换的url(切换到IndexListView).有什么想法吗?我会提供我修改过的视图,然后urlHey,这将变成一个调试会话。你上一次编辑可能属于另一个问题,因为以后很难继续。我的答案正确吗?对你原来的问题有用吗?我同意你的看法,它正在变成这样……你的答案会很完美,我相信f add_category也有效。不幸的是它不起作用这正是我的观点:add_category
不在我回答的原始问题中。一个新的问题是有意义的,因为它是一个完全不同的问题。而且,它将帮助将来的其他人找到并回答原始问题以及寻找f的人或者是对这个新问题的回答,就目前而言,这个问题的标题是相同的。
return redirect(reverse_lazy('index'))