0

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

Category matching query does not exist

我的意见.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)

创建链接表格:

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

那我怎么了?为什么我得到这个错误Category matching query does not exist

4

1 回答 1

0

如果category_name在您看来是一个参数,并且您想将其设置为等于link.category,那么在您views.py执行以下操作时:

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

出错的原因view是您试图将字段设置为等于 get() 查询,但 Django 期望在这里获得一个整数参数,因为模型中的字段categoryLink模型的字段。Foreign KeyCategory

于 2013-10-14T20:55:24.860 回答