How to make my welcome text appear? - python

After login, I want the text "Welcome, Niklas" to display but after logging in I have to reload the page and I didn't understand how to make the page display the text from the server variable current_user. If I login and press reload then the correct welcome message appears. Can you help me achieve what I want? Why is there no simple working example for FB python + javascript? Can I implement facebook connect without javascript? If so, do I have to use and set the cookie myself? Thank you
{% load i18n %}
<!DOCTYPE html>
<html xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<title>
Test Facebook SDK
</title>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '164355773607006', // App ID
channelURL : '//WWW.KOOLBUSINESS.COM/static/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<fb:login-button autologoutlink="true"></fb:login-button>
{% if current_user %}
<div id="user-ident">
<span>{% trans "Welcome," %} <b>{{ current_user.name|escape }}</b></span>
</div>
{% endif %}
</body>
</html>
Here's how I get the variable current_user
#property
def current_user(self):
if not hasattr(self, "_current_user"):
self._current_user = None
cookie = facebook.get_user_from_cookie(
self.request.cookies, facebookconf.FACEBOOK_APP_ID, facebookconf.FACEBOOK_APP_SECRET)
logging.debug("logging cookie"+str(cookie))
if cookie:
# Store a local instance of the user data so we don't need
# a round-trip to Facebook on every request
user = FBUser.get_by_key_name(cookie["uid"])
logging.debug("user "+str(user))
logging.debug("username "+str(user.name))
if not user:
graph = facebook.GraphAPI(cookie["access_token"])
profile = graph.get_object("me")
user = FBUser(key_name=str(profile["id"]),
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=cookie["access_token"])
user.put()
elif user.access_token != cookie["access_token"]:
user.access_token = cookie["access_token"]
user.put()
self._current_user = user
return self._current_user

When using Oauth 2.0
FB.Init(...oauth=true)
the login button is setting a cookie into your domain named
fbsr_(appid)=....
which is encoded using the app secret key, and which do not contain the user token anymore.
If you really want to avoid the use of java script client side (which is the most simple way) you can leverage the presence of this cookie to know if the user is connected to facebook and then perform any authorization check or dynamically display a welcome message.
I do not use python, so i do not have working example, but this give you a way to search.
Hope this help.

Related

Stripe integration with Django

I am following a tutorial on stripe.com, to accept a charge it says to use the following form and capture the Token it returns in a view
Stripe "Checkout" form:
<form action="{% url 'payment' %}" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_z1bxF7Bk4Rk9PZuBFHMrYZnj"
data-amount="999"
data-name="Demo Site"
data-description="Example charge"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto">
</script>
</form>
The next step says to simply copy and paste this and your test account should be able to accept charges
Stripe view:
def payment(request):
# Set your secret key: remember to change this to your live secret key in production
# See your keys here: https://dashboard.stripe.com/account/apikeys
stripe.api_key = "sk_test_BJUliYkgS5VZEKFM1UQAz9cF"
# Token is created using Checkout or Elements!
# Get the payment token ID submitted by the form:
token = request.POST['stripeToken']
charge = stripe.Charge.create(
amount=999,
currency='usd',
description='Example charge',
source=token,
)
but stripeToken is mentioned nowhere in the form and the code returns an error because of this, can someone explain where this is coming from? (Note, the example was in Flask so I changed token = request.form['stripeToken'] # Using Flask to token = request.POST['stripeToken'] #using Django
Both of these can be found at https://stripe.com/docs/quickstart (Step 1 shows 'Checkout', step 2 shows the python code) Thanks in advance for any help.
try
token = request.GET.get['stripeToken']

Django - How to save javascript variable into Django Database? [duplicate]

This question already has answers here:
How do I POST with jQuery/Ajax in Django?
(3 answers)
Closed 4 years ago.
I have a javascript variable called "counter", which I want to use to update a counter variable instantiated in models.py.
Here is a snapshot of models.py
class Player(BasePlayer):
#track the number of times the user has lost window focus
blur_quantity = models.IntegerField(initial=0)
Here is an example of pages.html
{% block content %}
<button name="blur_button" value=counter onclick="Warn()" class="btn btn-primary btn-large">Blur Button</button>
{% endblock %}
{% block scripts %}
<script>
var counter = 0;
// Tracks window blurs
$( document ).ready(function() {
function onchange (evt) {
counter++;
console.log(counter);
}
window.onblur = onchange;
});
function Warn() {
alert(counter);
}
</script>
{% endblock %}
Now, whenever the user clicks the button, the value of "counter" should be stored somewhere. How do I update the value of blur_quantity in models.py (e.g. my Django database) to reflect the value attached to the blur_button?
JavaScript:
var counter = 0;
$( document ).ready(function() {
function onchange (evt) {
counter++;
$.ajax({
url: '/update_counter/',
data: {'counter': counter},
type: 'POST'
}).done(function(response){
console.log(response);
});
}
window.onblur = onchange;
});
views.py:
from django.http import HttpResponse
from models import Player
def update_counter(request):
if request.method == 'POST':
player = Player.objects.get()
player.blur_quantity = request.POST['counter']
player.save()
message = 'update successful'
return HttpResponse(message)
urls.py:
from django.conf.urls import url
from views import update_counter
urlpatterns = [
url(r'^update_counter/', update_counter)
]
Basically, the ajax in call in the JavaScript sends counter to the server via a POST request. urls.py routes the request to your update_counter method, which updates the database with the value of counter. Finally, the update_counter method returns a response, which is handled by the done function in the JavaScript.
Inside the onChange method, you can send a POST request to one of your server's endpoint, and let the server updates the database from there. Then the server shall respond back as a response to that POST request with the most updated value of blur_quantity, and use this value as your new counter.

Django read cookie in template tag

Is it posible to read a cookie in a template tag?
I set the cookie in a middleware but I'd like to read in a template tag.
def process_response(self, request, response):
response.set_cookie('changed', 'yes')
response.set_cookie('choose', request.LANGUAGE_CODE)
return response
Thanks
Since cookies are key/value pairs, you can read the value of a cookie in a template using the dot notation as shown below.
In your views:
def process_response(self, request, response):
response.set_cookie('changed', 'yes')
response.set_cookie('choose', request.LANGUAGE_CODE)
return response
And in your template:
{{ request.COOKIES.cookie_name }}
Marcos' answer should be accepted.
Here's how I used Marcos' answer in my case:
1 - Django view (in views.py):
from django.shortcuts import render_to_response
def helloWorld(request):
response = render_to_response("awesomeapp/hello.html", {
'person_name': "Mark"
}, context_instance=RequestContext(request))
person_age = 26
response.set_cookie('the_new_number', person_age, max_age = 5000000) # 5million secs is almost two months, adjust as appropriate
return response
2 - In marktags.py:
# To read cookies within django template, from http://stackoverflow.com/questions/26301447/django-read-cookie-in-template-tag
#register.simple_tag(takes_context = True)
def cookie(context, cookie_name): # could feed in additional argument to use as default value
request = context['request']
result = request.COOKIES.get(cookie_name,'') # I use blank as default value
return result
Note that marktags.py file, where I have all my custom filters, is stored inside the templatetags directory
(In my case, I use django-allauth so I saved my custom file marktags.py beside the template_tags.py file in myapp/allauth/account/templatetags folder)
3 - Finally, hello.html includes the following:
<head>
{% load marktags %}
</head>
<body>
{{ person_name }} is {% cookie 'the_new_number' %} years old.
</body>
Note the {% syntax, not {{ for accessing the cookie
Here's another example
If you're new to cookies, I recommend an extension such as
EditThisCookie.
You can see only the server understood how the person's name was displayed, but the browser's cookie contains the value of the person's age
You have to create a template tag with takes_context
#register.simple_tag(takes_context = True)
def custom_template_tag_name(context, value1, value2):
request = context['request']
result = request.COOKIES.get('cookie_name', '')
return result

Google App Engine: HTTP Error 403: Forbidden

I'm using Google Books API to integrate with an E-commerce site that I'm developing. The idea is to let the users search for books using a search bar, and then calling the Google API to output the number of books corresponding to the search keyword.
However, I get a 403 Forbidden error after I click submit after entering my query in the form. This is strange, because this never happened when I was testing my application on the localhost. Here's the code for my application:
main.py
class SearchHandler(Handler):
def get(self):
self.render("search.html")
def post(self):
keey = self.request.get('keey')
finaal = "https://www.googleapis.com/books/v1/volumes?q=" + keey + "&key=MY_APP_KEY"
f = urllib2.urlopen(finaal).read()
self.render("jsony.html", finaal = finaal)
app = webapp2.WSGIApplication(('/search', SearchHandler)], debug=True)
search.html
<html>
<head>
<title>Web Mining</title>
</head>
<body>
<form method = "post">
Book Name:<input type = "text" name = "keey">
<input type = "submit">
</form>
</body>
</html>
jsony.html
<html>
<head>
<title>Web Mining</title>
</head>
<body>
<form method = "post">
{{finaal}}
</form>
</body>
Now, the jsony.html is still incomplete. All I'm doing now is displaying the URL which contains the outputted json in it's raw, unprocessed form.
What seems to be causing this 403 error to arise after I deploy my application ?
EDIT 1:
The problem resolves when I remove the following line from my main python file:
f = urllib2.urlopen(finaal).read()
However, I would be needing my API's URL in order to extract data from its source code. What's happening ?
Try adding &country=US to the URL query string.

Django - Session variables does not change unless the page is refreshed

I am using a session variable to check whether the user is logged in as a contractor or an employer
When contractor :
request.session['LoggedAsContractor'] = True
When employer :
request.session['LoggedAsContractor'] = False
I then implemented two switch methods, toContractor & toEmployer, that simply changes the session variable.
From the HTML view, when I click the switch button, the variable does not change and nothing else changes, but when I refresh the page, the variable changes and everything else.
This error does not happen when running the project on the localhost, it only happens when the project is deployed (Gondor).
This is the type of session I have :
INSTALLED_APPS = (
'django.contrib.sessions',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
)
UPDATE
This is the method toContractor which is called by the button Switch
def switchToContractor(request, user_name):
request.session['LoggedAsContractor'] = True
if "employer" in request.GET['next']:
if str(request.user) == user_name:
return redirect('/contractor/' + user_name + '/')
else:
return redirect(request.GET['next'])
else:
return redirect(request.GET['next'])
The difference between request.session['LoggedAsContractor'] = True and request.session['LoggedAsContractor'] = False, is the view in the HTML.
The HTML code :
{% if request.session.LoggedAsContractor %}
<!-- Show some buttons -->
{% else %}
<!-- Show other buttons -->
{% endif %}
UPDATE 2
This is the HTML code that contains the Switch button :
{% if request.session.LoggedAsContractor %}
Switch to Employer View
{% else %}
Switch to Contractor View
{% endif %}
the url /contractor/username/switch/ redirects to the method switchToEmployer.
the url /employer/username/switch/ redirects to the method switchToContractor.
Instead of redirecting, you should instead render a response with the updated session. For example:
def my_example(request):
request.session['key'] = True
response = render_to_response("example.html", context_instance = RequestContext( request ), mimetype = "text/html" )
return response
That's not an error any request needs a response to display something to the user. Can you add your button function?

Categories

Resources