StripeToken displaying? - python

Hello I am trying to setup stripe payment for an e_commerc django application, and I have a problem whit displaying stripeToken, when I try to pay whit the stripe test credit card.
This is my views.py, where am I defining mine stripe payment:
from django.conf import settings
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
import stripe
# Create your views here.
#login_required
def checkout(request):
if request.method == 'POST':
print request.POST
user = request.user
context = {}
tempalte = 'checkout.html'
return render(request, tempalte, context)
When I use test credit card it will display only this
<QueryDict: {u'csrfmiddlewaretoken': [u'NP0q3qvVZs2C0dB2yEiSzmMuNMBS9jvD']}>, whitout stripeToken.
Can you tell me what am I mistaking here?
Thank you.

Related

Django. ImportError: attempted relative import beyond top-level package

I'm a newbie. And I just started writing a django project. It is called the iRayProject and consists of two applications iRay_user_authentication and iRay_working_with_notes:
project structure here
iRay_user_authentication - this is a standard django app for registration
Here is his urls.py
from django.urls import path
from .views import login_user, registration
urlpatterns = [
path('', login_user, name='login_user'),
path('registration', registration, name='registration'),
]
In views.py registered user using redirect I want to send to the second application of the project
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.contrib.auth import login, logout, authenticate
from ..iRay_working_with_notes.views import list_notes
def login_user(request):
if request.method == 'GET':
return render(request, 'iRay_user_authentication/login.html', {'form': AuthenticationForm})
def registration(request):
if request.method == 'GET':
return render(request, 'iRay_user_authentication/registration.html', {'form': UserCreationForm})
else:
if '_guest' in request.POST:
pass
else:
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.create_user(request.POST['username'], password=request.POST['password1'])
user.save()
login(request, user)
return redirect(list_notes)
except IntegrityError:
return render(request, 'iRay_user_authentication/registration.html', {'form': UserCreationForm,
'error': 'name is busy '
})
else:
return render(request, 'todo_app/registration.html', {'form': UserCreationForm,
'error': 'passwords not math'})
But when trying to import a function from the second views.py
from django.shortcuts import render
def list_notes(request):
return render(request, 'iRay_working_with_notes/list_notes.html')
I get an error:
ImportError: attempted relative import beyond top-level package
And I found a lot of theoretical information about why this error occurs.
But I still couldn 't figure out if there is an easy way for relative or absolute import , or I just didn 't structure my project correctly ??
import is wrong
from ..iRay_working_with_notes.views import list_notes
should be
from iRay_working_with_notes.views import list_notes
redirect needs view name from the urls-pattern:
redirect('name-of-my-view-pattern')
So please create a url-pattern entry for the list_notes view and give the pattern name as parameter to the redirect.
Why? because a redirect is telling the browser on the client side to load the target redirect page, so it needs an url (that is generated by django via the url-pattern), as the target page will be called from the browser.
Technically of course you can import a view and call it from another module directly as it is just a python function - but that is not a http redirect (and would not change the url in the browser to the redirected page) and additionally that is not really the idea of the django request/response architecture.

How to customize the django-ratelimit 403 forbidden page?

I'm using django-ratelimit 2.0 for rate limiting my views. I want to show a different (custom) 403 forbidden page for different views. For example if it is a sign up view, it should give a message try again in 1 minute. If it is a forgot password view then message should be try again after 12 hours. Basically I want different rate limit message for different views.
this will help you
https://django-ratelimit.readthedocs.io/en/stable/usage.html#ratelimit.exceptions.Ratelimited
settings.py
DEBUG = False
ALLOWED_HOSTS = ['*']
views.py
from django.shortcuts import render
from django.http import HttpResponse
from ratelimit.decorators import ratelimit # 进行请求限制
from ratelimit.exceptions import Ratelimited # 进行请求限制,判断403
# Create your views here.
#ratelimit(key='ip', rate='2/m',block=True)
def Hello(request):
return render(request, 'hello.html')
def handler403(request, exception=None):
if isinstance(exception, Ratelimited):
return HttpResponse('Sorry you are blocked', status=429)
return HttpResponse('Forbidden')
urls.py
handler403 = views.handler403

undefined name in function 'redirect'

any advice on whats the problem? Im learning from a Django v1 tutorial, ive had a look at the documentation but cannot figure it out.
imports:
from django.shortcuts import render
from accounts.forms import RegistrationForm
from django.contrib.auth.forms import UserChangeForm
function:
def edit_profile(request):
if request.method == 'POST':
form = UserChangeForm(request.POST instance=request.user)
if form.is_valid():
form.save()
return redirect('/account/profile')
else:
form = UserChangeForm(instance=request.user)
args = {'form': form}
return render(request, 'accounts/edit_profile.html', args)
thanks
You need to import redirect from django.shortcut with
from django.shortcuts import redirect
This is well documented in the Django's shortcut documentation.

Django 1.9.4 Get input data from form to show into a different template

Here is my code that I believe pertains to this situation. I'm sorry, I'm new to django.
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import SearchForm
def result_one(request):
return render(request, "testresult.html", {})
def get_results(request):
if request.method == 'POST':
form = SearchForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/result/')
else:
form = SearchForm()
return render(request, 'index.html', {'form': form})
urls.py
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^search/$', "search.views.get_results"),
url(r'^result/$', "search.views.result_one"),
]
forms.py
from django import forms
class SearchForm(forms.Form):
client_group_number=forms.IntegerField(label='Group Number', widget=forms.TextInput(attrs={'placeholder': 'Group Number'}))
From my understanding, what I believe should happen is that an input will be put into a html page. When the user hits submit, the input gets saved into forms.py as data. This data gets manipulated in views.py which gets displayed in a different html page. (I hope this is correct)
What I want it to do is take in an input for client_group_number(in forms.py) from index.html(for example: 123), that can be accessed in views.py and displayed in another html template that I have called testresult.html, which would display Group Number = 123 (the 123 coming from either the forms.py or views.py).
This might be a very simple thing to accomplish and I apologize if it is, but I can't seem to find what I need on the internet.
Django validate the form input data in the cleaned_data dictionary. You would need to pass this to the new template either as arguments in the redirect or using session. Here is one simple example to give you an idea, there are probably better ways.
if form.is_valid():
group_number = form.cleaned_data["client_group_number"]
HttpResponseRedirect("/result/?group_number=" + group_number)

reverse() is not working

I am trying to pass the id through reverse. But it's not working. I'm getting this error
Reverse for 'reg.views.thanks' with arguments '(20,)' and keyword arguments '{}' not found.
Here is my views.py:
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
from reg.models import registration, registrationform
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
def registration(request):
if request.method == 'POST':
form = registrationform(request.POST)
if form.is_valid():
data = form.save()
id = data.id
return thanks(request,id)
else:
form = registrationform()
return render_to_response('registration.html', {'form' : form}, context_instance=RequestContext(request))
def thanks(request, id):
p = get_object_or_404(registration, pk=id)
return render_to_response('thanks.html', {'reg' : p})
Here is my urls.py:
from django.conf.urls import patterns, include, url
url(r'^registration/$', 'reg.views.registration'),
url(r'^thanks/$', 'reg.views.thanks'),
url(r'^$','django.views.generic.simple.direct_to_template', {'template' : 'index.html'}),
)
Here is thanks.html:
<html>
<body>
<p>Thank you for registration mr.{{reg.username}}</p>
</body>
</html>
and I'm also showing my models.py:
from django.db import models
from django.forms import ModelForm
class registration(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class registrationform(ModelForm):
class Meta:
model = registration
Thanks.
from this links (django tutorial):
https://docs.djangoproject.com/en/dev/topics/http/urls/#django.core.urlresolvers.reverse
example:
def myview(request):
return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
so your code goes to:
in urls.py:
url(r'^thanks/(?P<id>\d+)$', 'reg.views.thanks', name='my_thanks_url')
in your function:
return HttpResponseRedirect(reverse('my_thanks_url', args=[id]))
This line
return HttpResponseRedirect(reverse('reg.views.thanks', args=(id,)))
Is trying to construct a url to your view reg.views.thanks, with the id variable used as a parameter.
This line in urls.py
url(r'^thanks/$', 'reg.views.thanks'),
Does not have anywhere for that parameter to go.
The first thing that you need to figure out is whether you actually want to send an HTTP redirect to the browser to tell it to go to the 'thanks' page. If you really do, then you need a way to send that id in the URL. You can do it as part of the URL path itself, as #moguzalp suggests, or you can put it in the query string, like
/thanks/?id=12345
Or you can do other things, like stashing the id in the user's session, and pulling it out when they request the thanks page. That's a bit more complicated, though.
If you don't actually need to issue an HTTP redirect, then there's nothing stopping you from just calling the thanks() function from inside your view function, like this:
def registration(request):
if request.method == 'POST':
form = registrationform(request.POST)
if form.is_valid():
data = form.save()
id = data.id
return thanks(request, id)
else:
form = registrationform()
return render_to_response('registration.html', {'form' : form}, context_instance=RequestContext(request))
The URL won't change in the browser, but the correct ID will be used, and doesn't need to appear anywhere else, in the URL, the query parameters, or the session

Categories