Post method is not working in my HTML forms - html

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

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

<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

Flask | HTML not rendering data sent via render_template

I am making a query to my database, creating an object, and sending it to my HTML via render_template.
The issue I am having is that the HTML is not displaying the information.
Relevant code:
#app.route('/profile', methods=['POST','GET'])
def profile():
if 'sno' in session:
if request.method == 'GET':
user = session['sno']
print(user)
cursor = conn.cursor()
cursor.execute("""SELECT * FROM `users` WHERE `sno` LIKE '{}'.format(user))
r = cursor.fetchall()
print(r)
return render_template('profile.html', r=r)
return redirect('/')
<form class="form" method="POST" action="/edit" name="Name">
<label>First Name</label><br>
<input type="text" class="form-control" name="fname" value="{{r[1]}}" >
<label>Last Name</label><br>
<input type="text" class="form-control" name="lname" value="{{r[2]}}" >
<label>Age</label><br>
<input type="text" class="form-control" name="age" value="{{r[3]}}">
<label>CNIC</label><br>
<input type="text" class="form-control" name="cnic" value="{{r[4]}}">
<label>gender:</label>
<input type="text" name="gender" class="form-control" value="{{r[5]}}"><br>
<label>Email</label><br>
<input type="email" class="form-control" name="uemail" value="{{r[6]}}">
<label>Password</label><br>
<input type="text" name="upassword" class="form-control" value="{{r[7]}}"><br>
<input type="submit" class="btn btn-primary btn-block btn-lg" name="submit" value="Edit">
</form>
Is there something I am missing or doing wrong?
I just did this
I had kept method = "POST".I changed it to method="GET"
It worked like boom

Fetching data from template to send email

please this is the html file i am trying to fetch the data to be able to send it to my settings email
<form action="{% url 'send'%}" method="post" role="form" class="contactForm">
{% csrf_token %}
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validation"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validation"></div>
</div>
<div class="text-center"><button type="submit">Send Message</button></div>
</form>
and this is my views.py which i collected the data from the html file
def sendEmail(request):
if request.method == 'POST':
name = request.POST['name']
email = request.POST['email']
subject = request.POST['subject']
message = request.POST['message']
send_mail(
"Contact Form",
message,
email,
settings.EMAIL_HOST_USER,
fail_silently=False
)
return render(request, 'app/index.html')
and my settings for the email which i am using gmail
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '*****#gmail.com'
EMAIL_HOST_PASSWORD = '******'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
and my urls.py is which i sent it to my url to the views
urlpatterns = [
path('',views.index,name='index'),
path('sendmail/', views.sendEmail, name='send'),
]

checking radio button on Django view from template

I am creating a custom sign up form and this is the view I created:
def signup(request):
if request.user.is_authenticated:
return render(request, 'listings/index.html', {})
if request.method == 'POST':
if 'cr-1' in request.POST:
newuser = User.objects.create_user(username=request.POST.get('email'), email=request.POST.get('email'), password=request.POST.get('password'))
newpatient = Patient.objects.create(user=newuser)
user = authenticate(request, username=username, password=password)
if user is not None:
auth_login(request, user)
return redirect('dashboard')
elif 'cr-2' in request.POST:
newuser = User.objects.create_user(username=request.POST.get('email'), email=request.POST.get('email'), password=request.POST.get('password'))
newdoctor = Doctor.objects.create(user=newuser)
user = authenticate(request, username=username, password=password)
if user is not None:
auth_login(request, user)
return redirect('dashboard')
else:
print("##################### NOTHING HAPPENED #####################")
return render(request, 'dashboard/signup.html', {})
I purposely added an else statement printing NOTHING HAPPENED on the console because nothing happens when I click on submit.
Here is the template:
<form class="form-type-material" method="POST" action="{% url 'signup' %}">
{% csrf_token %}
<div class="custom-control custom-radio">
<input type="radio" id="cr-1" name="rg-1" class="custom-control-input" checked>
<label class="custom-control-label" for="cr-1">Patient/Visiteur</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="cr-2" name="rg-1" class="custom-control-input">
<label class="custom-control-label" for="cr-2">Médecin/Praticien</label>
</div>
<div class="form-group">
<input type="text" class="form-control" id="id_email" name="email" required>
<label for="email">Adresse email</label>
</div>
<div class="form-group">
<input type="password" class="form-control" id="id_password" name="password" required>
<label for="password">Mot de passe</label>
</div>
<div class="form-group">
<input type="password" class="form-control" id="id_password-conf" name="password-conf" required>
<label for="password-conf">Confirmation du mot de passe</label>
</div>
<div class="form-group">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" required>
<label class="custom-control-label">I agree to all <a class="text-primary" href="#">terms</a></label>
</div>
</div>
<br>
<button class="btn btn-bold btn-block btn-primary" type="submit">Créer et accéder au tableau de bord</button>
</form>
What seems to be the issue?
PS: In a previous attempt I did if 'cr-1'.checked in request.POST because I saw it in another stackoverflow thread but it gave me the error: str .... has no checked method.
Here in your template you have 'cr-1' and 'cr-2' as ids, but while submitting the form the name will be sent. i.e here you have name name="rg-1"
So, you need to check
if 'rg-1' in request.POST:

How to pass data from html to django view to use in URL?

I'm getting an error while working with django urls. I want to pass the value of Name input field after i hit the submit button.
Let's say I've this html form-
<form method='POST' action="{% url 'submittedform' slug=[firstname] %}">
{% csrf_token %}
<div>
<label for="name">Name</label>
<input type="text" name="firstname" id="name">
</div>
<div>
<label for="email">Email</label>
<input type="email" name="useremail" id="email">
</div>
<div>
<label for=phone>Phone</label>
<input type="text" name="phonenumber" id="phone" maxlength="12" pattern="[0-9]{10}">
</div>
<input type="submit" name="" id="btn" value="Submit">
</form>
Here's my view that handling it-
def submittedform(request, slug):
if request.method == 'POST':
# do something here
return render(request,'myapp/welcome.html')
return render(request,'myapp/welcome.html')
and here's my view that's handling it-
urlpatterns = [
path('index/',views.index ,name='index'),
path('welcome/<slug:slug>/',views.submittedform, name='submittedform')
]
I'm not using django forms. How can i get welcome/name working.
If you want to pass a variable to an URL you need redirect with the value:
from django.shortcuts import redirect
return redirect("/welcome/%s/" % slug)
Change the following line
<!-- Removed the bracket -->
<form method='POST' action="{% url 'submittedform' slug=firstname %}">
<!-- Children tags here -->
</form>
Now the variables are accessible in view like
def submittedform(request, slug):
if request.method == 'POST':
name = request.POST['name']
# and more variables as you need
# do something here
# do redirect here or give some message that their form has been
# submitted for their confirmation
return render(request,'myapp/welcome.html')
return render(request,'myapp/welcome.html')

flask multiple submit button

I am using flask and jinja2 to create a simple web app to serve up a simple sklearn algorithm for predictions.
In my html I need to get 4 variables: client id, textid, textid1, textid2
It currently works when I have it all connected to one submit button. But I would like to have two submit buttons to have the client id submit at the top of the page and the textid stuff at the bottom of the page. When I try to have two submit buttons it causes the page to refresh and I not able to connect the client id to the 3 textid vars.
<div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>
<form method="POST">
<input name="text", id='text', placeholder="Client ID #", value="{{ client_id|round|int }}" >
<br>
<label>Enter 3 suggestions</label>
<br>
<input name="textid", placeholder="Suggested Model ID #", value="{{ request.form['textid'] }}"/>
<input name="textid1", placeholder="Suggested Model ID #", value="{{ request.form['textid1'] }}"/>
<input name="textid2", placeholder="Suggested Model ID #", value="{{ request.form['textid2'] }}"/>
<input type="submit" >
</form>
</div>
I'm simply grabbing it in flask like this:
#app.route('/suggestion', methods=['GET', 'POST'])
def with_suggestions():
try:
client_id=request.form['text']
except:
#custom function when client id is not entered to get random one
client_id = recommender.random_client_id()
try:
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
#other functional code after this
How can I break up the html to get two submit buttons? Thanks!!
Now that you have updated your code, all you need to do is add hidden inputs to identify where the click was originated from. Also Remove the leading slash from your url_for like I did below
<div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>
<form method="POST" action={{url_for('suggestion')}}>
<input name="text", id='text', placeholder="Client ID" >
<input type="hidden" name="btn_identifier" value="client_id_identifier" />
<input type="submit" >
</form>
<form method="POST" action={{url_for('suggestion')}}>
<input name="textid", id='text', placeholder="Textid1">
<input name="textid1", id='text', placeholder="textid2 ">
<input name="textid2", id='text', placeholder="Textid3">
<input type="hidden" name="btn_identifier" value="text_id_identifier" />
<input type="submit" value="Submit">
</form>
main.py
from flask import Flask
from flask import render_template, url_for, request, redirect
app = Flask(__name__)
#app.route('/suggestion', methods=['GET', 'POST'])
def with_suggestions():
if request.methods == 'POST':
if request.form['btn_identifier'] == 'client_id_btn':
try:
client_id=request.form['text']
except:
# I think this would go in the second elif statement
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
elif request.form['btn_identifer'] == 'text_id_btn':
# run some code to handle a click that was originated from the second button
return render_template('index.html')
if __name__ == '__main__':
app.run()
I made some changes to your code.
index.html
<div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>
<form method="POST" action={{url_for('suggestion')}}>
<input name="text", id='text', placeholder="Client ID" >
<input type="submit" >
</form>
<form method="POST" action={{url_for('suggestion')}}>
<input name="textid", id='text', placeholder="Textid1">
<input name="textid1", id='text', placeholder="textid2 ">
<input name="textid2", id='text', placeholder="Textid3">
<input type="submit" value="Submit">
</form>
</div>
main.py
from flask import Flask
from flask import render_template, url_for, request, redirect
app = Flask(__name__)
#app.route('/suggestion', methods=['GET', 'POST'])
def suggestion():
if request.method == 'POST':
try:
client_id=request.form['text']
except:
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
return render_template('index.html')
if __name__ == '__main__':
app.run()
Note: Values are store in the variable, print to see
I have simplified the process of fetching the info from multiple buttons. Do note that you require the python flask framework for the "request" method.
home.html
<div class="container mt-5">
<div class="row col-4">
<form method="POST" class="form-register">
<input type="submit" name="submit_button" value="Add Email">
<input type="submit" name="submit_button" value="Clear Recipients">
</form>
</div>
</div>
run.py
if request.method == 'POST':
if request.form['submit_button'] == 'Add Email':
print("add email")
elif request.form['submit_button'] == 'Clear Recipients':
print("clear recipients")
you may refer to the link provided for more example
https://www.codegrepper.com/code-examples/python/checking+if+button+pressed+flask