Home > Back-end >  How can I redirect this to a slug url in django?
How can I redirect this to a slug url in django?

Time:10-11

So I have one detail view and one function in my views.py. So i have included the form in detail view template list_detail.html. and upon posting the form successfully. It redirects to all page(homepage basically). Now I want it to redirect to detailview page which is like this. and for that I need to pass the slug value of that List models specific object. But can build the logic here. I am new to django.

path('list/<slug:slug>/', TheirDetailView.as_view(),name='list_detail'),
path('all',views.all, name='all'),
path('create_comment',views.create_comment, name='create_comment'),
class TheirDetailView(DetailView):
    model = List
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        modell = Review.objects.all()
        context["modam"] = modell
        return context
def create_comment(request):
    context = {}
    form = ReviewForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect('app:all')
    else:
        context['form'] = form
        return render(request, "app/create_comment.html", context)

CodePudding user response:

def create_comment(request):
    # context = {}
    form = ReviewForm(request.POST or None)
    id_List = request.POST["List"]
    slug = List.objects.filter(id=int(id_List)).values("slug").first()
    if form.is_valid():
        form.save()
        return redirect("app:list_detail", slug=slug["slug"])

CodePudding user response:

Hey did some google and found this in stackoverflow link added this line replacing my redirect under my create_comment function if form.is_valid statement

return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

So my function looks like this

def create_comment(request):
    context = {}
    form = ReviewForm(request.POST or None)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
    else:
        context['form'] = form
        return render(request, "app/create_comment.html", context)

Weirdly enough its said in the post that it wont work in incognito/private mode but just checked and it does. But even in some articles its discouraged to use this referrer so still looking for a better solution to this. Thanks everyone.

  • Related