I am currently learning Django and would like to know how to automatically append the slug to the url.
For example, the full url to an old question I posted here is:
https://stackoverflow.com/questions/13263275/having-trouble-compiling-pysqlite-on-windows
But if I enter:
https://stackoverflow.com/questions/13263275
in the address bar, it automatically appends the slug in the url.
How do I do this in Django?
Thank you.
You can achieve this by taking 2 parameters in URL one pk
of the question and other slug
and handle like this.
urls.py
url(r'^(?P<pk>\d+)/$', views.questionDetail),
url(r'^(?P<pk>\d+)/(?P<slug>[\w.-]+)/$', views.questionDetail, name='question-detail'),
views.py
def questionDetail(request, pk, *args):
question = get_object_or_404(Question, pk=pk)
slug = ""
if(*args[0])
slug = *args[0]
if question.slug != slug:
return redirect('question-detail', pk, question.slug)
return render(request, 'questions/question_detail.html', context)