V
V
Vladimir2017-09-20 21:19:58
Django
Vladimir, 2017-09-20 21:19:58

How to combine output by ID and by SLUG in one URL?

Hello. Python 3.6.2 / Django 1.11.5 is used
It is necessary to be able to go to the page both by a link like /id1 and a slug like /kosmos
Done, it works, but there is a feeling that this can be done somehow better / more correctly / more beautiful. Can you please tell me if it is possible to compress / link / improve what is written below?
In urls.py

url(r'^id(?P<projekto_id>[0-9]+)/$', muro_views.sociaprojekto, name='muro_sociaprojekto'),
url(r'^(?P<projekto_slug>[\w-]+)/$', muro_views.sociaprojekto_slug, name='sociaprojekto_slug'),

In views.py
def sociaprojekto(request, projekto_id):

    sociaprojekto = get_object_or_404(KomunumojSociaprojekto, id=projekto_id)

    return render(request, 'muroj/muro_sociaprojekto.html', {'sociaprojekto': sociaprojekto,})


def sociaprojekto_slugo(request, projekto_slug):

    sociaprojekto = get_object_or_404(KomunumojSociaprojekto, slug__slug=projekto_slug)

    return render(request, 'muroj/muro_sociaprojekto.html', {'sociaprojekto': sociaprojekto,})

slug__slug is because it uses a separate model/table for slugs.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sim3x, 2017-09-20
@sim3x

Premature optimization
But slug__slug is the problem

T
tema_sun, 2017-09-20
@tema_sun

In this case, you will have pages duplicated at different addresses. If nothing has changed, then the search engines do not like it. You need to choose one main method, for example, by slug, and redirect to the main one from another option.
ps By the way, are you sure that the slug will never consist of only numbers?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question