Django app do not render html templates (no requirements.txt) - python

I am working with this app, I have tried running the app using the command provided in the doc then I had to install both Django and requests but now the template view do not render at all, it seems it's interpreted as text
What do I have to install? Or this app is not working properly? I am not sure why there's no requirements.txt
Below is the settings file
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'xxxxxxx'
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'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.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Company.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',
],
},
},
]
There's also a file named urls.py that contains the path I am supposed to work with
urlpatterns = [
url(r'^payment_request/',Payment_Request),
url(r'^payment_response/',Payment_Response),
url(r'^payment_receipt/',Payment_Receipt),
url(r'^admin/', admin.site.urls),
]
Only admin is working, Payment_Receipt and Payment_Response shows error but that's normal because they should get some data to process before
I also I'd like to mention that in the docs they ask to generate some hash sequence, is that mandatory to simply shows the htm template? I have never done this before
Create SHA256 Hash with below mention Parameters.
Merchant needs to form the below hash sequence before posting the transaction.
Below is the SHA 256 Hash creation format : Hash Sequence :-
trackid|Terminalid|password|secret_key|amount|currency_code

There are two ways this could happen:
Content type is wrong - Open up the Chrome Developer Console, Go to Network tab, reload the page and look at the content-type header in the request. Is it text/html? If it's something else, Chrome won't render it
The HTML is escaped - Right click on the page and click View Source. Is it different from the HTML you see in the page?

You have to add the name of the app in settings.py in the list INSTALLED_APPS
INSTALLED_APPS = [
"appname",
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

Related

Django still working fine even when DEBUG=False in settings.py

In settings.py, DEBUG set to True. But when we move it to the production we should be setting DEBUG=False.
So in my local environment itself, I have changed to DEBUG=False. But still my application is working fine even with this settings. Usually when we changed DEBUG to false we should be getting some issues like 500 or 404 error something like that , but in my case its not like that.
I have referred this """ https://stackoverflow.com/questions/38617046/django-debug-false-still-runs-in-debug-mode/47266619""" but it did not help much for me.
Please let me know if i misunderstood or missed something.
Below is the small snippet of code i have in settings.py
import os
BASE_DIR =
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
DEBUG = False
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'MyApp',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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',
],
},
},
]
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',
]
Please let me know if i need to provide anymore details.
The purpose of DEBUG is to control what happens when the application encounters an error.
If that happens and DEBUG is true, then the error page will contain debugging information that is useful to developers.
But you would not want this information to be shown to real users, so DEBUG should be false when deployed to production.
Setting DEBUG to false does not cause errors, as you seem to think.

Application labels aren't unique, duplicates: staticfiles

I'm having trouble figuring out what I'm duplicating here. I'm trying to migrate my files so I can deploy on Heroku. It says that "staticfiles" is duplicated, but I can't see where the conflict is. Does migration need to be done in order to deploy? or is there something wrong with my database?
import dj_database_url
import os
ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com']
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
'wiki_app',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.postgres',
]
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'coding_dojo_final_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'coding_dojo_final_project.wsgi.application'
...
WHITENOISE_USE_FINDERS = True
...
STATIC_URL = '/static/'
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
You need to set a static root which is where Django compiles the static files for serving in production when you run python manage.py collectstatic. The name must be different than the location of your static files in your project.
STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles'))
See the docs for more info.

django all-auth authenticating via twitch

I am trying to authenticate a user from twitch Auth using Django and reactjs. I am able to authorize the user and store its details in the Django admin from backend but not sure how to do it from reactjs.
What I tried so far:
Following the documents from here: https://django-allauth.readthedocs.io/en/latest/installation.html
I configured everything as:
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.twitch',
'django_extensions',
'users.apps.UsersConfig',
]
SITE_ID = 1
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 = app-name.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'sphinx.wsgi.application'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
I also registered the social application in the Django admin.
When I hit:
http://localhost:8000/accounts/twitch/login/
It takes me to the twitch authorization page, Which when I click on "Authorize" saves the user details in the Django admin redirects me back to the url:
http://localhost:8000/accounts/profile/
The problem is I need to make sure the LOGIN_REDIRECT_URL page '/accounts/profile/' has some authentication so only the logged in user can access it and to display the username of that user.
How do I authenticate the user? Like how do I send the access_token to the front-end reactjs and verify the user?
If you're using a custom auth schema, you can use the #login_required decorator before the view.

Can django webapp and django-rest-framework live together?

I have a Django WebApp to administrate certain things of my business. It's currently using Django 1.5.5, but I just migrated the code to Django 1.11.
The thing is that we are developing another apps using other technologies, and due to all my information is in the Django app, I decided to add Django Rest Framework to my existing Django Webapp. All ok so far, beautiful, API with Token access... happy...
But, then I realized that on PROD env, I've ALLOWED_HOST setting. :(. I added that line in my devbox, and the happiness end.
I tried adding CORS support using django-cors-headers, but, so far, I've not successful.
So, to avoid wasting time, I want to ask to people that knows more than me about it, if the Django App and the DRF API can live together, without removing the ALLOWED_HOST setting or setting it as ALLOWED_HOSTS = ['*'].
Thanks in advance!
UPDATE
My settings.py file looks like this:
# Django settings for dojosite project.
# -*- coding: utf-8 -*-
import os
import datetime
DEBUG = True
ALLOWED_HOSTS = ['www.myapp.com']
...
MIDDLEWARE_CLASSES = (
'corsheaders.middleware.CorsMiddleware',
'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'
)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [(os.path.join(ROOT_PATH, 'templates'),)],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.i18n',
'django.contrib.messages.context_processors.messages',
],
},
},
]
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
'django.contrib.humanize',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'myapp',
)
...
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissions',
]
}
# JWT settings
JWT_AUTH = {
'JWT_ENCODE_HANDLER':
'rest_framework_jwt.utils.jwt_encode_handler',
'JWT_DECODE_HANDLER':
'rest_framework_jwt.utils.jwt_decode_handler',
'JWT_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_payload_handler',
'JWT_PAYLOAD_GET_USER_ID_HANDLER':
'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',
'JWT_RESPONSE_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_response_payload_handler',
'JWT_SECRET_KEY': SECRET_KEY,
'JWT_GET_USER_SECRET_KEY': None,
'JWT_PUBLIC_KEY': None,
'JWT_PRIVATE_KEY': None,
'JWT_ALGORITHM': 'HS256',
'JWT_VERIFY': True,
'JWT_VERIFY_EXPIRATION': True,
'JWT_LEEWAY': 0,
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
'JWT_AUDIENCE': None,
'JWT_ISSUER': None,
'JWT_ALLOW_REFRESH': False,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
'JWT_AUTH_HEADER_PREFIX': 'Bearer',
'JWT_AUTH_COOKIE': None,
}
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False
That configuration is causing that ALLOWED_HOSTS is applied to the WebApp urls and also to the API URLs.
UPDATE 2
Something I didn't say, is that I want that API public. I mean, let's suppose that I didn't know which hosts will invoke my API. So, what I want to do is:
WebApp: should be just called from known hosts (ALLOWED_HOSTS should be applied)
API: can be called from unknown hosts (ALLOWED_HOSTS control should not be applied here).
Is this possible? How can I achieve this?
Thanks!
Yes you can use Django Rest Framework with your Django webapp with no problem at all. Moving to cors part you should first install pip install django-cors-headers
then add corsheaders to installed apps
INSTALLED_APPS = (
...
'corsheaders',
...
)
Add middleware properly in settings.py
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
... ]
lastly you should do in settings.py as you are allowing every host
CORS_ORIGIN_ALLOW_ALL = True
else make the whitelist
CORS_ORIGIN_WHITELIST = (
'hostname.example.com',
'localhost:8000',
'127.0.0.1:9000'
)

why would django not find templates for installed 3rd party apps that are in site-packages?

I recently spun off an old project and tried installing its apps (which worked) and also installing django-helpdesk/bootstrap_forms. But django could find neither helpdesk templates, or bootstrapform templates. My settings.py looks like:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'key'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
'index',
'taggit',
'helpdesk',
'bootstrapform',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
HELPDESK_PATH = "/home/cchilders/.local/virtualenv/new_bookmarks/lib/python2.7/site-packages/helpdesk/templates",
BOOSTRAPFORM_PATH = "/home/cchilders/.local/virtualenv/new_bookmarks/lib/python2.7/site-packages/bootstrapform/templates"
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates"),
"/home/cchilders/.local/virtualenv/new_bookmarks/lib/python2.7/site-packages/helpdesk/templates",
"/home/cchilders/.local/virtualenv/new_bookmarks/lib/python2.7/site-packages/bootstrapform/templates",],
'APP_DIRS': False,
'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',
],
},
},
]
STATIC_ROOT = '/home/cchilders/django_practice/new_bookmarks/static'
STATIC_URL = '/static/'
I don't have an issue now, but am very confused as to why I had to manually do HELPDESK_PATH and BOOSTRAPFORM_PATH. The last time I spun this up, installing the apps worked out the box, with the same TEMPLATE configs. I have these installed:
Django==1.8.3
argparse==1.2.1
betterpath==0.2.2
django-bootstrap-form==3.2
django-extensions==1.5.5
django-helpdesk==0.1.16
django-markdown-deux==1.0.5
django-mptt==0.7.4
django-taggit==0.16.2
email-reply-parser==0.3.0
ipython==3.2.1
l==0.3.1
lxml==3.4.4
markdown2==2.3.0
pytz==2015.4
requests==2.7.0
simplejson==3.8.0
six==1.9.0
vcversioner==2.14.0.0
wsgiref==0.1.2
zope.interface==4.1.2
I am running a VE (like I was when it found templates) and packages are where expected:
~/.local/virtualenv/new_bookmarks/lib/python2.7/site-packages/bootstrapform/templates
When turning off the new URLS back to 'DIRS': [os.path.join(BASE_DIR, "templates"), ], I get
TemplateDoesNotExist at /helpdesk/
helpdesk/public_homepage.html
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
/home/cchilders/django_practice/new_bookmarks/templates/helpdesk/public_homepage.html (File does not exist)
and I don't get why it isn't checking the usual places. My VE works, if I deactive it I can't runserver due to missing packages like 'taggit'. What usually causes django to ignore site-packages and not look for templates beyond BASE_DIR/templates? Thank you

Categories