checking radio button on Django view from template - html

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:

Related

Post method is not working in my HTML forms

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})

Iam Created Login Form but here If I login twice only it redirects the page in django

Here My Html Code I am created an Login Form
Here my action is empty if I give an URL in action means. Then I will submit means it will goes to next page without authentication.
Please Help me out...If I am login means it will redirect to the Page Dash. But here i want to login twice only means then it works successfully...If I login only once means it does'nt redirect the page I don't know why
<form action="" method="post">
{%csrf_token%}
<div class="form-outline mb-4">
<input type="text" name="username" id="form3Example3" class="form-control form-control-lg" class="form-control new-input" placeholder="Enter a Name" required>
<label class="form-label" for="form3Example3"></label>
</div>
<div class="form-outline mb-3">
<input type="password" name="password" id="form3Example4" class="form-control form-control-lg" placeholder="Enter password" required>
<label class="form-label" for="form3Example4"></label>
</div>
<div class="d-flex justify-content-between align-items-center">
<div class="form-check mb-0">
<input class="form-check-input me-2" type="checkbox" value="" id="form2Example3" />
<label class="form-check-label" for="form2Example3">Remember me</label>
</div>
Forgot password?
</div>
<div class="text-center text-lg-start mt-4 pt-2">
<input type="submit" value="submit" class="register-button2" />
</form>
<p class="small fw-bold mt-2 pt-1 mb-0">Don't have an account? <a href="{% url 'register'%}"
class="link-danger">Register</a></p>
</div>
Views.py
def Login(request):
if request.method=='POST':
username=request.POST['username']
password=request.POST['password']
user=auth.authenticate(username=username,password=password)
if user is not None:
request.session['user'] = username
auth.login(request,user)
print(user)
return redirect('Dash')
else:
messages.info(request,'invalid credientials')
return redirect('Login')
else:
return render(request,'Login.html')
This is the Dash View after login redirects the page.Here Dash View after login successfully
def Dash(request):
if 'user' in request.session:
print("INSIDE THE DASH")
current_user = request.session['user']
param = {'current_user': current_user}
return render(request,'Dash.html',param)
else:
return redirect('Login')
After Login successfully the page does'nt redirect to the next page...and again i will login with same username and password only it will login and redirect the page i don't know why please help me somebody

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

Django login form not keeping input after bad submit

I have a login form and if a user enters an invalid username or password, the page refreshes and removes the Username value they entered. I would like it so that the username field doesn't empty on failed submit.
views.py
def login_page(request):
if request.user.is_authenticated:
return redirect('dashboard:dashboard')
elif request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('dashboard:dashboard')
else:
messages.info(request, 'Username or Password is invalid.')
return render(request, 'main/login.html', {})
login.html:
<form id="login-form" action="" method="post" role="form">
{% csrf_token %}
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 center" style="border-radius: 16px;">
<input type="submit" name="login-submit" id="login-submit" tabindex="5" class="form-control btn btn-login" value="Login">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-lg-12">
<div class="center">
Forgot Password?
</div>
</div>
</div>
</div>
</form>
It's all about passing the username in the context.
try this:
views.py
def login_page(request):
context = {}
if request.user.is_authenticated:
return redirect('dashboard:dashboard')
elif request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('dashboard:dashboard')
else:
context["username"] = username
messages.info(request, 'Username or Password is invalid.')
return render(request, 'main/login.html', context)
login.html:
...
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="{{ username }}">
...

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'),
]