Django form does’nt render even if the code seems alright

I am beginner to Django. I have just started learning basic forms and here is the code which does'nt work. The method specified for the form in form_page.html is POST, so accordingly in views.py it must render me form_page.html but instead it prints thanks which means it does'nt recognize the method as post and run the else code snippet.Can you help me fix it!!

Views.py

from django.shortcuts import render
from django.http import HttpResponse
from  .forms import formname

def index(request):
    return render(request,'index.html')

def form_name_view(request):
    
    if request.method == 'POST':
        form=formname(request.POST)
        if form.is_valid:
            print('NAME:',form.cleaned_data['name'])
            print('email:',form.cleaned_data['email'])
            print('text:',form.cleaned_data['text']) 

            
            return render(request,'form_page.html',{'form':form})
            
            
            
    else:
        form=formname()
        return HttpResponse('thanks')

form_page.html

<!doctype html>

<html lang='en'>

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <title> Basic forms </title>
<head>

<body>

<h1>Fill out the form</h1>
<div class="container">
    <form method="POST">
        {{form.as_p}}
        {% csrf_token %}
        <btn type="submit" class="btn btn-primary ">Submit</btn>
    </form>
</div>
  

    
</body>
</html>

forms.py

from django import forms
from django.core import validators

class formname(forms.Form):
    name=forms.CharField()
    email=forms.EmailField()
    text=forms.CharField(widget=forms.Textarea)

urls.py

from django.contrib import admin
from django.urls import path
from basicformsapp import views
from django.conf.urls import url

urlpatterns = [
    url(r'^$',views.index,name='index'),
    path('admin/', admin.site.urls),
    url(r'^formpage/',views.form_name_view,name='form_name_view')
]


Read more here: https://stackoverflow.com/questions/65713424/django-form-doesnt-render-even-if-the-code-seems-alright

Content Attribution

This content was originally published by Tejaswini Savkar at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: