Email sending in django code is not working - html

Email sending in django code is not working,
it display error "[Errno 10061] No connection could be made because the target machine actively refused it"
these are my VIEWS.PY
def send_email(request):
username = request.POST.get('username', '')
from_email = request.POST.get('from_email', '')
message = request.POST.get('message', '')
if username and message and from_email:
try:
send_mail(username, from_email, message, ['canonizadocharm#ymail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return HttpResponseRedirect('/contact/thanks/')
else:
# In reality we'd use a form class
# to get proper validation errors.
return HttpResponse('Make sure all fields are entered and valid.')
these are my contact.html
<FORM METHOD="POST" ACTION="/send_email/" >
{% csrf_token %}
Name: <INPUT TYPE="text" NAME="username"><BR>
Email: <INPUT TYPE="text" NAME="from_email"><BR>
Message: <BR>
<TEXTAREA NAME="message" ROWS="10" WRAP="hard">
</TEXTAREA>
<INPUT NAME="redirect" TYPE="hidden">
<INPUT NAME="NEXT_URL" TYPE="hidden">
<BR>
<INPUT TYPE="submit" VALUE="Send">
<INPUT TYPE="reset" VALUE="Clear">
</FORM>
these are my URLS.PY
url(r'^send_email/', views.send_email),
url(r'^contact/', views.contact),
url(r'^thanks/', views.thanks),
and my SETTINGS.PY
EMAIL_HOST = 'localhost'
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 25
EMAIL_USE_TLS = True

Your action value of form must direct to view's url, mailto:canonizadocharm#ymail.com is not a valid path on your server.
UPDATED:
For example, add a new rule to urls.py like,
url(r'^mail/', views.send_mail),
Then change action value to mail.

Have your action value point to a URL, which in turn points to one of your views. For instance, your urls.py can do this.
url(r'^email/', 'project.views.send_email')
This will route your contact form to your send_mail view.

Your form in the templates has no csrf that's why you get an error of "CSRF verification failed".
<FORM METHOD=POST ACTION="/send_email/" ENCTYPE="text/plain">{% csrf_token %}
...........
</FORM>
If you want to know what is csrf just go to this link:
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/
Create email setting in your settings.py, like this for example:
settings.py
# Sending mail
EMAIL_USE_TLS = True
EMAIL_HOST='smtp.gmail.com'
EMAIL_PORT=587
EMAIL_HOST_USER='your gmail account'
EMAIL_HOST_PASSWORD='your gmail password'
views.py
from django.core.mail import send_mail
def send_email(request):
if request.method == 'POST':
username = request.POST.get('username')
message = request.POST.get('message')
from_email = request.POST.get('from_email')
send_mail(username, message, from_email, ['canonizadocharm#ymail.com',])
return HttpResponseRedirect('/contact/thanks/')
else:
return HttpResponse('Make sure all fields are entered and valid.')

Related

I am trying to create authentication system in Django. My code is failing to authenticate the user

<form method="post" action="/" class="mb-2">
{% csrf_token %}
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Enter Your Username" Required>
</div>
<div class="form-group">
<label for="pass1">Password</label>
<input type="password" class="form-control" id="pass1" name="pass1" placeholder="Enter Your Password" Required>
</div>
<button type="submit" class="btn btn-primary">Log In</button>
</form>
This is the form from home.html
def home(request):
if request.method == 'POST':
username = request.POST.get('username')
pass1 = request.POST.get('pass1')
user = authenticate(username=username, pass1=pass1)
if user is not None:
login(request, user)
return render(request,"main_tem/room.html")
else:
return redirect('signup')
return render(request,"main_tem/home.html")
this is home view from views.py in 'main' app.
so as u can see from the home view if user is present or signuped it should redirect user to room.html page but when i try to do it it redirects to signup page which shouldnt happen if user is already present in data base. i am kind of lost here as i dont know what kind of solution i should search for. from what i have observed i think home view is not able to get data from the form in home.html
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns=[
path("",views.home,name="home"),
path("signup",views.signup,name="signup"),
path("rooms",views.rooms,name="rooms"),
]
for reference here is the urls.py from 'main' app
Change this,
def home(request):
if request.method == 'POST':
username = request.POST.get('username')
pass1 = request.POST.get('pass1')
user = authenticate(username=username, pass1=pass1)
if user is not None:
login(request, user)
return render(request,"main_tem/room.html")
else:
return redirect('signup')
return render(request,"main_tem/home.html")
to this:
def home(request):
if request.method == 'POST':
username = request.POST.get('username')
pass1 = request.POST.get('pass1')
auth = authenticate(username=username, password=pass1)
if auth:
login(request, auth)
return render(request,"main_tem/room.html")
else:
return redirect('signup')
return render(request,"main_tem/home.html")
You should be go to go.

CSRF verification failed. Request aborted [New] 2021

I am completely tired with the csrf issue. I have created a sign in form and register form.
I am able to login and logout, even register a user.
The main problem I am facing is the refresh-after-signin.
After signing in, if I refresh the page it simply gives a csrf verification failed error.
I have literally searched for it since past two days with no solution, all the answers are almost 4-5 years older, which are not helping.
This is the views.py signin function.
def signin(request):
if request.method=="POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password)
if user is not None:
login(request,user)
messages.success(request,"Logged in Successfully!")
return render(request,'authtest/index.html')
else:
messages.error(request,"Bad Credentials")
return redirect('index')
return render(request,'authtest/signin.html')
This is the HTML form that is returning POST request
<form action="{% url 'signin' %}" method="POST">
<!-- I have no idea what this thing does -->
{% csrf_token %}
<!-- I have no idea what this thing does end -->
<input type="hidden" id="csrf_token" value='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>
<label for="username">UserName</label>
<input type="text" name="username" id="username" required>
<label for="password">Password</label>
<input type="password" name="password" id="password" required>
<button type="submit">SignIn</button>
</form>
Due to some security issues to keep each user's session safe, it is not possible to authenticate and render the url in the same view functions.
Therefore, you must perform the rendering operation in another URL after redirecting
something like this
def signin(request):
if request.method=="POST":
........
if user is not None:
..........
return redirect ('dashboard')\
and that dashboard func is like this
def dashboard(request):
.......
return redirect ('dashboard')

(DJANGO) retrieving data from html form using GET/POST

This is part of the CS50W courseware Project 1. I have tried to retrieve a user input from a form using a get method. However, the search_query variable in views.py does not have any input. I then changed the get methods to post methods and it worked. Why is that so?
layout.html (GET method)
<form action="{% url 'search' %}" method="GET">
<input type="search" name="search_query" placeholder="Search Encyclopedia">
</form>
views.py (GET method)
def search(request):
search_query = request.GET['search_query']
if search_query in util.list_entries():
return redirect('entry_page', title=search_query)
for entry in util.list_entries():
if search_query in entry:
return redirect('search_results')
layout.html (POST method)
<form action="{% url 'search' %}" method="POST">
{% csrf_token %}
<input type="search" name="search_query" placeholder="Search Encyclopedia">
</form>
views.py (POST method)
def search(request):
search_query = request.POST['search_query']
if search_query in util.list_entries():
return redirect('entry_page', title=search_query)
for entry in util.list_entries():
if search_query in entry:
return redirect('search_results')
I think this is due to differences in the nature of http requests. In POST requests we send the data separately, but in GET requests we have to put them in the url. You probably expect form to do this for you, but it does not! This means that this form will not put the parameters in the url in GET mode.

django inserting data into db using html template

I'm new in django. I'm trying to connect already made an html file to django backend without rebuilding whole file.
Already created forms and views in python but have no idea what to put into html file.
view class:
class signup(View):
template = loader.get_template('signup.html')
form_class = UserRegistrationForm
def get(self, request):
form = self.form_class(None)
return render(request, 'signup.html', {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
current_user = form.save(commit=False)
email = form.cleaned_data['email']
password = form.cleaned_data['password']
current_user.set_password(password)
current_user.save()
userToAuthenticate = authenticate(email=email, password=password)
if userToAuthenticate is not None:
if userToAuthenticate.is_active:
login(request, userToAuthenticate)
return redirect('siteViews:index')
return render(request, 'signup.html', {'form': form})
form code:
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['email', 'password']
and html code:
<div id="registersquare">
<div id="panel">
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<label for="email">Email adress:</label>
<input type="email" id="username" name="email}">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<label for="password">Repeat password:</label>
<input type="password" id="password" name="repeatedpassword">
<label class="control-label col-sm-2" for="password">{{ field.label_tag }}</label>
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox"><a style="color: #999999;" href="#">I Accept Website Terms And Conditions.</a></label>
<input type="submit" value="Sign up">
</div>
</form>
</div>
</div>
anyone can explain how to do it?
cheers
You hav already created a Form, which is not Django's form, so you dont actually have to write anything in forms.py, as the purpose of it is to create an form based on the model structure and perform validations according to the fields defined.
Now you have to fetch data from form and perform the validation and checks by yourself in views. So the post would be
def post(self, request):
email = request.POST.get('email') # get value in name="email" field
password = request.POST.get('password')
repeatedpassword = request.POST.get('repeatedpassword')
if password == repeatedpassword: # manual validation to check if both string are same
# Other Validations code here and
# Register or Login etc functions here
return render(request, 'signup.html', {'form': form})
You need to delete the labels and inputs from your html file and add this tag after the {% csrf_token %}, {{form.as_p}}, that's a start. You are also using an older version of Django, the way I can tell is because when you defined your ModelForm you wrote forms.ModelForm when it has been changed to just ModelForm, to upgrade write
pip install -U Django
You essentially created two forms, one with just html and one with Django only you did not apply your ModelForm to your html file instead you just made a html form instead of a html rendered Django ModelForm.

Passing values via post with Django

I'm trying to make a signup form via html/django so I have 3 input boxes for the user to put in the email, username, and password that then sends them via POST to /adduser
<form action="/OmniCloud_App/adduser" method="post">
{% csrf_token %}
Email Address: <input type="text" name="email" /></br>
Username: <input type="text" name="username" maxlength=25 /></br>
Password: <input type="password" maxlength=30 /></br>
</br>
<input type="submit" value="Send" /> <input type="reset">
</form>
adducer creates a new User and saves it to the DB:
def adduser(request, email, username, password):
u = User(email=email, username=username, password=password)
u.save()
return render_to_response('adduser.html', {'email':email, 'username':username, 'password':password})
but when I click submit on /signup, it complains that I am only giving it 1 parameter when 3 were expected. How should I pass the email,username, and password fields from signup.html to the username function (located at /username)?
If you read part 3 of the tutorial, you'll see that the view function expects parts of the URL itself as arguments. If you read part 4 of the same tutorial, you'll see that POST parameters come in via request.POST. Further in the documentation, you'll learn that you can write Form classes that handle both the generation and validation of HTML forms.
they will be in request.POST, which you can query like you would a dict
email = request.POST.get('email')
username = request.POST.get('username')
password = request.POST.get('password')