Home > Net >  error while redirecting one page to other in django
error while redirecting one page to other in django

Time:07-08

Basically, from and to both page have parameters so how can I redirect to page with parameters?

html page:

{% for vr in adduser.adduser.all %}
<form method="POST" action="{% url 'edituser' id=vr.id bid=adduser.id %}">
{% csrf_token %}
 <label for="FirstName">First Name<span style="color:#ff0000">*</span></label>
<input type="text"  name="firstname" placeholder="Type FirstName here...." value="{{vr.f_name}}">
 <label for="LastName">Last Name<span style="color:#ff0000">*</span></label>
<input type="text"  name="lastname" placeholder="Type LastName here...." value="{{vr.l_name}}">
{% endfor %}
<button type="submit" >Add</button>

urls.py

path('edituser/<uid>/<bid>', views.edituser, name="edituser"),

views.py

def edituser(request, uid, bid):
if request.method == "POST":
    if request.POST.get('firstname') and request.POST.get('lastname'):
        saverecord = AddContact()
        saverecord.id = uid
        saverecord.f_name = request.POST.get('firstname')
        saverecord.l_name = request.POST.get('lastname')
        saverecord.save()
        viewRecords = AddContact.objects.filter(subscribe='subscribe')
        return HttpResponseRedirect(reverse('adduser',bid))
    else:
        viewRecords = AddContact.objects.filter(subscribe='subscribe')
        messages.error(request, "Error During Editing of Contact")
        return redirect(request, 'broadcastlist.html')
else:
    viewRecords = AddContact.objects.filter(subscribe='subscribe')
    messages.error(request, "Error During Editing of Contact")
    return redirect(request, 'broadcastlist.html')

To clarify more uid is userid which is for edit the user and bid is broadcast id which is to redirect to the broadcast list.

CodePudding user response:

To redirect to another page in Django with parameters use this

return HttpResponseRedirect(reverse(viewname='the view to which it should redirect', args=(parameters to be passed)))

CodePudding user response:

Use redirect, it's easier than invoking reverse and HttpResponseRedirect directly. (Doc)

from django.shortcuts import redirect
...
    return redirect( 'myapp:url_name', urlparam=value, ...)

which is the same as

    return HttpResponseRedirect( 
         reverse( 'myapp:url_name',
         kwargs={ 'urlparam': value, ... } 
    )
  • Related