Receiving 404 Error in Heroku with Django-Tenants with Wildcard CNAME - django

I have a really weird situation I cannot seem to figure out. I have not touched my implementation of this package since the beginning of the year and now the functionality ceases to exist on my live heroku server. I currently have a Create Account form on my public tenant which generates a tenant/domain just as the docs do and django-tenants does its auto schema generation. This works correctly on my localhost and have zero problems. However on my live server, I proceed to get a 404 error... Not Found...The requested URL / was not found on this server.
​
I have a CNAME record on DNSimple which points to a wildcard domain that appears to be working, because I have already have a tenant I made awhile ago that is still completely functional (ie. some-customer.mydomain.com). I have looked into my PSQL db attached to heroku and everything is there as it should be, as well as the migrations occurring in the logs when I create an account which generates a tenant.
​
I was hoping that there might be some enlightenment as to what I am doing/have done wrong to make this issue occur. It just seems so odd that none of my now generated tenants can be accessed via their Domain.
Edit: Posting Code.
local .env file
SECRET_KEY=...
DEBUG=True
DB_NAME=...
DB_USER=...
DB_PASSWORD=...
DB_HOST=localhost
ALLOWED_HOSTS=.localhost, .herokuapp.com
GOOGLE_RECAPTCHA_SECRET_KEY=...
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
AWS_STORAGE_BUCKET_NAME=...
SECURE_SSL_REDIRECT='False'
settings.py (included things I think are relative)
...
LOGIN_URL = 'login'
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=[], cast=Csv())
DEBUG = config('DEBUG', default=False, cast=bool)
SECRET_KEY = config('SECRET_KEY')
SHARED_APPS = (
'django_tenants',
'tenant',
'django.contrib.contenttypes',
'public.apps.PublicConfig',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.sessions',
'debug_toolbar',
'storages'
)
TENANT_APPS = (
'django.contrib.contenttypes',
'inventory.apps.InventoryConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.messages',
)
INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS]
TENANT_MODEL = 'tenant.Client'
TENANT_DOMAIN_MODEL = 'tenant.Domain'
MIDDLEWARE = [
'django_tenants.middleware.main.TenantMainMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'myapp.urls'
WSGI_APPLICATION = 'myapp.wsgi.application'
DATABASE_ROUTERS = (
'django_tenants.routers.TenantSyncRouter',
)
PUBLIC_SCHEMA_URLCONF = 'myapp.urls_public'
SECURE_SSL_REDIRECT = config('SECURE_SSL_REDIRECT', default=False, cast=bool)
...
production Heroku settings (included relative stuff)
...
ALLOWED_HOSTS: .herokuapp.com, .mydomain.com, mydomain.com
DEBUG: False
SECURE_SSL_REDIRECT: True
...
urls.py (each tenant should see these)
urlpatterns = [
...
url(r'^$', dashboard, name='dashboard'),
url(r'^login/$', login_view, name='login'),
url(r'^logout/$', logout_view, name='logout'),
...
]
urls_public.py (main site)
urlpatterns = [
url(r'^$', home_view, name='home'),
url(r'^login/$', login_view, name='login'),
url(r'^logout/$', logout_view, name='logout'),
url(r'^create_account/$', create_account_view, name='create_account'),
]

Everything seems to look fine. If you try generating a tenant using the django-tenant docs in the shell on your production server by doing heroku run python manage.py shell -a yourapp and that works, then there is something wrong with your code that generates the tenants which you have not posted.

Related

Stripe checkout unable to access my django apps success page on heroku

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

django-allauth-2fa: Unexpected behaviour of accounts/two_factor/setup/ -> page reload after pressing 'verify'

I am trying to use django-allauth & django-allauth-2fa in my Django app.
My django-allauth app is set uo correctly - everything is working as expected.
However, when trying to set up django-allauth-2fa I ran into some issues: Configuring a two-factor authentification at accounts/two_factor/setup/ when I scan the QR code, input the token generated and press verify the page simply reloads with a new QR code instead of leading me to the next step in the Two-Factor configuration workflow. I can't figure out what my mistake may be, as I set up everything as written in the django-allauth-2fa documentation
My Pipfile:
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
[packages]
django = "==3.0.0"
pylint = "==2.4.4"
django-crispy-forms = "==1.9"
django-allauth = "==0.42.0"
django-allauth-2fa = "==0.8"
[requires]
python_version = "3.7"
my settings.py file:
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
# Local
'users.apps.UsersConfig',
'pages.apps.PagesConfig',
#Third-party
'allauth',
'allauth.account',
'django_otp',
'django_otp.plugins.otp_totp',
'django_otp.plugins.otp_static',
'allauth_2fa',
'crispy_forms',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django_otp.middleware.OTPMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'allauth_2fa.middleware.AllauthTwoFactorMiddleware',
]
SITE_ID = 1
ACCOUNT_ADAPTER = 'allauth_2fa.adapter.OTPAdapter'
...
my urls.py file:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('allauth_2fa.urls')),
path('accounts/', include('allauth.urls')),
path('', include('pages.urls')),
]
And I also ran python manage.py migrate
had the same problem on Ubuntu20 . Fix it with enbaling automatic sync date & times.

Django Downloading a media file using XHR gives CORS error

I have a project where the admin upload FBX files,
These FBX files are fetched through an XHR call and loaded to Threejs.
Django Set-up.
Requirement.txt
asgiref==3.2.3
Django==3.0.2
django-cors-headers==3.2.1
django-filter==2.2.0
djangorestframework==3.11.0
Markdown==3.1.1
pytz==2019.3
sqlparse==0.3.0
URLS
urlpatterns = [
path('admin/', admin.site.urls),
path('fbx/', include('fbx.urls')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Settings.py
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
Upload model
from django.db import models
class Fbx(models.Model):
name = models.CharField(max_length=200)
fbx = models.FileField(max_length=200, blank=True)
normals = models.FileField(max_length=200, blank=True)
bump = models.FileField(max_length=200, blank=True)
texture = models.FileField(max_length=200, blank=True)
status = models.BooleanField(default=False)
pub_date = models.DateTimeField(auto_now=True)
IMPORTS and MIDDLEWARES
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'rest_framework',
'fbx.apps.FbxConfig'
]
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',
'corsheaders.middleware.CorsMiddleware',
]
I have no issues with upload, everything works fine.
I'm using Threejs FBXloader to download the FBX. This is an XHR call.
This call fails. But if I put the same link on the browser it works fine.
The XHR call to this file http://XXXX/media/correction_1.fbx fails.
But works when you put it in browser.
What could be the issue here?
Django does not serve the media files through the middleware stack, so any attempts to inject headers are pointless. You need to enable the CORS in the apache.
This change in the virutal host did it for me.
Alias /media/ /**<path to media>**/media/
<Directory /**<path to media>**/media>
Header set Access-Control-Allow-Origin "*"
Order allow,deny
Allow from all
</Directory>
If you can not access the virutal host it is possible to do the change in the .htaccess
https://enable-cors.org/server_apache.html

Django request.user is anonymous in views without login_required decorator

I am working on a Django (v2.0) app with django-allauth as auth backend. I'll explain my problem in steps:
User logs in -> user redirected to home page (can't access home page without login)
In the home page (after logging in), several calls are made for a particular view in the server.
Ex: https://mywebsite.com/api/getstuff/123
Problem: getstuff returns/prints data that is intended for a user who is NOT logged in.
getstuff is defined in urls.py as:
url(r'^api/getstuff/(?P<hash_code>[a-zA-Z0-9]{3})$', views.getstuff, name='getstuff')
in views.py: (views.getstuff)
#csrf_protect
#ensure_csrf_cookie
def getstuff(request,hash_code):
if request.user.is_authenticated:
#do stuff....
print('user is authenticated!')
return HttpResponse(hash_code+'foo-auth')
else:
#do other stuff..
print('user is NOT authenticated')
return HttpResponse(hash_code+'foo-un_auth')
I only see user is NOT authenticated being printed in my case. Shouldn't the output be user is authenticated since the user is already logged in? the request.user object is an AnonymousUser object. All the requests I make are from https.
few configurations from settings.py:
CSRF_USE_SESSIONS = True
CSRF_COOKIE_SECURE = True #tried removing this, still same result as above
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django_extensions',
'django.contrib.sitemaps',
'mysite.core',
'bootstrapform',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
'allauth.socialaccount.providers.github',
'allauth.socialaccount.providers.twitter',
'embed',
'channels',
'djcelery'
]
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',
]
AUTHENTICATION_BACKENDS = (
"allauth.account.auth_backends.AuthenticationBackend",
)
I tried clearing cache before accessing the website and logging in - still same result.
Am I missing something? What could be the problem?
Your use of if request.user.is_authenticated: is fine. Change the image src tag to use the domain that you logged into.
<img src="/api/getstuff/123">

Page not found (404) - Django

I have a strange behavior when I try to test my Django on the webpage.
I see what is the error, but I have no clue from where it comes.
What I try to do is :
I have project called stockmarket
I have application called stockanalysis
the problem is :
when I try to open 'domain/stockmarket I get this:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8888//
When I try to open 'domain/stockmarket/stockanalysis'
I get this:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8888//stockanalysis/
The issue is clear to me. In both cases I have two slashes (//) instead of one (/).
The issue is - I do not know from where it comes.
Any ideas?
here some files:
urls.py (project folder)
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^stockanalysis/', include('stockanalysis.urls')),
url(r'^admin/', admin.site.urls),
]
urls.py (app. folder)
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
views.py (app folder)
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the index.")
setting.py (project folder)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = '****************************************'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'stockanalysis.apps.StockanalysisConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'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 = 'stockmarket.urls'
WSGI_APPLICATION = 'stockmarket.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
Issue is solved.
As I expected nothing wrong was with the files itself (like urls.py or settings.py).
The company which hosts the files did a mistake in vhosts entries in Apache. That's what they told me.
After I created my first Django project I was asked to provide some details, so they could do some adjustments on server side. While doing this they did mistake.