Django - Authentication using REMOTE_USER - How to test in dev server? - python

I want to use django.contrib.auth.middleware.RemoteUserMiddleware for authentication as outlined here:
https://docs.djangoproject.com/en/dev/howto/auth-remote-user/
Question is, how can I test this in a dev environment where there is no Apache? i.e. can I set REMOTE_USER somehow in local settings?
EDIT (adding settings)
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.RemoteUserBackend',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
...
)
Then I have this in my local_Settings:
os.environ['REMOTE_USER'] = "mmatyas"
I also tried the 'HTTP_REMOTE_USER' variant. Thanks!

The variable has to be set in the environment in which you start the dev server. usually it's just:
REMOTE_USER=myuser ./manage.py runserver

You can write some WSGI middleware and set it there, and then make sure the wsgi middleware wraps your django app in the wsgi stack. lots of tutorials around on writing wsgi middleware, it'll be a short one page of code. Easy-peasy-lemon-squeezy!

In your dev environment, you can set an environment variable in the same command prompt you use to start up your dev server.
Something like export REMOTE_USER="duncan" if on a Unixy machine.
You can also do this by editing your manage.py and setting os.environ['REMOTE_USER'] = "duncan"

Related

How do I allow my django website to be hosted by a local server (127.0.0.1) and a Heruko server

I don't know if I am explaining my problem correctly but I can clarify with the following picture of my settings.py file
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECURITY WARNING: don't run with debug turned on in production!
# DEBUG = True
DEBUG = False
# ALLOWED_HOSTS = []
ALLOWED_HOSTS = ['sheryar-portfolio.herokuapp.com', '127.0.0.1']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pages',
'calculator',
'amino'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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',
]
Now here in ALLOWED_HOSTS, I have declared two hosts.
The Heroku one is running perfectly whereas I am having some issues in the local one.
It seems like that my static folder is not being located by django as I can only see the HTML of my website in local server.
In short, I cannot see the CSS being applied to my website when I am including the local server in ALLOWED_HOST

Cannot connect to localhost:8000/admin page, Django

I created a superuser for my site, but when I started the server and tried to connect to the localhost:8000/admin page, I got an ERR_CONNECTION_REFUSED (site cannot be reached) error, and the server stopped running.
urls.py :
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('blog.urls'))
]
settings.py :
# Application definition
INSTALLED_APPS = [
'blog.apps.BlogConfig',
'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',
]
When I start the server, I get the below message:
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
May 17, 2020 - 18:25:44
Django version 3.0.1, using settings 'django_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
same happened to me. I realized that i defined the path with / but i was writing localhost:8000/admin
path('admin/', admin.site.urls)
I should type admin/ localhost:8000/admin/
Check if the firewall is causing any problem. (If only admin page is causing this problem, then firewall is not causing any probelm.)
Make sure that you have made necessary changes in urls.py and views.py.
Project's urls.py should include
path('admin/', admin.site.urls), in urlpatterns list.
settings.py should include
INSTALLED_APPS = ['django.contrib.admin',
...#more apps
]`
Let me know if this is helpful.
I was facing the same problem .My vpn was causing the problem .Go to chrome menu >setting>advanced settings>here my vpn was controlling the proxy settings and just disabling it fixed the issue .All the best
Try cleaning browser cache and then refreshing.
Additionally, in case you have created a custom User model, make sure you
Register your custom user model in the admin.py of the app where you defined your custom user model (see https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Admin_site#registering_models)
In the settings.py, define a variable AUTH_USER_MODEL = '<app-name>.<custom-user-model-name>'
you forgot to runserver! python manage.py runserver

Heroku Django app not loading static files (404 Not Found)

I have been trying to deploy a django app onto heroku. However, it's not able to obtain the static files. I ran collecstatic on heroku and there is a static folder in the root directory of the app that contains the correct files:
~/static/rest_framework/css/bootstrap.min.css.
Settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
cURL:
curl 'https://xxx.herokuapp.com/static/rest_framework/css/bootstrap.min.css' \
-XGET \
-H 'Referer: https://xxx.herokuapp.com/users/login' \
-H 'Accept: text/css,*/*;q=0.1' \
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7'
I've spent some hours before I was able to figure out this. #VipinMohan solution works for whitenoise<4. However, in version 4+, WhiteNoise removes some options which were deprecated in the previous major release. For the record, I am using Django 2.1.
From the docs:
The WhiteNoise middleware should be placed directly after the Django SecurityMiddleware (if you are using it) and before all other middleware.
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
# the next line of code is the one that solved my problems
'whitenoise.middleware.WhiteNoiseMiddleware',
'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'
]
Pay attention to the Note in the section of the provided link.
You might find other third-party middleware that suggests it should be given highest priority at the top of the middleware list. Unless you understand exactly what is happening you should ignore this advice and always place WhiteNoiseMiddleware above other middleware.
Django does not support serving static files in production. However, the fantastic WhiteNoise project can integrate into your Django application, and was designed with exactly this purpose in mind.
pip install whitenoise
add whitenoise to your requirements.txt
add this code in app/wsgi.py
from whitenoise.django import DjangoWhiteNoise
application = DjangoWhiteNoise(application)
Add collectstatic to Procfile
web: python manage.py collectstatic --no-input; gunicorn myapp.wsgi --log-file - --log-level debug
Thanks to this stack overflow answer
WhiteNoise configuration should be changed if you use v4.0 or later.
Please refer this whitenoise-changelog

Deploying Django application in AWS. Raise Disallowed Host exception

I am newbie in Amazon Web Services and I'm trying to deploy a Django application using elastic BeansTalk. I'm following the AWS developer guide and when I deploy the application using EBCLI and open the browser to see my application running, I get the following error.
Request Method: GET Request URL: http://django-env.vsvztq2hxp.us-west-1.elasticbeanstalk.com/
Django Version: 1.9.12 Python Version: 3.4.3 Installed Applications:
['django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles'] Installed
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/opt/python/run/venv/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
123. response = middleware_method(request)
File "/opt/python/run/venv/lib/python3.4/site-packages/django/middleware/common.py" in process_request
56. host = request.get_host()
File "/opt/python/run/venv/lib/python3.4/site-packages/django/http/request.py" in get_host
109. raise DisallowedHost(msg)
Exception Type: DisallowedHost at /
Exception Value: Invalid HTTP_HOST header: 'django-env.vsvztq2hxp.us-west-1.elasticbeanstalk.com'. You may need to add 'django-env.vsvztq2hxp.us-west-1.elasticbeanstalk.com' to ALLOWED_HOSTS.
Obviosly the application was deployed but for some reason the exception raises.
Can anybody help me, please?
You are privileged to get such a verbose error..
Exception Type: DisallowedHost at / Exception Value: Invalid HTTP_HOST
header: 'django-env.vsvztq2hxp.us-west-1.elasticbeanstalk.com'. You
may need to add 'django-env.vsvztq2hxp.us-west-1.elasticbeanstalk.com'
to ALLOWED_HOSTS.
Just add django-env.vsvztq2hxp.us-west-1.elasticbeanstalk.com to your ALLOWED_HOSTS in settings.py
Do something like this
#in settings.py
ALLOWED_HOSTS = [ 'django-env.vsvztq2hxp.us-west-1.elasticbeanstalk.com', ...]
Try this:
ALLOWED_HOSTS = ['us-west-1.elasticbeanstalk.com']
in your settings.py file
Here is a great checklist before you deploy in prod.
https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

Can't login to Django admin using correct username and password

I have deployed a Django application on DigitalOcean using ngnix, gunicorn and a Postgresql database. Everything works just fine and when I run python manage.py syncdb and I'm able to create a user which populates my DB nicely.
Problem I'm having is that when I try to login to the Django admin interface I get prompted that I'm using the wrong username and/or password. I'm pretty sure the credentials are right as I have tried setting up the db multiple times.
Any ideas why Django thinks I'm inputing the wrong user info?
Thanks!
SETTINGS.py looks like
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'XXXXXXXXXXXXXXX'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
)
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 = 'qvido.urls'
WSGI_APPLICATION = 'qvido.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydbname',
'USER': 'user',
'PASSWORD': 'pass!',
'HOST': 'localhost',
'ROOT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_ROOT = '/webapps/django-env/static/'
STATIC_URL = '/static/'
WSGI.py looks like
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "qvido.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
EDIT
Ok, I aslo tried doing python manage.py dbshell and the select * from auth_user; I see the user I've created but still can't log in with it. So strange.
I apologize for the late answer, but I believe that this may be useful to someone.
I was having this same issue. After reading all of the comments to the original question, I was able to figure out what had happened.
During development, I had switched databases from an old test db to a new one which included all of the required tables rather than just changing the existing db. I had only changed the settings.py file to update the location of the new db, and did not touch the wsgi.py file. After migrating to the new db and removing the old file from the project, my admin user did not exist within the new database.
Based on comments by #Torsten Engelbrecht and the OP, all I needed to do was run the command suggested by #Alen thomas to make it functional again:
python manage.py createsuperuser
At this point I was able to set up the same admin account I'd used before, since it no longer existed. Now it all works fine. It might seem a little silly, but it pays to check the
So, I found the answer to why this was happening and indeed #scriptmonster was correct.
When I installed Django, Gunicorn etc. in my virtual-env I used sudo pip install which installed these outside of my virtaul-env.
I ran sudo chown -R myuser:myuser /webapps/myenv and then ran pip install django and pip install gunicorn again and everything worked just fine.

Categories

Resources