Fetching data from template to send email - html

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

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

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 }}">
...

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:

I need code to send mail fom my Contact Us page

I have designed a contact form and I need to receive mail from the "Contact Us" page, on a specific email ID.
This my form:
contact.html
<form action="contactservlet" method="post">
<h4>Get in <i>Touch</i></h4>
<input type="text" id="name" name="name" placeholder="NAME" class="input-style" />
<input type="email" id="emailid" name="emailid" placeholder="EMAIl" oninput="sendRequest('GET','Checkemailid',1)" required="required" class="input-style" />
<input type="text" id="mobno" name="mobno" placeholder="Enter Mobile No." required="required" class="input-style"/>
<textarea type="text" id="message" name="message" placeholder="MESSAGE" required="required" class="input-style"></textarea>
<div class="contact-btn">
<a title="" href="#"><input type="submit" id="submit" value="Submit"/></a>
</div>
</form>
I don't know how to write contactservlet.java.
UPDATED
Try this,
ContactUs.html
<form action="ContactServlet" method="post">
<h4>Get in <i>Touch</i></h4>
<input type="text" id="name" name="name" placeholder="Name" />
<input type="email" id="emailId" name="emailId" placeholder="Email" />
<input type="text" id="mobileNo" name="mobileNo" placeholder="Enter Mobile No." />
<textarea type="text" id="message" name="message" placeholder="Message"></textarea>
<input type="submit" id="submit" value="Submit"/>
</form>
For sending mails we used JavaMail API. Download and Documentation.
ContactServlet.java -> doPost()
//This data will be added to your Database using DAO Layer....
String name=request.getParameter("name");
String emailId=request.getParameter("emailId");
Long mobno=Long.parseLong(request.getParameter("mobileNo"));
String message= request.getParameter("message");
//Call Some function that do database storage.....
//Sending Mail Through Gmail SMTP
//Separate this code at DAO/Service Layer - - -
final String gmailUsername = "somethin#gmail.com";
final String gmailPassword = "somethin#123";
try{
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(gmailUsername, gmailPassword);
}
});
Message mailMessage = new MimeMessage(session);
mailMessage.setFrom(new InternetAddress("somethin#gmail.com"));
mailMessage.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(emailId));
mailMessage.setSubject("Type Subject : ");
mailMessage.setText("Type LONGGGG Message Here......");
Transport.send(mailMessage);
} catch(MessagingException e){
e.printStackTrace();
}