I am a relatively inexperienced python/django programmer and have run into a issue that i am unable to resolve on my own, inspite of searching around for help. English is not my first language so please do not mind language related errors in my attempt to explain my problem.
My django 3.2 App uses stripe checkout for payment. While in development on my local machine, i could process payment and return to my apps success page, but after i deployed it to heroku, it processes the payment but wont return to my apps success page. I have installed the corsheaders package and have tried all the possible settings suggested here on stackoverflow and elsewhere. I am stating my settings below and also the stripe checkout views code. Any help will be highly appreciated.
all the relevant settings are as under
BASE_DIR = Path(__file__).resolve().parent.parent
ALLOWED_HOSTS = ['*']
CORS_ORIGIN_ALLOW_ALL = True
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd party
'rest_framework',
'corsheaders',
'crispy_forms',
'sorl.thumbnail',
'cloudinary',
'storages',
# local
'accounts.apps.AccountsConfig',
'main.apps.MainConfig',
'api.apps.ApiConfig',
'cart.apps.CartConfig',
'payment.apps.PaymentConfig',
'order.apps.OrderConfig',
'setmenu.apps.SetmenuConfig',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [str(BASE_DIR.joinpath('templates'))],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
core.urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('accounts.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('api/v1/', include('api.urls')),
path('cart/', include('cart.urls', namespace='carturls')),
path('setmenu/', include('setmenu.urls', namespace='setmenu')),
path('orders/', include('order.urls', namespace='orders')),
path('payment/', include('payment.urls', namespace='payment')),
path('', include('main.urls', namespace='main')),
]
payment urls.py
app_name = 'payment'
urlpatterns = [
path('process/', login_required(views.payment_process), name='process'),
path('done/', views.payment_done, name='done'),
path('canceled/', views.payment_canceled, name='canceled'),
path('webhook/', views.webhook, name='webhook')
]
Payment apps view that processes payment
def payment_process(request):
order_id = request.session.get('order_id')
order = get_object_or_404(Order, id=order_id)
total_cost = int(order.get_total_amount() * 100)
session = stripe.checkout.Session.create(
line_items=[{
'price_data': {
'currency': 'inr',
'product_data': {
'name': f'Order number {order_id}',
},
'unit_amount': f'{total_cost}',
},
'quantity': 1,
}],
mode='payment',
success_url='https://myappname.herokuapp.com/payment/done',
cancel_url='https://myappname.herokuapp.com/payment/canceled',
)
return redirect(session.url, code=303)
even if i put a done/ it doesnt redirect. The below success urls work though and i am redirect to my home page and the admin page respectively.
success_url='https://myappname.herokuapp.com'
and
success_url='https://myappname.herokuapp.com/admin'
But ofcourse, ideally it has to return to the specific success page. The fact that it successfully redirects to https://myappname.herokuapp.com/admin, bothers me even more as to why it wont go to https://myappname.herokuapp.com/payment/done
I have tried to discard the payment urls and dump the payment routes in the core urls thinking that its not accessing custom namespaced urls, but that too did not work.
Please do point me to the right direction. I am inclined to think that my Cors settings are not right but then i have allowed all hosts and cors_origin_allow_all is true.The corsheaders middleware is also at the top as suggested but yet its not redirecting from stripe. So i feel like i have hit a wall.
Thanks a lot for your help
Related
Well I am trying to add login and sign up with facebook functionality and when i click on login with facebook it takes me to facebook but shows an error such as
Facebook has detected Believer isn't using a secure connection to transfer information.
Until Believer updates its security settings, you won't be able to use Facebook to log into it.
I used comments for those lines which i add for social app. This code is from my project/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap3',
'accounts',
'social_django', # <--adding social app
]
AUTHENTICATION_BACKENDS = (
'social_core.backends.facebook.FacebookOAuth2',
'social_core.backends.twitter.TwitterOAuth',
'social_core.backends.github.GithubOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware', #<--for social app
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'social_django.context_processors.backends', # <-- Here
'social_django.context_processors.login_redirect', # <-- Here
],
},
},
]
LOGIN_REDIRECT_URL = 'test'
LOGOUT_REDIRECT_URL = 'thanks'
SOCIAL_AUTH_FACEBOOK_KEY = '1289678764728890' # App ID
SOCIAL_AUTH_FACEBOOK_SECRET = '1c2a66c9c8116e4e2d97cb059db5d6a9' # App Secret
I'm setting production environment on EC2. The exactly same code is running on Dev and Prod, but gunicorn (prod) and different settings.py.
It's all working fine, but when a visitor tries to reset password he access the page "password_reset", fill the form with his email but, after submitting, get a 500 error.
When this occour, i'm emailed (admin emails) with this error saying:
"Internal Server Error: /accounts/password_reset/
NoReverseMatch at /accounts/password_reset/
Reverse for 'auth_password_reset_confirm' not found. 'auth_password_reset_confirm' is not a valid view function or pattern name."
What i understand is that "/accounts/password_reset/" is trying to call an "auth_password_reset_confirm" that indeed does not exist (the correct url name is "password_reset_confirm"). But i don't know who is adding this "auth_" before.
I've tried:
1) Confirm on dev and prod that the url name given from django.contrig.auth is "password_reset_confirm"
2) Downloaded server version of django.contrib.auth and confirm no "auth_" is being added to the call.
3) Confirm that i didn't add "auth_" on any url name on my apps.
common_settings.py:
INSTALLED_APPS = [
#My Apps
'institutional', #External generic public pages
'lab', #Internal pages and controllers
'shop', #External shop pages and controllers
'account', #Group of dynamics to handle users, members (profile)
'django.contrib.auth', #Here just because of django_registration password reset issues if this line was after
#Third-party Apps
'django_registration',
'snowpenguin.django.recaptcha3',
'pagseguro',
'polymorphic',
'django_countries',
'compressor',
#Django Default Apps
'django.contrib.sitemaps',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'myapp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'myapp.wsgi.application'
# Password validation
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Django auth configuration
LOGIN_URL = '/accounts/login/'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
myapp.urls.py:
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.contrib.staticfiles.urls import static, staticfiles_urlpatterns
urlpatterns = [
#Default admin app urls
path('admin/', admin.site.urls),
#Account pages
path('accounts/', include('account.urls')),
#Pattern to allow lazy translations
path('i18n/', include('django.conf.urls.i18n')),
]
#Media and images configuration
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
accounts.urls.py:
from django.urls import path, include
from . import views, forms, regbackend
from django_registration.backends.activation.views import RegistrationView
urlpatterns = [
#Account necessary views
path('register/', RegistrationView.as_view(form_class=forms.ExtendedRegistrationForm), name='django_registration_register'),
path('member/', views.member_read, name='accounts.member_read'),
path('member/update', views.member_update, name='accounts.member_update'),
#Account pages from Django Auth and django_registration
path('login/', views.ExtendedLoginView.as_view(), name='login'),
path('', include('django.contrib.auth.urls')),
path('', include('django_registration.backends.activation.urls')),
]
I realy dont understand what is going on, can anyone help me?
I did a turn around here adding this url to my accounts.url.py:
from django.contrib.auth.views import PasswordResetConfirmView
...
path('reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='auth_password_reset_confirm'),
And it's working. But i really need to understand who's calling this page.
Thanks
I need to get some information from LinkedIn profile of a user to fill existing fields of my application form. So I am using LinkedIn API(I have created app in linkedin and stand with client_Key, client_Secret,r_liteprofile and r_emailaddress permissions). Now it is prompting me to sign-in with linkedIn and asking for "Allow" permission(All OK till this prompt) but In the next page I'm getting below error instead of showing json file with user information.
"""
HTTPError at /complete/linkedin-oauth2/
410 Client Error: Gone for url: https://api.linkedin.com/v1/people/~:(first-name,id,last-name)?oauth2_access_token=AQVpVZCnhj2oLkzUvQytDU89kJUMm5yEIadV0BZMid3WVqPSVdOiJIePGIH7ZL7i3M5gppOlbUqpS68rDaaio56Y-nkC3Njpvf91v8WUPxQ8t-3uqJRzCC_MdrKUpntLalp24Eo2BMjpYIKeHGdxjFIlaMt9tszkIVHpPcZA2-dgbqOBrvt9-QE4P91bTXqBBkrtHEXg9F560OvltnQDgc0U1xwO-5yOT5LjlqAtvDJ_gMf3G8rZ9cdkayq4aP1CO-ljglGqlJb4uxorPRg7qPqqkNaAmQjXploM0KVQ6pK7nidP4zC2l7WW1aqg38GRDe8AM8jzaiIkg-SX3JfCJA28fT9H8A&format=json
"""
Below is my code, Did I miss anything....I'm newbie to Django Please help me to fix it??
I have tried to get exact access token format like{access token:XXXXX,expires in:XXX} with url https://www.linkedin.com/oauth/v2/accessToken?grant_type=client_credentials&client_id=[my_client_ID]&client_secret=[my_client_secret] I got below response.
{"error":"access_denied","error_description":"This application is not allowed to create application tokens"}
How can I achieve it??
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'bootstrap4',
'social_django',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect',
],
},
},
]
AUTHENTICATION_BACKENDS = (
'social.backends.linkedin.LinkedinOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = 'my_client_ID'
SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = 'my_client_secret'
SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_liteprofile']
SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = ['r_emailaddress']
SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA = [('id', 'id'),
('firstName', 'first_name'),
('lastName', 'last_name'),
('emailAddress', 'email_address')]
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/home/'
SOCIAL_AUTH_LOGIN_URL = '/'
```[the error I'm getting][1]
[1]: https://i.stack.imgur.com/ECS3N.png
So i'm trying to build a basic blog in Django (am currently using the latest version of Django) and i'm running into a really annoying problem. When I try and set up my html templates, I keep on getting a templatedoesnotexisterror.
Here's the rub--if I set up my html templates in the root app of the project ("blogcode"), they run perfectly. But then, once I start running another app ("articles") and then I set up a templates folder using articles/templates/articles/homepage.html, all of the sudden, it doesn't work. I can't get django to look anywhere but in the root app directory to find and ultimately render templates.
In my settings.py file, i've the DIRS list set to 'templates'. When I tried changing it to os.path.join(BASE_DIR, 'templates') I get the same "templatedoesnot exist" error. Also, my app IS properly installed in the INSTALLED_APPS list in settings.
I've tried looking in other documentation, but the only hints I can find are really outdated. On the views.py, if I chop off the articles/, and just leave it as 'homepage.html' django renders it from the root app just fine and ignores the template in the articles app, but if I try and get it to render from the articles app, I get the "templatedoesnotexist" error. What's going on?
Here's my code:
articles/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.startpage, name='startpage'),
]
articles/views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Article
def startpage(request):
return render(request, 'articles/homepage.html')
blogcode/settings.py
INSTALLED_APPS = [
'articles.apps.ArticlesConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'horror_blog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'horror_blog.wsgi.application'
Try register the app that way, and put django apps above your owns
Instead of
'articles.apps.ArticlesConfig',
Try this:
INSTALLED_APPS = [
''' django apps'''
'articles'
]
this 'DIRS': ['templates'] should be 'DIRS': [os.path.join(BASE_DIR, 'templates'),],
Making a project login with facebook. But it's showing error
my localhost url -- 127.0.0.1:8000/demo/index/
My code is like this
setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'social_django',
'dashboard'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.join(BASE_DIR), 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'social_django.context_processors.backends', # <--
'social_django.context_processors.login_redirect',
],
},
},
]
AUTHENTICATION_BACKENDS = (
'social_core.backends.facebook.FacebookOAuth2',
'social_core.backends.google.GoogleOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
STATIC_URL = '/static/'
LOGIN_URL = '/demo/login/'
LOGIN_REDIRECT_URL = '/'
SOCIAL_AUTH_FACEBOOK_KEY = '184354188769721'
SOCIAL_AUTH_FACEBOOK_SECRET = 'c4d9ed712a59be2f9bb25b5368432f61'
LOGIN_URL = '/demo/login/'
LOGIN_REDIRECT_URL = '/'
url.py
url(r'^facebook/', include('social_django.urls', namespace='social')),
index.html
Login with Facebook
I created facebook API and set
domain - empty
site url - empty
in facebook login(plugins)
Valid OAuth redirect URIs - http://localhost:8000/_auth/facebook
Give solution wy its showing this error while login.
URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.
You have to set APP DOMAINS in Facebook APP settings
Go to your App's settings page in http://developers.facebook.com
Click on the dropdown arrow on the top left (next to the name of your app) and click "Create Test App" and give it a name
In the Settings > Basic of that new Test App set the App Domains as "localhost"
check this link for more info -
Facebook App: localhost no longer works as app domain
For Oauth URL Forward - try putting only domain name
I got the answer...
I have changed the domain name(27.0.0.1:8000 www.example.com) first using this command..
sudo -i gedit /etc/hosts
and then edited in setting.py
ALLOWED_HOSTS = ["www.example.com"]
Go to your App's settings page in http://developers.facebook.com
add site url http://www.example.com:8000/
and domain name example.com