如何在slug中添加id,使其显示为
"这-是-A-交易-1"
其中"这是一笔交易"是标题和" 1"是身份证号码。目前使用当前代码,它显示为"this-is-a-deal-None"
models.py ... slug = 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)
urls.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)
答案 0 :(得分:1)
你不应该改变数据库中的slu ..在网址中分隔slug
和id
:
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)