类别匹配查询不存在错误

时间:2013-10-14 10:01:41

标签: python django

我想发布一个网址并保存到链接模型。但我得到了这个错误:

Category matching query does not exist

my views.py

def category_detail(request, category_name):
    if request.POST:
        form = CreateLinkForm(request.POST)
        user = request.user
        if form.is_valid():
            link = form.save(commit=False)
            link.user = user 
            link.category = Category.objects.get(name=category_name)
            link.save()
        return HttpResponseRedirect(reverse('category_detail', args=[category_name]))
    else:
        form = CreateLinkForm()
    links = Link.objects.filter(category__name=category_name)
    return render_to_response("category_detail.html", {"links":links, "form":form, "category_name":category_name}, context_instance=RequestContext(request))

当我在终端python manage.py shell查询时,我得到了这个:

>>> from link.models import Category
>>> Category.objects.all()
[<Category: <django.db.models.fields.related.ManyRelatedManager object at 0x22dbfd0> Programlama>, <Category: <django.db.models.fields.related.ManyRelatedManager object at 0x22de110> Foto>, <Category: <django.db.models.fields.related.ManyRelatedManager object at 0x22dbfd0> Sanat>]
>>> Category.objects.get(name="Foto")
<Category: <django.db.models.fields.related.ManyRelatedManager object at 0x22dbed0> Foto>

链接模型:

class Link(models.Model):
    user = models.ForeignKey(User)
    posted_at = models.DateTimeField(auto_now_add=True)
    url = models.URLField()
    title = models.CharField(max_length=255, null=True, blank=True)
    category = models.ForeignKey(Category)

    def __unicode__(self):
        return "%s %s %s" %(self.url, self.title, self.category)

CreateLinkForm:

class CreateLinkForm(ModelForm):
    class Meta:
        model = Link 
        exclude = ["user", "posted_at", "category"]

那我错了什么?为什么我收到此错误Category matching query does not exist

1 个答案:

答案 0 :(得分:0)

如果category_name是您视图中的参数,并且您希望将其设置为link.category,那么请在views.py中执行此操作:

if form.is_valid():
  ...
  link.category = category_name
  ...
  # your other view code

view错误输出的原因是你试图将字段设置为等于get()查询,但是Django期望在这里得到一个整数参数,因为你的category字段Link模型是Foreign Key模型的Category