Passing Parameters to a Mail Script - python

I want to send an email from python using the below codes i wrote/reffered
<script>
$(document).ready(function() {
$("#form1").submit(function(){
$("#form1").validationEngine();
if($('div input[type=text]').val() != "")
{
var textfield2=document.getElementById("textfield2").value;
var textarea=document.getElementById("textarea").value;
var dataS=$("#form1").serialize();
$.ajax({
type: "POST",
crossDomain: 'true',
url: "mail.py",
success: function( ){
alert("completed");
},
error: function(){
alert(dataS);
}
});
}
return false;
});
});
</script>
For the mail part , i reffered the below google code
from google.appengine.api import mail
mail.send_mail(sender="Example.com Support <support#example.com>",
to="Albert Johnson <Albert.Johnson#example.com>",
subject="Your account has been approved",
body="""
Dear Albert:
Your example.com account has been approved. You can now visit
http://www.example.com/ and sign in using your Google Account to
access new features.
Please let us know if you have any questions.
The example.com Team
""")
Now the question is , on ajax call .. How can i recieve the HTML parameters in the mail.py script? pls help i'm new to python

Within a cgi script, if you instantiate a cgi.FieldStorage(), it is automatically filled with the GET or POST parameters. If you want to post content, then just add a data property to your ajax request object:
$.ajax({
...
data: {param1: 'value1', param1: 'value2', ...}
...
})
In your python script it should the be enough to do:
import cgi
store = cgi.FieldStorage()
par1 = store.getfirst('param1')
...
One more thing -
Ask yourself: do you really want to submit the form when the page is loaded? (Your're using the 'ready' event). Wouldn't it be better to wait until somebody has entered somehting in the form?

Related

How to add link previews in django?

I'm doing a chat app in python Django and I Want to implement Link preview while typing that ink in chat box. Anybody familiar with this please help.
You can use a Link preview API service - [1]: https://www.linkpreview.net/
Try this code .
$.ajax({
url: "https://api.linkpreview.net",
dataType: 'jsonp',
data: {q: "message URL", key: 'your API key'},
success: function (response) {
let data=response;
console.log(data);
}
});

URL sent to Django using AJAX is different when printed from Django

I have a JQuery event that, when a link is clicked, an AJAX POST request is sent to a Django function. There I print the recieved url and do other stuff with it. However, when it is printed (by Django) some characters in the url are changed.
The specific url this happened with was :
https://www.catholicleague.org/05press_releases/quarter%204/051110_put_on_notice.htm
Which was printed as :
https://www.catholicleague.org/05press_releases/quarter+4/051110_put_on_notice.htm
Where %20 was changed to +
Here is the AJAX and Django code:
$("a").on("click", function(e){
e.preventDefault();
if(e.target.href){
let clicked_source = e.target.href;
let csrf_tok = parent.document.getElementById("csrf_tok").value;
$.ajax({
url: "/change_origin/",
data: JSON.stringify({"clicked_source":clicked_source}),
type: "POST",
beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrf_tok );},
success: function(response) {
console.log(response.msg)
},
error:function(error) { console.log(error); }
});
}
});
def change_origin(request):
if request.method == 'POST':
received = ast.literal_eval(request.body.decode())
print(received)
clicked_source_url = received['clicked_source']
return JsonResponse({'msg': "ok"})
Where decode is used as the JSON object is received in Python as a byte-like object. And ast is used to turn the string representation of the object to an actual object (or dict) for access.
I need either:
1) A way to just send a string from Ajax to Django
2) A better way to deal with the received object as I believe using .decode() might be the one causing this issue.
EDIT: The link is the second link in the "origin" part of this article
https://www.snopes.com/fact-check/an-unmerried-woman/

Django get request via ajax making two requests

I am working on passing data from ajax to a Django view. However, ajax somehow is making 2 GET requests: one with the query string and the other without it. In the view when I try to get the query string its empty.
Ajax code:
<script>
$( document ).ready(function() {
var query = "{{ item.ipv4_address }}";
$("#clickid").click(function() {
$.ajax({
url: "/reserve/run/?ip=",
type: "GET",
data: {ip:query},
success:function(data){
console.log(data);
}
});
});
});
</script>
Django view:
def run_script(request):
if request.GET:
ip = request.GET['ip']
print ip
return render_to_response('test.html',{'item':ip})
Two urls:
[16/Dec/2017 07:43:56] "GET /reserve/run/?ip=198.18.101.123 HTTP/1.1" 200 570
[16/Dec/2017 07:03:58] "GET /reserve/run/ HTTP/1.1" 200 1
urls.py file
url(r'^run/$',views.run_script,name='run_script'),
Please let me know where I am going wrong. Also, let me know if you need any more info. Any pointers is appreciated.
If you are passing query parameter in your data attribute you need not to send it in url parameter.Update your url parameter as:
$.ajax({
url: "/reserve/run/",
type: "GET",
data: {ip:query},
success:function(data){
console.log(data);
}
});
I found the error. In my tag, I had mentioned the URL too. {% url 'run_script' %}. This was sending that extra GET request. Once I removed it, the issue resolved.

Asynchronously update page with data that are stored by middleware

I have middleware, that stores all http requests into DB.
Also I have view, that fetches data from DB and put this data into the context.
views.py
def requests(request):
http_requests = WebRequest.objects.all()
context = {
"http_requests": http_requests
}
return render(request, "requests.html", context)
How can I asynchronously update data on this page as new requests come in (so, new requests should appear on this page asynchronously)? Can I use only Django features to achieve such behavior or I need to use some javascript libraries?
It depends on how much time you want to spend on the project. As Lorenzo stated, it might make sense to create an API and have javascript-frameworks (e.g. emberjs or angularjs) handle the asynchronity. I dont think you can handle this with pure django...
If you don't have time and are in for some 'hack' you could just replace the content of your page by polling the url and replacing the whole document with the response:
$.ajax({
type: "GET",
url: "<url_to_your_requests_view>",
success: function(response){
$('body').html(response);
}
});
This is NOT clean, but should work as a quick an dirty trick...
EDIT: If you only want to exchange certain parts of your site, you can break it down to just add elements to the page:
$.ajax({
type: "GET",
url: "<url_to_your_requests_view>",
success: function(response){
var newlyAddedRows = // find your newly added rows through some jquery
newlyAddedRows.forEach(function(row){
$('#request-holder').append(row);
});
}
});
OR WITH JSON
$.ajax({
type: "GET",
url: "<url_to_your_requests_api_endpoint>",
success: function(response){
var requestRows = response.requestItems
var $requestsHolder = $('#request-holder');
$requestHolder.empty();
requestRows.forEach(function(row){
requestsHolder.append('<div class="request-row">' + <visualize your data somehow> + '</div>'); //e.g. row.timestamp if you have that in your json
});
}
});

how to read a file using ajax and django?

My Ajax code:
var upfile = $("#file-id").val().split(/[\/\\]/).pop();
$.ajax({
type: 'POST',
url: '/upload/',
data:{"upfile":upfile},
success: function(data) {
if (data['success'] === "true") {
}
},
dataType: 'json'
});
return false;
Django code:
In simple form submit action request.FILES.get('upfile') works. I can read the content of file using read() But in ajax, it is not working. even request.POST.get('upfile') gives me the filename string.
How to solve this issue?
It's normal, by default a form submitted with Ajax will not upload files. You need o have a look to some file upload jquery plugins (there's a few of them, I can not suggest one as I did not try any of these yet)

Categories

Resources