Home > database >  Post method is not working in my HTML forms
Post method is not working in my HTML forms

Time:10-18

my form is like this

<h1>Signup below</h1>
<form action="result" method="post">
    {% csrf_token %}
    <h3>Username</h3>
    <input type="text" name="username" />
    <h3>Email</h3>
    <input type="email" name="email">
    <h3>Password</h3>
    <input type="password" name="password">
    <h3>Rententer your password</h3>
    <input type="password" name="password2">
    <input type="button" />
    </form>

and in my view folder code for this url is this

def register(request):
    username=request.POST['username']
    email=request.POST['username']
    password=request.POST['username']
    verify_password=request.POST['verify_password']
    return render(request,'result.html')

but whenever I run this code it shows

screenshot of the error message

CodePudding user response:

you should add in def

def register(request):
   if request.method == 'POST':
     .....

also when you want to return a response check this valid response form django

finally make sure you are using a valid URL in urls.py

CodePudding user response:

<h1>Signup below</h1>
<form action="/result/" method="post">
    {% csrf_token %}
    <h3>Username</h3>
    <input type="text" name="username" value="{{form.username}}" />
    <h3>Email</h3>
    <input type="email" name="email" value="{{form.email}}">
    <h3>Password</h3>
    <input type="password" name="password" value="{{form.password}}">
    <h3>Rententer your password</h3>
    <input type="password" name="password2" value="{{form.password2}}">
    <input type="button" />
    </form>

Note: form is context name from view so that's why I have written

{{form.username}}

And in views.py:

try this:

def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid:
            form.save()
            username = form.cleaned_data.get('username')
            # messages.success(request,f'Welcome { username }')
            return HttpResponseRedirect('/users/')
    else:
        form = RegisterForm()
    return render(request,'users/register.html',{'form':form})
  • Related