External url in Django template - django

I got receipt url from stripe like:
"receipt_url": "https://pay.stripe.com/receipts/acct_1FpzDdEHHOJvKiFZ/ch_1IsB5REHHOJvKiFZGxagDBoQ/rcpt_JVBS4giqfp3YUoHcqzjQAwMHWq",. I added to template as:
<div class="status-message">{{ transID.receipt_email }}<br/>Find your Receipt here:</div>
When i click on the link i'm redirected to the same page.
view storing fields from stripe:
transID = stripe.PaymentIntent.retrieve(session.payment_intent)
context = {
'customer': customer,
'transID': transID,
}
Is there a way when clicking on the link to redirected to the stripe's receipt_url?
Many thanks.

Is it possible that the receipt_url is empty? That would likely cause the behaviour you're describing. Maybe try logging it to make sure it's actually present.

Related

Django redirect page does not update the view

I'm using the Django Framework on Google App Engine.
I have multiple forms on the same view, to submit to different URL.
Trouble is after I get a form submitted: even if the called method update the datastore and some data, the previous page (where the forms are put in) is not refreshed, showing the updated data.
I could solve this problem using jQuery or some javascrip framework, appending dinamically content returned by the server but, how to avoid it?
Suggestions?
Am I wrong somewhere?
A part of "secure.html" template
<form action="/addMatch" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Matches:
<br />
{% for m in matches%}
{{m.description}} ---> {{m.reward}}
{% endfor%}
the "/addMatch" URL view:
def addMatch(request):
form = MatchForm(request.POST)
if form.is_valid():
user = User.all().filter('facebookId =', int(request.session["pbusr"]))
m = Match(user=user.get(),description =form.cleaned_data["description"],reward=form.cleaned_data["reward"])
m.save()
return HttpResponseRedirect("/secure/")
else:
logging.info("Not valid")
return HttpResponseRedirect("/secure")
The view method whose seems not working:
#auth_check_is_admin
def secure(request):
model={}
user = User.all().filter('facebookId =', int(request.session["pbusr"]))
u = user.get()
if (u.facebookFanPageId is not None and not u.facebookFanPageId == ""):
model["fanPageName"] = u.facebookFanPageName
model["form"] = MatchForm()
model["matches"] = u.matches
else:
....
return render(request,"secure.html",model)
Francesco
Based on what you posted, it seems like you're redirecting properly and are having database consistency issues. One way to test this would be to look at the network tab in the Google Chrome developer tools:
Click on the menu icon in the upper right
Click on "Tools"
Click on "Developer Tools"
Click on "Network" in the thing that opened up at the bottom of the screen.
Now, there will be a new entry in the network tab for every request that your browser sends and every response it receives. If you click on a request, you can see the data that was sent and received. If you need to see requests across different pages, you might want to check the "Preserve log" box.
With the network tab open, go to your page and submit the form. By looking at the network tab, you should be able to tell whether or not your browser issued a new GET request to the same URL. If there is a new request for the same page but that request has the old content, then you have a datastore consistency issue. If there was NOT a new request that yielded a response with the data for the page, then you have a redirect issue.
If it turns out that you have a datastore consistency issue, then what's happening is the data is being stored, but the next request for that data might still get the old data. To make sure that doesn't happen, you need what's called "strong consistency."
In a normal App Engine project, you get strong consistency by putting entities in the same entity-group and using ancestor queries. I'm not certain of what database/datastore you're using for Django and how the different database layers interact with App Engine's consistency, so this could be wrong, but if you can give your users the right key and then fetch them from that key directly (rather than getting all users and filtering them by key), you might get strong consistency.

How to display a post registration welcome message when using both django-registration and django-socialauth?

This is a pretty trivial question but I must be missing something because I can't come up with a solution I'm happy with.
I'm using two libraries to handle registration, django-registration for the email based registration and django-socialauth for the social based registration, and want to display a welcome message when the user registers for the first time.
My current approach is to have a context processor that checks if the user has registered within the past 2 minutes and if so, updates the request object. This seems inefficient since I'm checking every time when it's only used once.
I tried implementing it using signals but the issue I ran into was that I needed some way to hook into the request but only django-registration passes the request along.
An option I'm contemplating is using the signals to update a record in the database but that seems like overkill for something this simple. Am I missing something obvious?
context_processors.py:
def just_registered(request):
just_registered = False
if request.user.is_authenticated() and request.user.email:
if request.user.date_joined < datetime.today() + timedelta(minutes=2):
if 'just_registered' not in request.session:
just_registered = True
request.session['just_registered'] = just_registered
return { 'just_registered' : just_registered }
you can use django messages and implement it in your template
{% if messages %}
{% for message in messages %}
{{message}}
{% endfor %}
{% endif %}
.
def just_registered(request):
if request.user.is_authenticated():
if request.user.date_joined < datetime.today() + timedelta(minutes=2):
messages.info(request, "Welcome")
return ''
user is authenticated is already understood, you don't have to put user email because when you register, the email is required
Just to be clear, you want to display a welcome message when the user successfully logs in for the first time (it says register for the first time in your question)? Do they follow an activation link from an email? You could have that emailed link go to a new user version of your landing page.
Otherwise, if you want to use the same page for normal users and people logging in the for the first time, I don't see how you can avoid checking if this is the user's first time logging in. To do that, it seems like using a boolean attrib on the user (or fk'ed to them) that keeps track of whether they have logged in before would be the way to go, instead of looking at how long ago they activated the account (what if they activated 2 days ago but didn't log in?)
Following from your comment on princesses answer your best bet would be to save some kind of data when the user logs in for the first time.
I would suggest write a simple middleware which detects first login and saves that in a persistent form
Have a look at this:
http://blog.elcodo.pl/post/926902087/django-detect-users-first-login
You can also checkout the middleware in django tracking
https://github.com/codekoala/django-tracking/blob/master/tracking/middleware.py
It is slightly inefficient , however I don't see any other way given the statelessness of HTTP

Django redirect behavior with back button

I'm running into an issue now where I have a "random" link on my site to see a random user. The way I have it set up is to get the user_id and then use redirect to serve the proper page. The issue I'm running into is if I click the random button multiple times, clicking on back will bring me back to the page before the "random" clicks.
To be more concrete, this is what's happening:
HomePage, Click Random (go to /user1/), Click Random (go to /user4/), Hit back (end up on HomePage). In this scenario I'd like to end up on /user1/
This is the random view method:
def Random(request):
user = helpers.GetRandomUser()
return redirect('user_display', user_slug=user.username)
The template just has a link to /random/ which gets routed to the above view.
Edit: Apparently it works as expected in Firefox but in Chrome. I'd like it to have the Firefox-like behavior everywhere.
So if I understand you correctly you click two times on a link to the same url (like /random_user/) and you respond with a random redirect. This seems quite unconventional and it doesn't sound so wrong that Chrome might view this as a single history entry.
To archieve your wanted behaviour across browsers simply generate the random url before you render your random user link.
As you want to use it in multiple views, write a custom template tag:
#register.simple_tag
def random_user_url():
user_url = # generate your random user url
return user_url
In your template:
{% load your_tag_lib %}
Random user
This way every click leads the browser to a different url and will be memorized as seperate history entry.
Use the following code to force the browser not to cache the page. So, clicking back button sends request to server and now you can catch it and redirect him to the desired page.
from django.views.decorators.cache import cache_control
#cache_control(no_cache=True, must_revalidate=True)
def func()
#some code
return
To be clear, when you say "Back Button" do you mean:
Browser Back Button
Your own creation of a Back Button
If 2, are you doing this via client side? Such as via javascript?

Get the original path in django

I have a question: how to get the current path of the url. Let's say, I have 3 navigation bars, about , blog and contact page. In each page, I have facebook, twitter and a manual email a friend button. When I clicked the email a friend button, and the current URL is www.example.com/about, the current URL is now already www.example.com/emailafriend. How can I get the www.example/about? Also in blog and contact. Please help me. Thanks.
How does your email a friend button work? Is it a django view that takes the current URL and emails it? If so, you don't want the "current" URL, which, as you note, is actually the email a friend URL. What you want to do is pass the URL you want to share as a URL parameter, ie:
/share?url=http://www.example.com/blog
Adding more info based on comments:
When I was referencing URL above, I was not referring to your django URL configuration. Let's take a step back.
On your About page you have a link to email a friend, right? That link is probably generated in your template, but it's the same on every page. Something like:
Email a friend
Instead of this, try this:
Email a friend
Now you need to make your email_a_friend view handle this. It can get the url via
request.get('url', '').
Some additional information:
You might want to escape the {{ request.get_full_path }} function so that it's escaped and URL safe, then you'll have to unescape it in your view. Once you get the URL back to your view, you can do as you please with it.
{{ request.get_full_path|urlencode }}
Try using Relative URLs like for example From www.example.com/about to get to www.example.com/email use /email. Using relative urls is the simplest solution .
Take a look at this.
Absolute vs relative URLs
It sounds like your want to get the referring URL (the URL that sent you to the current page). That is available to you in the request object, although it is not 100% reliable:
request.META['HTTP_REFERER']
See the documentation on HttpRequest objects for more information.

Django: How do I position a page when using Django templates

I have a web page where the user enters some data and then clicks a submit button. I process the data and then use the same Django template to display the original data, the submit button, and the results. When I am using the Django template to display results, I would like the page to be automatically scrolled down to the part of the page where the results begin. This allows the user to scroll back up the page if she wants to change her original data and click submit again. Hopefully, there's some simple way of doing this that I can't see at the moment.
It should already work if you provide a fragment identifier in the action method of the form:
<form method="post" action="/your/url#results">
<!-- ... -->
</form>
and somewhere below the form, where you want to show the results:
<div id="results">
<!-- your results here -->
</div>
This should make the page jump to the <div> with ID results.
It is complete client site and does not involve Django, JavaScript or similar.
You need to wrap your data into something like this:
<div id="some-id">YOUR DATA TO BE DISPLAYED</div>
and if you make redirect in your view you need to redirect to url: /some-url/#some-id
if you don't make redirect you need to scroll to the bottom using javascript (but note that redirect is preffered way to use in view after saving data).