我如何在子弹中添加ID,以便它看起来像这样
“这是交易1”
其中“这是一笔交易”是标题,“ 1”是ID号。目前,当前代码显示为"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'),
管理员
class SubmitModelAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('deal_title',)} #prepopulate slug with deal_title
class meta:
model = SubmitDeal
admin.site.register(SubmitDeal, SubmitModelAdmin)
最佳答案
您不应更改数据库中的子弹。在URL中将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)
关于python - 在Django中,如何在slug标题中添加ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29362606/