I would like to create a Django project to save tags or pixels fires from different websites in a my database:
For this reason, create the following Django model. This one, include all variables that I want to save
class Purchase (models.Model):
account = models.CharField(max_length=250, blank=True)
user_cookie = models.CharField(max_length=250, blank=True)
session_id = models.CharField(max_length=250, blank=True)
….
For collect data from other websites I saw this method. I don’t know if it’s the base way to collect this data.
<script>
var e= document.createElement("script");
e.async = true;
e.src =e.src ="https://mydomain.js;m=001;cache="+Math.random()+
"?account=0001"+
"&user_cookie=" + String(utag_data.uidCookie) +
"&session_id =" + utag_data.Session_ID);
var s =document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(e,s);
</script>
Finally, I would like to collect this javascript request in my Django database. Which url I need to use?
How can store this data in my dataset?
Thank you for your help
I think this is the solution you are looking for:
<script>
$(document).on('click', '#fire-button', function(event){
// collect all the data you want to from the webpage.
var url = "{% url 'sample_view' %}" + "?param1=" + param1 + "¶m2=" + param2 + "¶m3=" + param3;
$.ajax({
type: "GET",
url: url,
success: function(result){
alert("Success");
}
});
});
</script>
views.py:
def sample_view(request):
var param1 = request.GET.get('param1')
var param2 = request.GET.get('param2')
var param3 = request.GET.get('param3')
models.Purchase.objects.create(
account=param1,
user_cookie=param2,
session_id=param3
)
urls.py:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^sample-view$', views.sample_view, name='sample_view'),
]
Related
I'm currently coding a Flask application with a simplified version of my code below.
#app.py
from flask import Flask, render_template, request
# Configure application"'
app = Flask(__name__)
# Ensure templates are auto-reloaded
app.config\["TEMPLATES_AUTO_RELOAD"\] = True
#app.route("/")
def index():
return render_template("gettranslation.html")
#app.route("/translate")
def translate():
word = request.args.get("word")
lang = request.args.get("lang")
return render_template("translate.html", lang = lang, word=word)
The default webpage should log a translation of the given words, but instead it just logs the word before translation, though when visited the webpage being fetched takes a second to load and then shows the correct translation. How do I fetch this correct translation?
Here is simplified code from my two files:
<!--translate.html-->
<script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<div id="google_translate_element"></div>
<p id="to-translate">{{word}}</p>
<script>
var lang = "{{ lang }}";
var lang = lang[0] + lang[1];
console.log(lang);
function googleTranslateElementInit() {
new google.translate.TranslateElement(
{
pageLanguage: lang
},
"google_translate_element"
);
}
window.href = window.href + "/#googtrans(" + lang + "|en)";
</script>
<!--gettranslation.html-->
<script>
async function translate(sourcelang, destlang, word){
var url = '/translate?word=' + word + "&lang=" + sourcelang + "/#googtrans(" + sourcelang + "|" + destlang + ")";
console.log(url);
let response = await fetch(url, {redirect: 'follow'});
let text = await response.text();
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(text, 'text/html');
var translation = htmlDoc.getElementsByTagName('p')[0].innerHTML;
console.log(translation);
}
translate("fr", "en", "bonjour");
</script>
I thought using await or redirect: follow would work but neither did. I also got the idea to use #googletrans("source|dest") from this question: Trigger Google Web Translate Element if that's helpful.
Someone there saidthe Google translate select box is created after the window.load event triggers, so that is could be what is messing up my fetch request but if so I have no idea how to fix that.
Thanks in advance!
The html template is rendered at server side, this might be causing the problem with your script.
Why don't you translate the words in flask and then send them to the template? There are libraries for that such as Flask-Googletrans Flask-Googletrans.
You can translate in the view function:
from flask_googletrans import translator
ts = translator(app)
in the jinja template
<h1>{{ translate(text='your text', src='en', dest=['fr']) }}</h1>
I hope this helps
Solution:
My mistake was that the url attribute doesn't just add the string given to 127.0.0.1 but to the current url, and so the url for the Like view was supposed to be 127.0.0.1/article/article_id/like-article-commm
I wrote a django app that has articles and im trying to add a like functionality, I added the code in the bottom and nothing happens. No error just nothing in the database or the html code changes. Any idea what is the problem?
The relevent part of the html/javascript code:
<head>
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
</head>
<button id='like-button' color = 'black'> Like </button>
<script type="text/javascript">
$('#like-button').click(function(){
var article_id = '{{ article.id }}';
var user_id = '{{ user.id }}';
var like_dislike = True;
$.ajax(
{
type:"GET",
url: "like-article-commm",
data:{
article_id: article_id,
user_id: user_id,
like_dislike: like_dislike
},
success: function( data )
{
$('#like-button').css('color', 'blue'); } }) });
</script>
The like-article-comm View:
def Like_Article_View(request):
if request.method == 'GET':
article_id = int(request.GET['article_id'])
likedarticle = Article.objects.get(id = article_id)
user_liked_id = int(request.GET['user_id'])
userliked = User.objects.get(id = user_liked_id)
like_dislike_0 = request.GET['like_dislike']
like_object_list = Like_Article.objects.filter(article_liked = likedarticle, user_liked = userliked)
if like_object_list.count() > 0:
existing_like = like_object_list.filter()
if existing_like.like_dislike == like_dislike_0:
return HttpResponse('success')
existing_like.like_dislike = like_dislike_0
existing_like.save()
like_new_object= Like_Article(article_liked=likedarticle, user_liked=userliked, like_dislike=like_dislike_0)
like_new_object.save()
return HttpResponse('success')
else:
return HttpResponse("unsuccesful")
urls.py file:
from django.urls import path
from . import views
from .views import ArticleListView, ArticleDetailView, ArticleCreateView, ArticleUpdateView, ArticleDeleteView
urlpatterns = [
path('', ArticleListView.as_view(), name="home-comm"),
path('article/<int:pk>/', ArticleDetailView.as_view(), name="article-comm"),
path('like_article/', views.Like_Article_View, name='like-article-commm'),
]
I can add like objects to the database manually.
--update--
After some discussion, we figure out that frontend ajax is not communicating with the backend properly. With chrome devtools we managed to pin point where the issue lies.
have you enabled CORS cross site resource sharing?
I convert the current mxGraph the user creates into XML which is stored in the database (ajax.js). I return this in my views as a JSONResponse to my ajax request (views.py).
The data stored in the database saves, as I have checked in the Django administration page and the xml gets updated per save button.
This is all working fine, however the issue is that when I refresh the page the graph created does not stay on the page.
ajax.js
var button = mxUtils.button('Save', function()
{
//var url = "{%url'login'%}"
//var url = "{% url 'myapp:productdetail' %}";
//location.href = '/saveData/'
var encoder = new mxCodec();
var node = encoder.encode(graph.getModel());
var xml = mxUtils.getPrettyXml(node);
var csrftoken = getCookie('csrftoken');
$.ajax({
type: "POST",
url: "/saveData/",
data: { "xml": xml},
headers:{
"X-CSRFToken": csrftoken
},
success: function(data){
//console.log("data" + data[0])
//console.log(graph)
//var xmlDoc = data[0]
var xmlDoc = mxUtils.parseXml(data[0]);
//var xmlDoc = mxUtils.load("/saveData/").getXml();
//console.log("xmlDoc " + xmlDoc)
var node = xmlDoc.documentElement;
//console.log("node " + node)
var dec = new mxCodec(node.ownerDocument);
//console.log("dec " + dec)
//console.log("graph model " + graph.getModel())
dec.decode(node, graph.getModel());
}
});
views.py
def saveData(request, user):
if request.method == "POST":
#Get user profile
member = Member.objects.get(username=user)
#Get XML data once user presses save
#xmlData = request.POST['xml']
member.data = request.POST['xml']
member.save()
print(member.data)
response = JsonResponse([
member.data
], safe = False);
#return render(request, 'fastcookapp/index.html', {"xmlData": member.data})
return HttpResponse(response, content_type="application/json")
return HttpResponse('POST is not used')
models.py
class Member(User):
data = models.TextField(null=True)
def __str__(self):
return self.username
P.S I have no clue why my JS is not coming in colour, I have added the javascript tag and it's not working... sorry in advance
I had to create an Ajax GET request and decode the mxGraph as done above.
I am getting an error saying unexpected token while trying for passing id from django template to reatjs for uploading multiple images to its associated foreign key object. The error is shown as unexpected token }. In depth it is shown as
in console
var uploadUrl = {
url:
};
What i am trying to do is , I have created a listing page with multiple form and it is entirely developed using reactjs. I want user to fill the data about room and upload multiple images related to their room. There are two models one with room info and another gallery(multiple image is associated with one rent). I wanted the uploaded images be associated with its rent so i coded it as below
urls.py
urlpatterns = [
url(r'^add/$', AddView.as_view(), name="add"),
url(r'^add/space/$', AddSpaceView.as_view(), name="addSpace"),
url(r'^upload/image/(?P<pk>\d+)/$', ImageUpload, name="ImageUpload"),
]
views.py
def ImageUpload(request,pk=None): // for saving images only to its asscoiated rent
if request.POST or request.FILES:
rental = Rental.objects.get(id=pk)
for file in request.FILES.getlist('image'):
image = GalleryImage.objects.create(image=file,rental=rental)
image.save()
return render(request,'rentals/add.html')
class AddView(TemplateView): // for listing page
template_name = 'rentals/add.html'
class AddSpaceView(View): // for saving data to database except image
def post(self,request,*args,**kwargs):
if request.POST:
rental = Rental()
rental.ownerName = request.POST.get('ownerName')
rental.email = request.POST.get('email')
rental.phoneNumber = request.POST.get('phoneNumber')
rental.room = request.POST.get('room')
rental.price = request.POST.get('price')
rental.city = request.POST.get('city')
rental.place = request.POST.get('place')
rental.water = request.POST.get('water')
rental.amenities = request.POST.get('amenities')
rental.save()
return HttpResponseRedirect('/')
listing.js(ajax code for uploading multiple image)
var image = [];
image = new FormData(files);
$.each(files,function(i,file){
image.append('image',file);
});
$.ajax({
url:"/upload/image/", // want to used id over here that is passed from add.html script tag so that image will be uploaded to its associated foriegn key object
data:image,
contentType:false,
processData:false,
type:'POST',
mimeType: "multipart/form-data",
success: function(data) {
console.log('success');
}
});
}
add.html page
<div id="listing">
</div>
{% include 'includes/script.html'%}
<script type="text/javascript">
var uploadUrl = {
url: {% for rental in object_list %} { "id": {{ rental.id }} } {% endfor %} // here is an error
};
console.log('url is', url);
$(function() {
app.showListingSpaceForm("listing");
});
</script>
The code might explained what i was trying to achieve. If models.py is also required for more scrutiny then i will update it.
You're missing a fundamental piece: TemplateView has no concept of object_list, you have to populate it yourself. If your view is simple enough use ListView and set your model property. If not, you have to manually populate the object list, something like this:
def get_context_data(self, **kwargs):
context['object_list'] = MyModel.objects.all()
That was just an example to set you on the right path.
Basically, I want to have an interactive button on my website, that, when clicked, sends some data to the server in order to be checked and display the response (without form sending / page reload).
I thought it would be something like:
function checkData()
{
var req = new XMLHttpRequest();
var conf = document.getElementById('my_text_area').value;
req.open("GET", 'check_data', true);
req.onreadystatechange = function ()
{
var pre = document.getElementById('check_data_out');
pre.innerHTML = req.responseText;
}
req.send(conf);
return false;
}
And on the server side:
#get('/check_data')
def check_data():
# Process the content and answer something...
content = str(request.is_ajax) + ' - ' + str(request.GET) + ' - ' + str(request.POST)
return content
But this obviously doesn't work. Either it is not the right way to send data via javascript or not the right way to access it in bottle.py.
Showing me how it works is highly appreciated.
You can use dojo for client side logic.
var button = dojo.byId('button_id'); // button_id refers to the id of the button you want to click
dojo.connect(button,'onclick',dojo.xhrGet({
url: '/check_data',
handleAs : 'text',
load : function(response){
dojo.byId('button_id').innerHTML = response;
}
}));