0

I have tried to implement redirect in django 4.1.1 views. Please find the following code.

redirect is working

def customer_registration(request):
    return redirect('customer_login')

redirect not working

def customer_registration(request):
    print("ASFADFAd")
    if request.method == 'POST':
       return redirect('customer_login')
    return render(request, 'registration/registration.html')

Can anyone help what is the problem, I have already gone through the internet none of the solutions working. Please help me.

Cadmus
  • 665
  • 7
  • 13
  • Does this answer your question? [A good way to redirect with a POST request?](https://stackoverflow.com/questions/2604530/a-good-way-to-redirect-with-a-post-request) – hd1 Oct 12 '22 at 02:32
  • Not quite a duplicate, but [this](https://stackoverflow.com/questions/2604530/a-good-way-to-redirect-with-a-post-request) may prove helpful – hd1 Oct 12 '22 at 02:33
  • Can you show me output of ```print(request.method) ``` before ```if``` statement? – Saeed Oct 12 '22 at 02:34
  • response of `request.method` is `POST` `[11/Oct/2022 17:39:11] "POST /customer/registration HTTP/1.1" 302 0 [11/Oct/2022 17:39:11] "GET /customer/login HTTP/1.1" 200 6226` from browser its' not redirecting – Cadmus Oct 12 '22 at 03:29
  • i'm trying to redirect url from django views, not perticulary from the form submission or UI. – Cadmus Oct 12 '22 at 03:35

1 Answers1

0

====== views.py ========

def HomeView(request):
    form = ProductForm()
    
    context = {
      'form':form
    }
    return render(request,'index.html',context)


def customer_registration(request):
    print("-------- GET method called ----------")
    if request.method == 'POST':
      print("-------- POST method called ----------")
      return redirect('home')

===== urls.py =====

from django.urls import path
from .views import *
 
urlpatterns = [
 
    path('home/', HomeView,name='home'),
    path('', customer_registration,name='other'),
 
]

====== html code ========

{% block body %}
     <form action="{% url 'other' %}" method="post">
          {% csrf_token %}
          
          <p>{{form.name.label}}:{{form.name}}</p>
          <p>{{form.cate.label}}:{{form.cate}}</p>
               
          <p><button type="submit">Add</button></p>
          
     </form>
{% endblock body %}

====== output after press Add button in terminal ========

-------- GET method called ----------
-------- POST method called ----------