2011-11-27 4 views
1

Django-MPTT를 사용하여 장고 프로젝트의 분류 앱을 개발하고 있습니다. 하지만 하위 카테고리에서 벗어나지 않는 후행 슬래시를 추가하는 정규식 패턴을 얻지 못하는 것 같습니다.Django MPTT 기반 분류 응용 프로그램에 후행 슬래시를 어떻게 추가합니까?

다음은 URL 예입니다. http://mydjangoapp.com/categories/parentcat/childcat/http://mydjangoapp.com/categories/parentcat을 사용하고 후행 슬래시 버전으로 리디렉션 할 수 있기를 바랍니다. 동일한 내용이 http://mydjangoapp.com/categories/parentcat/childcat에 적용되어야합니다 (http://mydjangoapp.com/categories/parentcat/childcat/으로 리디렉션되어야 함). 여기

내 urls.py의 :

from django.conf.urls.defaults import patterns, include, url 
from django.views.decorators.cache import cache_page 

from storefront.categories.models import Category 
from storefront.categories.views import SimpleCategoryView 

urlpatterns = patterns('', 
    url(r'^(?P<full_slug>[-\w/]+)', cache_page(SimpleCategoryView.as_view(), 60 * 15), name='category_view'), 
) 

그리고 여기 내보기입니다 :

from django.core.exceptions import ImproperlyConfigured 
from django.core.urlresolvers import reverse 
from django.views.generic import TemplateView, DetailView 
from django.views.generic.detail import SingleObjectTemplateResponseMixin, SingleObjectMixin 
from django.utils.translation import ugettext as _ 
from django.contrib.syndication.views import Feed 

from storefront.categories.models import Category 

class SimpleCategoryView(TemplateView): 

    def get_category(self): 
     return Category.objects.get(full_slug=self.kwargs['full_slug']) 

    def get_context_data(self, **kwargs): 
     context = super(SimpleCategoryView, self).get_context_data(**kwargs) 
     context["category"] = self.get_category() 
     return context 

    def get_template_names(self): 
     if self.get_category().template_name: 
      return [self.get_category().template_name] 
     else: 
      return ['categories/category_detail.html'] 

그리고 마지막으로, 내 모델 :

from django.db import models 
from mptt.models import MPTTModel 
from mptt.fields import TreeForeignKey 

class CategoryManager(models.Manager): 
    def get(self, **kwargs): 
     defaults = {} 
    defaults.update(kwargs) 
     if 'full_slug' in defaults: 
      if defaults['full_slug'] and defaults['full_slug'][-1] != "/": 
       defaults['full_slug'] += "/" 
     return super(CategoryManager, self).get(**defaults) 

class Category(MPTTModel): 
    title = models.CharField(max_length=255) 
    description = models.TextField(blank=True, help_text='Please use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> for all text-formatting and links. No HTML is allowed.') 
    slug = models.SlugField(help_text='Prepopulates from title field.') 
    full_slug = models.CharField(max_length=255, blank=True) 
    template_name = models.CharField(max_length=70, blank=True, help_text="Example: 'categories/category_parent.html'. If this isn't provided, the system will use 'categories/category_detail.html'. Use 'categories/category_parent.html' for all parent categories and 'categories/category_child.html' for all child categories.") 

    parent = TreeForeignKey('self', null=True, blank=True, related_name='children') 

    objects = CategoryManager() 

    class Meta: 
     verbose_name = 'category' 
     verbose_name_plural = 'categories' 

    def save(self, *args, **kwargs): 
     orig_full_slug = self.full_slug 
     if self.parent: 
      self.full_slug = "%s%s/" % (self.parent.full_slug, self.slug) 
     else: 
      self.full_slug = "%s/" % self.slug 
     obj = super(Category, self).save(*args, **kwargs) 
     if orig_full_slug != self.full_slug: 
      for child in self.get_children(): 
       child.save() 
     return obj 

    def available_product_set(self): 
     """ Returns available, prioritized products for a category """ 
     from storefront.apparel.models import Product 
     return self.product_set.filter(is_available=True).order_by('-priority') 

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

    def get_absolute_url(self): 
     return '/categories/%s' % (self.full_slug) 

답변

0

입니다 : 일치하지 url(r'^(?P<full_slug>[-\w/]+)'...

1

이 슬래쉬없이 URL을 일치해야합니다 :

r'^(?P<full_slug>[-\w/]+)/$' 

이 일치 항목을 full_slug + "/"로 리디렉션 할 수 있습니다.

+0

하지만 URL은 하위 범주에서 휴식. 즉,이 작품 : http://mydjangoapp.com/categories/parentcat/하지만이 않습니다 : http://mydjangoapp.com/categories/parentcat/childcat/ –

1

내 패턴이 약간 바뀌 었습니다. URLConf에서 올바른 패턴 내가이 솔루션을가는 결국 (r'^(?P<full_slug>[-\w/]+/)$'