gpt4 book ai didi

python - 在 Django 中,如何在 slug 标题中添加 id

转载 作者:太空宇宙 更新时间:2023-11-04 05:52:39 25 4
gpt4 key购买 nike

如何在 slug 中添加 id,使其看起来像这样

"this-is-a-deal-1"

“这是一笔交易”是标题,“1”是 ID 号。目前,当前代码显示为 "this-is-a-deal-None"

模型.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))

View .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'),

管理员.py

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

admin.site.register(SubmitDeal, SubmitModelAdmin)

最佳答案

你不应该改变数据库中的 slug。将url中的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)

关于python - 在 Django 中,如何在 slug 标题中添加 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29362606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com