2015-03-31 41 views
1

我怎样才能添加ID段塞,这样它会出现这样的在Django中我怎么能在塞标题添加ID

“这 - 是 - 一 - 交易-1”

其中“这是一笔交易”是标题,“1”是id号。在它被显示为"this-is-a-deal-None"

models.py ... 蛞蝓= models.SlugField()

def save(self, *args, **kwargs): 
     if not self.id: 
      # Newly created object, so set slug 
      self.slug = '%s-%s' %(
          slugify(self.deal_title), 
          str(self.id)) 

views.py

def deal_page(request, deal_title_slug): 

    # Create a context dictionary which we can pass to the template rendering engine. 
    context_dict = {} 

    try: 
     deal = SubmitDeal.objects.get(slug=deal_title_slug) 
     context_dict['deal_title'] = deal.deal_title 

     context_dict['deal'] = deal 
    except SubmitDeal.DoesNotExist: 
     # We get here if we didn't find the specified category. 
     # Don't do anything - the template displays the "no category" message for us. 
     pass 

    return render(request, 'deal_page.html', context_dict) 

网址当前代码的时刻。 py

url(r'^(?P<deal_title_slug>[\w\-]+)/$', 'submit_deals.views.deal_page', name='deal_page'), 

admin.py

class SubmitModelAdmin(admin.ModelAdmin): 
    prepopulated_fields = {'slug':('deal_title',)} #prepopulate slug with deal_title 
    class meta: 
     model = SubmitDeal 

admin.site.register(SubmitDeal, SubmitModelAdmin) 

回答

1

你不应该改变分贝中的slu g。分开slugid的网址:

url(r'^(?P<slug>[\w\-]+)-(?P<pk>\d+)/$', 'submit_deals.views.deal_page', 
             name='deal_page'), 

的再使用pk获取对象,忽略slug

def deal_page(request, slug, pk): 
    try: 
     deal = SubmitDeal.objects.get(pk=pk) 
     context_dict = {'deal_title': deal.deal_title, 'deal': deal} 
    except SubmitDeal.DoesNotExist: 
     context_dict = {} 
    return render(request, 'deal_page.html', context_dict)