can't restore my site back after adding allowed_hosts = ['*']

Hello Brothers i need really support and help on this please
i was trying to solve some bugs in my env vars .env file and i faced a problem to set multiple hosts in .env file
i have tried something that i never tried before in my settings

ALLOWED_HOSTS = ['*']

i know that this line allowing all kinds of hosts and is not secure but i didn’t think that it will causing a problem and i can retrieve back everything
after running my server locally using normal command runserver
i find the site redirected to strange port , and i don’t remember the number
but after removing the all host line
i can’t restore my site anymore
every time i go to localhost:8000
i found nothing just the page reloading and nothing happens, and at the end i got

This site can’t be reached

localhost took too long to respond**
While my terminal doesn’t show any logs or traces or errors
also i have tried to change the running port and everything but never work
i have mem caches but i don’t know what is really causing this by adding **allowed hosts to ***
how can i fix this please cause i can’t find any related issues

That means that going to localhost:8000 isn’t going to get you to your site. It also generally means that you’ve got some other process running on your system that is connecting to port 8000, preventing runserver from using that port.

Stop and restart runserver, making note of the port number that it gives you, and connect to it instead of 8000.

Side note: This has absolutely nothing to do with your ALLOWED_HOSTS setting. It is only related to what else you might have running on your computer.

but when i stop and restart the server it gives me the same port number and no any issues

Screenshot 2022-12-17 at 3.14.27 PM

Screenshot 2022-12-17 at 3.13.56 PM

So it’s fixed then? You’re now able to connect?


really i am so sad bro i feel like i am destroying myself by continuing in this issues
i don’t know what to do

i will try to rebuild again and see what is the reason from beginning
anyway i can’t go without thanking you for replying me
appreciated brother @KenWhitesell

hey my brother @KenWhitesell
when i pressed the link provided to the terminal
i got
Screenshot 2022-12-17 at 3.25.46 PM
what that mean exactly
maybe this is the port that’s been redirected to when i added allowed hosts to *
i went there
https://127.0.0.1:51359/
but still got nothing either in terminal or in browser, so do you have any idea how to back to normal please

That port (51359) is your browser’s port. Your server is running on 8000 as identified on the line two above that.

An HTTP 301 is a redirect. Your base url is trying to redirect you somewhere.

What does your root urls.py file look like?

Oh Thank God, i thought you will never reply me and i was trying to know what is the relation between
this in my settings
.env
ENVIRONMENT=production
and settings.py

ENVIRONMENT = os.getenv('ENVIRONMENT', 'development') # development is the default valuew
if ENVIRONMENT == 'production':
    DEBUG = True
    SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key())
    SESSION_COOKIE_SECURE = True
    SECURE_BROWSER_XSS_FILTER = True
    SECURE_CONTENT_TYPE_NOSNIFF = True
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_HSTS_SECONDS = 60   
    SECURE_REDIRECT_EXEMPT = []
    SECURE_SSL_REDIRECT = True
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

as this line
SECURE_HSTS_SECONDS = 60 # may break the site
but as environment is production so it has no relation
and here is the urls.py in project folder

API_TITLE = 'Site API'
API_DESCRIPTION = 'A Web API for creating and viewing highlighted code snippets.'
schema_view = get_schema_view(title=API_TITLE)
urlpatterns = [
    path('admin', admin.site.urls),
    #re_path(r'^schema/$', schema_view), # old deprecated
    #re_path(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION)), # old deprecated
    path('openapi', get_schema_view(title="My Project", description="API for all things …"), name='openapi-schema'), # the newest one
    # to get the built-in authinticatuion views login/logout/change_password/etc...
    #path('accounts/', include('django_registration.backends.activation.urls')),
    path('accounts/', include('django.contrib.auth.urls')),
    path('accounts/', include('account.urls', namespace='accounts')),
    path('contacts/', include('contact.urls', namespace='contacts')),
    path('jobs/', include('job.urls', namespace='jobs')), 
    #re_path(r'^blog/', include('blog.urls')),
    path('blog/', include('blog.urls', namespace='blog')),
    path('', include('home.urls', namespace='home')),
    #re_path(r"^messages/", include("messages.urls", namespace="messages")), it was pinax.message but i took it outside the pinax abn made it free
    path('messages/', include('postman.urls', namespace='postman')), # just alternated by pinax.messages
    path("chat/", include("chat.urls", namespace='chat')),
    re_path(r'chat2/', include('django_private_chat2.urls', namespace='django_private_chat2')),
    #re_path(r'^api/', include('rest_framework.urls', namespace='rest_framework')),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), # has no relation with others blog urls only for login to api
    path('__debug__/', include(debug_toolbar.urls)), # after install django-debug-toolbar
] + staticfiles_urlpatterns()
if settings.DEBUG:
    urlpatterns+= static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
# ...
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

if you want anything else tell me please
and thanks a lot for replying me again god bless you

Are you saying that for this test you’ve got ENVIRONMENT = production?

(Side note: Delays in my responses shouldn’t be taken personally. This is a hobby that I’m doing in my spare time. Other things do take priority over this - I get to questions when I can and when I’m able.)

yes bro it was production and still same but i don’t know what causing that
also i know that this is a hobby but i though as you don’t know more information about the problem you will leave it and not reply except when i post again but i know that it’s not delay
anyway hope if i can help you once a day as you always been so helpful for me

Ok, so the problem is here:

If ENVIRONMENT = production, then SECURE_SSL_REDIRECT == True - which means that any request to http://localhost is going to be redirected to https://localhost, which your localhost isn’t set up to handle.

There are going to be a couple issues that you would need to address if you tried to run your system in “production” mode - this is just the first.

AHA
i have changed this to False and any kind of related to production and revert to dev and nothing happens

DJANGO_DEBUG=True
DEVELOPMENT_MODE=False
ENVIRONMENT=development

still same
anyway there maybe something has broken and i will recreate the site and back to you
cause the problem was that i am not able to have multiple .env hosts as local and digital ocean

Meaning you’re still getting the 301 on the root url?

What happens if you try a different url such as admin?

If admin/ works, what does your ‘home/urls.py’ file look like?

i have removed everything brother database and all the project and recreated all things with the same code forgive me on latency for reading, cause i was trying to see if anything in the project is causing this
and i have installed postgresql 15 with 14 and both works fine in pgadmin but i can’t run except one of them on the localhost

so the database has no relation
i know that you told me to not think ever to delete the database but i have no data already on it
this is my first project to deploy and it’s my profile
so i was keeping the same code that already works before
so the problem is in .env and settings
after i recreate the project
the same thing happens as i didn’t change anything
even admin page i can’t get it the same thing happens on any url not only home
i have created new super user and it has been created successfully and no errors but still cant see anything in browser
so here is the all settings and .env file
setings.py

from pathlib import Path
import os
from django.core.management.utils import get_random_secret_key
import psycopg2
import sys
import dj_database_url
from dotenv import load_dotenv
load_dotenv()

INSTALLED_APPS = [ #  pip install django-phonenumber-field[phonenumbers
    'rest_framework',
    'account.apps.AccountConfig',
    'django.contrib.admin',
    "daphne",
    'django.contrib.auth', # Core authentication framework and its default models
    'django.contrib.contenttypes', # Django content type system (allows permissions to be associated with models).
    'django.contrib.sessions',
    'django.contrib.sites', # set of a single Django application/codebase with different sites (that can use different databases, logic in views, etc)
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'phonenumber_field',  # pip install django-phonenumber-field[phonenumberslite]
    'crispy_forms',
    "mailer",
    #'django_registration',
    'django_filters',
    # CORS
    'corsheaders',
    'bootstrap4',
    "django_bootstrap5",
    'chat',
    'blog.apps.BlogConfig', 
    'home.apps.HomeConfig', 
    'contact.apps.ContactConfig',
    'job.apps.JobConfig',
    'postman.apps.PostmanConfig', # either this or post man not both
    'ajax_select',
    'pinax.notifications',
    #"messages", # it will clashes with postman.Message, so don't activate both, but just one and postman is the best ever
    'django_private_chat2.apps.DjangoPrivateChat2Config',
    'debug_toolbar', # after install pip3 install django-debug-toolbar
]
SITE_ID=1 
AUTH_USER_MODEL = 'account.User' # because we have extended user Model using a custome model in user app
ACCOUNT_ACTIVATION_DAYS = 7 # One-week activation window
MIDDLEWARE = [
    # CORS
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware', # Manages sessions across requests
    'django.middleware.cache.UpdateCacheMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware', # after pip3 install django-debug-toolbar
    'django.contrib.auth.middleware.AuthenticationMiddleware', # Associates users with requests using sessions.
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.locale.LocaleMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
    'http://localhost:8080',
)
#CACHE_MIDDLEWARE_ALIAS = '' # The cache alias to use for storage
CACHE_MIDDLEWARE_SECONDS = 600 # The number of seconds each page should be cached
CSRF_COOKIE_AGE = 31449600 

CACHE_MIDDLEWARE_KEY_PREFIX = ''
CRISPY_TEMPLATE_PACK = 'bootstrap4'
ROOT_URLCONF = 'project.urls'
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
#BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
        'LOCATION': ['127.0.0.1:11211', '0.0.0.0:11211'],
        'TIMEOUT': 200,
        'OPTIONS': {
            'no_delay': True,
            'ignore_exc': True,
            'max_pool_size': 4,
            'use_pooling': True,
        }
    },
    'redis': {
        'BACKEND': 'django.core.cache.backends.redis.RedisCache',
        'LOCATION': ['redis://127.0.0.1:6379', os.getenv("REDIS_URL"),],
        'OPTIONS': {
            'db': '10',
            'parser_class': 'redis.connection.PythonParser',
            'pool_class': 'redis.BlockingConnectionPool',

        }
    },
    'dummy': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
    }
}

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',
                #"messages.context_processors.user_messages", # i would use postman
            ],
        },
    },
]

WSGI_APPLICATION = 'project.wsgi.application'
CSRF_COOKIE_SECURE = True


REST_FRAMEWORK = {

    'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

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',
    },
]

EMAIL_BACKEND = "mailer.backend.DbBackend"
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

# Postman Settings
POSTMAN_I18N_URLS = True # True, if you want the internationalization of URL patterns, Defaults to: False
POSTMAN_DISALLOW_ANONYMOUS = True # True if you do not allow visitors to write to users, default is False
POSTMAN_DISALLOW_MULTIRECIPIENTS = False  # True if you do not allow more than one username in the recipient field, default is False.
POSTMAN_DISALLOW_COPIES_ON_REPLY = False # True if you do not allow additional recipients when replying, default is False.
POSTMAN_DISABLE_USER_EMAILING = False # True if you do not want basic email notification to users.
POSTMAN_NOTIFICATION_APPROVAL = 'account.views.notification_approval'

def get_from_email(context):
    return '<{} admin> no-reply@domain.tld'.format(context['action'])
POSTMAN_FROM_EMAIL = 'from@host.tld'   # get_from_email, default is DEFAULT_FROM_EMAIL
def get_params_email(context):
    return {
        'reply_to': ['someone@domain.tld'],
        'headers': {'X-my-choice': 'my-value'}
    } if context['action'] == 'acceptance' else {}
POSTMAN_PARAMS_EMAIL = get_params_email  # default is None
POSTMAN_AUTO_MODERATE_AS = True  # default is None
POSTMAN_SHOW_USER_AS = 'get_full_name' # lambda u: u.get_profile().nickname. like => progile.get_absolute_url()
POSTMAN_NAME_USER_AS = 'last_name'
POSTMAN_QUICKREPLY_QUOTE_BODY = True
POSTMAN_NOTIFIER_APP = 'pinax_notifications' 
POSTMAN_MAILER_APP = 'mailer'
POSTMAN_AUTOCOMPLETER_APP = {'name': 'ajax_select', 'field': 'AutoCompleteField', 'arg_name': 'channel', 'arg_default': {}}


SECRET_KEY = os.getenv("SECRET_KEY", get_random_secret_key()) # get_random_secret_key() supplied as default value

DEBUG = True

ALLOWED_HOSTS = ['nagies.digitalocean.com', 'localhost', '127.0.0.1'] # ALLOWED_HOSTS = ['*']

from django.core.exceptions import ImproperlyConfigured
def get_env_value(env_variable):
    try:
        return os.environ[env_variable]
    except KeyError:
        error_msg = 'Set the {} environment variable'.format(env_variable)
        raise ImproperlyConfigured(error_msg)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # django.db.backends.mysql'
        'NAME': os.environ.get('PG_NAME'), # DB Name os.environ['PG_NAME'],
        'USER': os.environ.get('PG_USER'),  # os.environ['PG_USER'], from server register => connection tab change the name of server and username
        'PASSWORD': os.getenv('PG_PASSWORD'), # os.environ['PG_PASSWORD'], 
        'HOST': os.environ.get('PG_HOST'),    # os.environ['PG_HOST'],
        'PORT': os.environ.get('PG_PORT'),  # int(os.environ['PG_PORT']),
    }
}

ENVIRONMENT = os.getenv('ENVIRONMENT', 'development') # development is the default valuew
if ENVIRONMENT == 'production':
    DEBUG = True
    SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key())
    SESSION_COOKIE_SECURE = True
    SECURE_BROWSER_XSS_FILTER = True
    SECURE_CONTENT_TYPE_NOSNIFF = True
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_HSTS_SECONDS = 60    # 31536000
    SECURE_REDIRECT_EXEMPT = []
    SECURE_SSL_REDIRECT = True
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..')
SITE_ROOT = PROJECT_ROOT / BASE_DIR # SITE_ROOT = BASE_DIR
TEMPLATE_DIRS = (

    os.path.join(SITE_ROOT, 'templates'),
)

STATIC_URL = '/static/' # then you can reach to all static from this url

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # for production use "/var/www/example.com/static/"

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIAFILES_DIRS = (BASE_DIR / 'media')

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

ASGI_APPLICATION = "project.asgi.application"
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    }, # you can add more channel layers here
}

.env

DJANGO_DEBUG=True
DEVELOPMENT_MODE=True
ENVIRONMENT=development
# production database
DB_NAME=db_name
DB_USERNAME=username
DB_PASSWORD=password
DB_URL=url...
DB_PORT=5342
# dev databse
PG_NAME=name
PG_USER=username
PG_PASSWORD=pasword
PG_HOST=localhost
PG_PORT=5432

SECRET_KEY='django-insecure-...'
DJANGO_ALLOWED_HOSTS=nagy.digitalocean.com,127.0.0.1,localhost

REDIS_URL=redis://...

DISABLE_COLLECTSTATIC = 1

please brother help me i am really disparate

everything was working fine before i added .env and trying to change my settings for production as you may remember my previous question for you on how to load
the env vars cause django can’t load it as you have told me to get some library to load them and i have found python-dotenv and django-dotenv and django-environ and solve that but was trying to run the server locally before keep changing settings to deploy and i came to allowed hosts and heppend this problem after please brother suggest on me what to do ?

no any other page is working no accounts or jobs or blog as though the site is hidden or something is hidding it from showing

In all cases here, please continue to copy/paste the text from your console window where you’re running runserver.

Also, your PGAdmin image implies that you’re running two instances of PostgreSQL on your system? Is that correct? Do you know which one is running on what port?

If there’s any issues or questions about your PostgreSQL instances, you should resolve them before trying to get Django working with it. If not, you’re not going to be able to tell when you’ve got your configuration correct.

Are you using git or some other version control system for your code? If not I’d urge you to do so, following a test driven development (TDD) process like the one in this free online book. This will allow you to carefully examine what changed right before things broke and help you understand what’s happening when they do.

i am running one instance of postgres on version 14 that has my site database locally and running on 5432
the photo just tell me i cant open the other server on port 5433 on the same localhost
now i got this error after removing bootstrap4 as it deprecated and it may cause this error but after removing it i got

% python3 manage.py runserver                             
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 1009, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 946, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/abunagy/Projects/mysite/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/Users/abunagy/Projects/mysite/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
    autoreload.raise_last_exception()
  File "/Users/abunagy/Projects/mysite/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "/Users/abunagy/Projects/mysite/lib/python3.10/site-packages/django/core/management/__init__.py", line 398, in execute
    autoreload.check_errors(django.setup)()
  File "/Users/abunagy/Projects/mysite/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/Users/abunagy/Projects/mysite/lib/python3.10/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/abunagy/Projects/mysite/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "/Users/abunagy/Projects/mysite/lib/python3.10/site-packages/django/apps/config.py", line 193, in create
    import_module(entry)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'bootstrap4'

how can i rid of that to get back to the console and copy the trace
also bro @eronlloyd , i always forget to commit my changes to git, and keep changing and changing really this is stupidity from me , so i can’t back to the previous working version, but i will doing this after this tragedy to not having all these problems

What do you think this message is telling you? What do you think the solution might be?