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?
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
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'),
]
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.
I'm following a tut from here but I can't get the ajax to work, also I did checked the headers in chromes console, but I didn't see a text/json header as well! Could you please help me with it I can't figure it out.
Thanks in advance.
main.py
class Main(webapp2.RequestHandler):
def get(self):
if self.request.get('fmt') == 'json':
data = {'name' : 'sam', 'age': 25}
self.response.headers['content-type'] = 'text/json'
self.response.write(json.dumps(data))
return
self.templateValues = {}
self.templateValues['title'] = 'AJAX JSON'
template = jinja_environment.get_template('index.html')
self.response.write(template.render(self.templateValues))
app = webapp2.WSGIApplication([('/.*', Main),], debug=True)
index.html
<input type ="button" id="getitbutton" value="click button"/>
<div id= "result">
</div>
js script
<script type="text/javascript" >
function showData(data){
console.log(data.name);
$('#result').html(data.name)
}
function handleclick(e){
$.ajax('/',{
type: 'GET',
data: {
fmt: 'json'
}
success: showData
});
}
$(document).ready(function(){
$('#getitbutton').on('click', handleclick);
});
</script>
There are some problems with the current browsers, especially IE which does not send the text/json content type header. So I learned not to depend on the headers.
Instead my solution to this is like this:
The js ajax function:
function ajax(url,obj,callback){
var xhr=new XMLHttpRequest;
xhr.onreadystatechange=function(){
if(this.readyState==4){
if(callback){
callback(this.responseText);
}
}
}
xhr.open("POST",url);
xhr.send(JSON.stringify(obj));
}
Then on the server side, I read directly from the Request Body (sorry for the Go code, but I think you can also get the Request body from Python runtime?):
// read the request body
body, _ := ioutil.ReadAll(httpRequest.Body)
// parse the json payload
var user struct {
Email string
Password string
}
json.Unmarshal([]byte(body), &user)
Hope this helps
I'm trying to add 'Share on Twitter' functionality on one of the pages of my Django-powered site. Here's the relevant portion of link_page.html:
<a class="tweet_link metaSpacing" data-link_id={{ link.id }}>Share on Twitter</a>
Here's the JavaScript portion responsible for listening for events:
// tweet_link
$('.tweet_link').click(function(e){
link_id = $(this).attr('data-link_id');
var target = $(this);
tweetLink(target);
});
function tweetLink(t){
link_id = t.attr('data-link_id');
$.ajax({
type: "POST",
data: { "link_id": link_id, "csrfmiddlewaretoken": csrfmiddlewaretoken},
url: "/tweet_link",
});
};
In Django I added the following line at the end of the urls.py:
url(r'^tweet_link/?$', 'portnoy.views.tweet_link'),
And here's the Django view itself:
# tweet the link
def tweet_link(request):
c = RequestContext(request)
twitter = Twython(
twitter_token = TWITTER_KEY,
twitter_secret = TWITTER_SECRET,
oauth_token = request.session['request_token']['oauth_token'],
oauth_token_secret = request.session['request_token']['oauth_token_secret']
)
twitter.updateStatus(status="See how easy this was?")
return HttpResponse('')
However, what happens when I click on the 'Share on Twitter' link, I get this error on Chrome Console:
POST http://127.0.0.1:8000/tweet_link 404 (NOT FOUND)
Any idea how to fix this? Thanks in advance!
Your url shouldn't have a ? in it:
url(r'^tweet_link/$', 'portnoy.views.tweet_link'),
You know that you can simply launch a link with this URL to tweet something:
https://twitter.com/intent/tweet?source=webclient&text=d+twitter+msg+goes+here