models.py中的django python slug varibale

时间:2014-12-01 06:53:16

标签: python django

当我点击搜索按钮时..显示

找不到页面(404)

没有类别与给定的查询匹配。

我的观点

def search_in_category(request, slug):
# reset the search params, if present

try:
    del request.session['search']
except KeyError:
   pass
return search_results(request, slug)

def search_results(request, slug):
category = get_object_or_404(Category, slug=slug)
fields = list(category.field_set.all())
fields += list(Field.objects.filter(category=None))
fieldsLeft = [field.name for field in fields]

if request.method == "POST" or 'search' in request.session:
    ads = category.ad_set.filter(active=True,
                                 expires_on__gt=datetime.datetime.now())
    # A request dictionary with keys defined for all
    # fields in the category.
    post = {}
    if 'search' in request.session:
        post.update(request.session['search'])
    else:
        post.update(request.POST)

    sforms = prepare_sforms(fields, fieldsLeft, post)

    isValid = True

    for f in sforms:
        # TODO: this assumes the form is not required
        # (it's a search form after all)
        if not f.is_valid() and not f.is_empty():
            isValid = False

    if isValid:
        if request.method == 'POST':
            request.session['search'] = {}
            request.session['search'].update(request.POST)
            return redirect('classifieds_browse_search_results', slug=slug)

        for f in sforms:
            ads = f.filter(ads)

        if ads.count() == 0:
            return render_to_response('classifieds/list.html',
                                      {'no_results': True,
                                       'category': category},
                                      context_instance=RequestContext(request))
        else:
            context = context_sortable(request, ads)
            context['category'] = category
            return render_to_response('classifieds/list.html', context,
                                      context_instance=RequestContext(request))
else:
    sforms = prepare_sforms(fields, fieldsLeft)

return render_to_response('classifieds/search.html',
                          {'forms': sforms, 'category': category},
                          context_instance=RequestContext(request))

我的models.py

class Category(models.Model):
site = models.ForeignKey(Site)
template_prefix = models.CharField(max_length=200, blank=True)
name = models.CharField(max_length=200)
slug = models.SlugField()
enable_contact_form_upload = models.BooleanField(default=False)
contact_form_upload_max_size = models.IntegerField(default=2 ** 20)
contact_form_upload_file_extensions = models.CharField(max_length=200,
                                                 default="txt,doc,odf,pdf")
images_max_count = models.IntegerField(default=0)
images_max_width = models.IntegerField(help_text=_(u'Maximum width in pixels.'),
                                       default=1024)
images_max_height = models.IntegerField(help_text=_(u'Maximum height in pixels.'),
                                        default=1024)
images_max_size = models.IntegerField(help_text=_(u'Maximum size in bytes.'),
                                      default=2 ** 20)
images_allowed_formats = models.ManyToManyField(ImageFormat, blank=True)
description = models.TextField(default='')
sortby_fields = models.CharField(max_length=200,
                                 help_text=_(u'A comma separated list of field names that should show up as sorting options.'),
                                 blank=True)
sort_order = models.PositiveIntegerField(default=0)

def __unicode__(self):
    return self.name + u' Category'

class Meta:
    verbose_name_plural = u'categories'

我的网址

url(r'^search/(?P<slug>[-\w]+)/$', 'browse.search_in_category',
    name='classifieds_browse_category_search'),

url(r'^search/results/(?P<slug>[-\w]+)/$', 'browse.search_results',
    name='classifieds_browse_search_results'),

这是我的代码,为什么我收到404错误?我需要做些什么来解决这个错误?

1 个答案:

答案 0 :(得分:1)

你做不到

return search_results(request, slug)

确实是这个重定向

return redirect(reverse('classifieds_browse_search_results', kwargs={'slug':slug}))

别忘了导入

from django.core.urlresolvers import reverse
from django.shortcuts import redirect