python - Django redirect to latest created article -


i want redirect people latest article created after submitting.

the url doesn't use id slugs how can it? thinking :

views.py

def article_id(request, slug):     context = {'article_id': get_object_or_404(article, slug=slug)}     return render(request, 'article_id.html', context)   @login_required(login_url='/user') def article_ajouter(request):     if request.method == 'post':         form = articleform(request.post, request.files)          if form.is_valid():             save_it = form.save()             save_it.user = request.user             save_it.save()             object = article.objects.get(article_id)             redirect(object, permanent=true) #i don't know if mistaken.     else:         form = articleform()      context = {'form':form}     return render(request, 'article_ajouter.html', context) 

any suggestions in order redirection?

---- update ----

article/urls.py

url(r'^(?p<slug>[-\w\d]+)/$', views.article_id, name="article_detail"), 

article/views.py

if form.is_valid():     save_it = form.save()     save_it.user = request.user     save_it.save()     return redirect('article_detail', article_id=save_it.slug) 

you don't have local variable called article_id defined, code fail because try , pass view name article.objects.get(), make no sense @ all.

however there no need query; save_it article want. if article class has defined get_absolute_url code work (with 1 change, see below); if not need use url pattern name in redirect call.

the final change need return redirect, return other kind of response.

so, assuming you've defined url article_id view looks this:

url(r'^articles/(?p<slug>\w+)/$', article_id, name='article_detail'), 

then this:

return redirect('article_detail', slug=save_it.slug) 

(i'd point out "article_id" strange name view; wants called "article_detail" anyway.)


Comments