Passing values via post with Django - html

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

Related

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

How to save non-input field(which is coming from DB) in different database table in node.js?

I am trying to save user login id (which is coming when user logged in application) in different table(User_assessment).But user_assessment table have different input form.So when itry to export only user input data getting export and i am only able to save assessment data not the user login details.I want to save assessment data with user login detaile so when i check the history data only come for the user who logged in.
the export code and HTMl is given below:-
HTML:-some part of code
<div class="form-group">
<label for="fullName"><b>User Name : </b></label>
<a name = "namehelp">{{user.User_Name}}</a>
<label for="fullName"><b>User Email : </b></label>
<a name = "UserEmail">{{user.User_Email}}</a>
</div>
<div class="form-group">
<label for="fullName">Team/Project Name </label>
<input type="name" required class="form-control" name="TeamName" id="fullName" aria-describedby="nameHelp" placeholder="Enter full project name" >
<small id="nameHelp" class="form-text text-muted">Please enter your team/project name.</small>
</div>
auth.js :-
exports.assessment = (req,res) => {
console.log(req.body);
Set an onsubmit on your form and in its function first stop default behavior of form with e.preventDefault() and then get your inputs data and add your login id and then send them with an ajax request to nodejs.
<form id="myForm" onsubmit="yourFunction(event)" >
<!-- some inputs -->
</form>
yourFunction(e){
e.preventDefault();
let data = new FormData(e.target)
data.append("loginId" , yourLoginId)
// create XMLHttpRequest and send data to nodejs
}

get input form not as variable but as url

I am building a webservice so people can search into the database. Lets say I have users and companies. Each user and company can be found thought their id. So if you search myurl/users/<id> you get information of that user, on the other hand if you search company/ you get information of that company.
For this I have created two simple input texts (one for users and another for companies) where people can type the <id>. My problem is that when I get the value from the input text I get this myrul/users?<id> and not myurl/users/id. I tried to hardcode the slash but then I get myrul/users/?<id>.
So my question is how can I get input text as a url and not as a variable.
I am using flask so my html has jinja2 code like this:
<!-- USER id -->
<form method='GET' action={{url_for('get_info_by_id', type_collection='user')}}>
<input type="text" name="my_id"/><input type="submit" value="Go">
</form>
<!-- COMPANY id-->
<form method='GET' action={{url_for('get_info_by_id', type_collection='company')}}>
<input type="text" name="my_id"/><input type="submit" value="Go">
</form>
In my python script (flask)
#app.route('myurl/<type_collection>/<my_id>')
get_info_by_id(type_collection,my_id):
# search into the database and return info about that id
As #dirn suggested in the commentary, I made it through JavaScript, here is the code if someone else is also interested:
HTML:
<!-- USER id -->
<form method='GET' class="search" id="user" action="">
<input type="text" name="my_id"/><input type="submit" value="Go">
</form>
<!-- COMPANY id-->
<form method='GET' class="search" id="company" action="">
<input type="text" name="my_id"/><input type="submit" value="Go">
</form>
JS:
$(".search").submit(function( event ){
event.preventDefault();
var my_id = $(this).find(":input").val();
url = 'myurl/'+ $(this).attr("id") + '/' + my_id;
window.location.href = url;
});
python (flask)
#app.route('myurl/<type_collection>/<my_id>')
get_info_by_id(type_collection,my_id):
# search into the database and return info about that id
Is there a reason you cannot use the variable, or are you just trying to get it into a URL so that you can do your search? I went out on a limb and assumed you just want the form and database search to work, so try the following out.
Adjust your route like so:
#app.route('myurl/<type_collection>/')
def findAllTheThings():
if not request.form['my_id']: # Just check if a specific entity is chosen
return render_template('YourTemplateHere') # If no entity, then render form
entity_id = request.form['my_id']
get_info_by_id(type_collection, entity_id):
# search into the database and return info about that id
Now adjust the template as follows:
<!-- USER id -->
<form method='GET' action={{url_for('findAllTheThings', type_collection='user')}}>
<input type="text" name="my_id"/><input type="submit" value="Go">
</form>
<!-- COMPANY id-->
<form method='GET' action={{url_for('findAllTheThings', type_collection='company')}}>
<input type="text" name="my_id"/><input type="submit" value="Go">
</form>
Now, if no entity has been selected you'll just render the form. You can throw in a flash to let them know they need to select a specific ID, or just let them figure it out. If an entity has been selected, you will call the fucntion correctly.

multiple submit button values with multipart/form-data

Working on a Multipart File Upload form. Using Java with Servlet 3.0. It seems with multipart, the value of the submit button is not passed to the server?
e.g.
<form method="POST" enctype="multipart/form-data" action="/servlet">
<input type="hidden" name="mode" value="image">
<input type="hidden" name="id" value="123">
<input type="file" name="file" id="file">
<input type="submit" name="action" value="Upload">
<input type="submit" name="action" value="Delete">
</form>
In a regular post, you would just check the value of the "action" parameter. How do you access this in a multipart form? I tried examining the Parts in the request, and it's just not there.
e.g.
Collection<Part> parts = request.getParts();
System.out.println("parts: "+parts.size());
for(Part part : parts){
System.out.println(part.getName());
}
Outputs:
parts: 3
mode
id
file
As in...
String mode = request.getParameter("mode"); //reads "image"
String id = request.getParameter("id"); //read "123"
String action = request.getParameter("action"); //reads null
How do you solve this one?
Have a hidden field declared and set its value based on the Submit button clicked , before you submit , using Javascript
<input type="hidden" name="submitType" value="">
first import multipart jar file in your program then
try to use multipartrequest class for accessing multipart data from your form -
MultipartRequest mpr=new MultipartRequest(request,"C:");
String ad=mpr.getParameter("made"); // read "image"
String ad=mpr.getParameter("id"); // read "123"
String ad=mpr.getParameter("action"); // if u submit from from upload then it read "upload" or submit from delete then it read "delete" String .

Email sending in django code is not working

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.')