Search code examples
djangoformspost

Django- form submitting to the same view and not to desired view


My form stopped submitting to the desired view, and submitting to its own view instead.

URLS.PY:

path('validate_registration', views.validate_registration,name='validate_registration'),

VIEWS.PY:

def user_registration(request):
    print("in reg")
    # populate form
    form = register_form(request.POST)
    print("anonymous form")
    template = loader.get_template('registration.html')
    return HttpResponse(template.render({'form':form}, request))


def validate_registration(request):

    if request.POST:
        print("validating")
        #populate form
        form = register_form(request.POST)
        return render(request, 'val_reg.html', {})

TEMPLATS.HTML:

<form class="text-warning text-center rounded pt-2 ps-2 pe-2" method="POST" action="{% url 'validate_registration' %}" >
    {% csrf_token %}
    {{form.as_p}}
    <br/>
    <button type="submit" class="btn btn-warning mt-5">Register</button>
    <br/>
    <br/>
</form>

The form was working, but after change to the views.py it stopped, which made me shorten its code to few lines only. Even the print "in reg" line doesn't work.

Any help please ?


Solution

  • In your code user_registration view, you are creating a new form instance with request.POST data and then rendering it. This is not standard for a GET request scenario. Generally, you'd instantiate the form without data (form = register_form()) for a GET request, and with request.POST data for a POST request.

    Also, function validate_registration in your view, you are populating the form with request.POST, but you're not doing anything with it afterward.

    If you want to validate the form data, you should check if the form is valid (form.is_valid()) and then proceed next.

    Try this in your views.py:

    def user_registration(request):
        if request.method == 'POST':
            form = register_form(request.POST)
            if form.is_valid():
                # Process the data in form.cleaned_data
                # Redirect to a new URL, or handle the data
                pass
        else:
            form = register_form()
    
        return render(request, 'registration.html', {'form': form})
    
    def validate_registration(request):
        if request.method == 'POST':
            form = register_form(request.POST)
            if form.is_valid():
                # Process valid data
                return render(request, 'success_template.html', {})
            else:
                # Handle invalid form
                return render(request, 'val_reg.html', {'form': form})