Iron Man
Iron Man

Reputation: 145

error while redirecting one page to other in django

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" class="form-control" name="firstname" placeholder="Type FirstName here...." value="{{vr.f_name}}">
 <label for="LastName">Last Name<span style="color:#ff0000">*</span></label>
<input type="text" class="form-control" name="lastname" placeholder="Type LastName here...." value="{{vr.l_name}}">
{% endfor %}
<button type="submit" class="btn btn-primary">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.

Upvotes: 1

Views: 224

Answers (2)

nigel222
nigel222

Reputation: 8202

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, ... } 
    )

Upvotes: 0

Pythonista
Pythonista

Reputation: 195

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)))

Upvotes: 1

Related Questions