Creating Django superuser
max-miller
HOBBYOP

3 months ago

Hello,

I've got a very basic Django project up and running from the template, but now I can't seem to get any of the usual Django actions to happen. Based on my searching around the documentation and forums, I have the railway CLI installed, I linked the project, but if I try to run 'railway run manage.py createsuperuser' I get the following error:

'django.db.utils.OperationalError: could not translate host name "postgres.railway.internal" to address: nodename nor servname provided, or not known'

$10 Bounty

17 Replies

dardameiz
PRO

3 months ago

Hello, I had the same problem, then I found the solution. Why this happens is because railway is trying to use the internal network which cannot be used only within railway services, between each other. The solution is to use the DATABASE_PUBLIC_URL. You need to add the DATABASE_URL and the python createsuperuser in the same command otherwise if you first export DATABASE_URL=xxxx.railway.proxy etc, then railway will override it with the internal host name which will also run on error. Therefore try this:

CLI:
after railway login
DATABASE_URL="insert here the DATABASE_PUBLIC_URL" python manage.py createsuperuser

then it will go further the same way then in localhost


dardameiz

Hello, I had the same problem, then I found the solution. Why this happens is because railway is trying to use the internal network which cannot be used only within railway services, between each other. The solution is to use the DATABASE_PUBLIC_URL. You need to add the DATABASE_URL and the python createsuperuser in the same command otherwise if you first export DATABASE_URL=xxxx.railway.proxy etc, then railway will override it with the internal host name which will also run on error. Therefore try this:CLI:after railway loginDATABASE_URL="insert here the DATABASE_PUBLIC_URL" python manage.py createsuperuserthen it will go further the same way then in localhost

max-miller
HOBBYOP

3 months ago

Hmm, makes sense, but I'm having trouble implementing - do I need to add 'railway run' to that line?

If I do: DATABASE_URL="..." python manage.py createsuperuser, that errors out with a key error for 'PGDATABASE'

if I do: DATABASE_URL="..." railway run python manage.py createsuperuser, that prompts me to select a service (server or Postgres) to pull variables, but then gives me the same error I had up top ('could not translate the host name...')

If I do: railway run DATABASE_URL="..." python manage.py createsuperuser, it prompts me to select a service and then tells me 'No such file or directory'

And finally completing the set of all variants I could think of, if I do railway DATABASE_URL="..." run python manage.py createsuperuser, it errors telling me that 'DATABASE_URL...' is an unrecognized subcommand


dardameiz
PRO

3 months ago

Do you insert there the DATABASE_PUBLIC_URL whitch contains the proxy link? Because when I have the railway.internal link in the database_url I can choose the service and I would run again to the same host name error.

I did not have to put railway run for me it was working fine without that (using vs code). I am running though the command in my directory where the project is and the local env is activated already. Have you tried like that?


hieuggit02
HOBBY

3 months ago

Hi, i'm still doing on the django project

You are encountering this error because of how railway run works.

It executes the command locally on your computer. It pulls the environment variables from Railway, including DATABASE_URL. Railway's default database URL uses an internal hostname (postgres.railway.internal). Your local computer is outside Railway's internal network, so it cannot resolve (find) that address.

The Solution

You need to run the command inside the Railway server, not on your local machine.

Option 1: Use railway shell

This opens a terminal session directly inside your running deployment. Since you are "inside" the network, the internal hostname will work.

Open your terminal and run:

railway shell

Once connected, run your Django command:

  • python manage.py createsuperuser

Option 2: Use the Public URL (Local workaround)

If you absolutely must run this from your local machine, you need to override the internal URL with the public one.

Go to Railway Dashboard → Postgres → Connect.

Copy the Public Connection URL (starts with postgresql://... and ends with .net).

Run the command locally by overriding the variable:

Mac/Linux:

  • DATABASE_URL="your_public_url_here" python manage.py createsuperuser

Windows (PowerShell):

PowerShell

  • $env:DATABASE_URL="your_public_url_here"; python manage.py createsuperuser

Use railway shell. It is the standard way to run production management commands like migrations or creating superusers.

Hopefully, this will have you solve it.

Good luck


dardameiz

Do you insert there the DATABASE_PUBLIC_URL whitch contains the proxy link? Because when I have the railway.internal link in the database_url I can choose the service and I would run again to the same host name error.I did not have to put railway run for me it was working fine without that (using vs code). I am running though the command in my directory where the project is and the local env is activated already. Have you tried like that?

max-miller
HOBBYOP

3 months ago

Yes, where I have been writing DATABASE_URL="..." I have been inserting the database public url. Perhaps I have been copying in the wrong address? But there's only one obvious place to get an address for the database that I can see (clicking on the Postgres -> Settings - > Public Networking).

I am in the directory (where the manage.py file is, so I think there's only one place I can be), I have the env active. I must be missing something that is obvious to everyone else, but for the life of me I can't figure it out.


dardameiz
PRO

3 months ago

yes but you need the full link and the DATABASE_PUBLIC_URL you can find it in the variables of Postgres. slightly_smiling_face emoji


dardameiz
PRO

3 months ago

Here:

Attachments


dardameiz

Here:

max-miller
HOBBYOP

3 months ago

Ah, well, that's at least one stupid mistake of mine identified! I'm still erroring out when I try to run manage.py:

"'NAME': os.environ["PGDATABASE"],

File "/usr/local/bin/../../../Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 678, in getitem

raise KeyError(key) from None

KeyError: 'PGDATABASE'"


dardameiz
PRO

3 months ago

Ah sorry. I suggest you to use dj-database-url. What it does is that it parses the database important parts from the URL added. Meaning:

Input (one string):

postgresql://postgres:mypassword@host.railway.app:5432/railway

Output (Django-compatible dict):

{

'ENGINE': 'django.db.backends.postgresql',

'NAME': 'railway',

'USER': 'postgres',

'PASSWORD': 'mypassword',

'HOST': 'host.railway.app',

'PORT': 5432,

}

I am using dj-database-url therefore it was working for me.

what you can do:

1. install dj-database-url (pip install dj-database-url)

  1. try to add all the database login details like this and run it in shell.

    DATABASE_URL="postgresql://postgres:PASSWORD@HOST:PORT/railway" \

    PGDATABASE="railway" \

    PGUSER="postgres" \

    PGPASSWORD="PASSWORD" \

    PGHOST="HOST" \

    PGPORT="PORT" \

    python manage.py createsuperuser

above variables, you can copy out from the Variables of postgres

let me know if you had success!


dardameiz

Ah sorry. I suggest you to use dj-database-url. What it does is that it parses the database important parts from the URL added. Meaning:Input (one string):postgresql://postgres:mypassword@host.railway.app:5432/railway Output (Django-compatible dict):{'ENGINE': 'django.db.backends.postgresql','NAME': 'railway','USER': 'postgres','PASSWORD': 'mypassword','HOST': 'host.railway.app','PORT': 5432,}I am using dj-database-url therefore it was working for me.what you can do:1. install dj-database-url (pip install dj-database-url)try to add all the database login details like this and run it in shell. DATABASE_URL="postgresql://postgres:PASSWORD@HOST:PORT/railway" \PGDATABASE="railway" \PGUSER="postgres" \PGPASSWORD="PASSWORD" \PGHOST="HOST" \PGPORT="PORT" \python manage.py createsuperuserabove variables, you can copy out from the Variables of postgreslet me know if you had success!

max-miller
HOBBYOP

3 months ago

Not quite, now I'm getting an operation time out error...


dardameiz
PRO

3 months ago

try the following.

Install dj database url with pip, then update your settings.py: 🇦

import dj_database_url

DATABASES = {

'default': dj_database_url.config(

default=os.environ.get('DATABASE_URL'),

conn_max_age=600

)

}

then you can try to run this in terminal:

DATABASE_URL="your_DATABASE_PUBLIC_URL" python manage.py createsuperuser

If you still have problem maybe you could try to check if public networking is enable for postgres in the settings under networking? By default I think it is

Let me know if this worked


dardameiz

try the following.Install dj database url with pip, then update your settings.py:import dj_database_urlDATABASES = {'default': dj_database_url.config(default=os.environ.get('DATABASE_URL'),conn_max_age=600)}then you can try to run this in terminal:DATABASE_URL="your_DATABASE_PUBLIC_URL" python manage.py createsuperuserIf you still have problem maybe you could try to check if public networking is enable for postgres in the settings under networking? By default I think it isLet me know if this worked

max-miller
HOBBYOP

3 months ago

This mysteriously is a partial fix - after importing dj_database_url and using it to format the database dictionary output, I can indeed successfully run createsuperuser! but if I need to do anything else that touches the database (say, make migrations) it fails and gives me an error for that line in the settings.py file I added using dj_database_url.config(). It says:

% (spliturl.scheme, ", ".join(sorted(SCHEMES.keys())))

ValueError: No support for ''. We support: cockroach, mssql, mssqlms, mysql, mysql-connector, mysql2, mysqlgis, oracle, oraclegis, pgsql, postgis, postgres, postgresql, redshift, spatialite, sqlite, timescale, timescalegis

It seems that dj_database_url is using urllib to parse the url. urllib is looking for a scheme like 'http', 'file' or 'imap' or something, not finding one and then passing a blank string, but dj_database_url is expecting the scheme to be the sql type and not expecting the blank string.

This error arises just from calling dj_database_url.config(default=os.environ.get('DATABASE_URL'), I tried making a separate script to try to debug that line, and I couldn't make anything work, there does not seem to be a way to pass an expected scheme type to dj_database_url that would override what it's getting from urllib. I don't understand why it doesn't crash createsuperuser as well?


dardameiz
PRO

3 months ago

The issue is DATABASE_URL is somehow being set to an empty string. A few things to check:

1. Check if DATABASE_URL is already set in your shell: echo $DATABASE_URL

If it shows blank, that’s your problem. (after setting it)

You can try this:

  1. unset DATABASE_URL

  2. DATABASE_URL="your_DATABASE_PUBLIC_URL" python manage.py makemigrations

Try this workaround in settings.py:

import dj_database_url

import os

db_url = os.environ.get('DATABASE_URL')

if not db_url or db_url == '':

raise ValueError("DATABASE_URL is not set or is empty!")

DATABASES = {

'default': dj_database_url.config(

default=db_url,

conn_max_age=600

)

}

Even thugh you use the same this can at least say if this is set or not.

Let me know if you see an error


dardameiz

The issue is DATABASE_URL is somehow being set to an empty string. A few things to check:1. Check if DATABASE_URL is already set in your shell: echo $DATABASE_URLIf it shows blank, that’s your problem. (after setting it)You can try this:unset DATABASE_URLDATABASE_URL="your_DATABASE_PUBLIC_URL" python manage.py makemigrationsTry this workaround in settings.py:import dj_database_urlimport osdb_url = os.environ.get('DATABASE_URL')if not db_url or db_url == '':raise ValueError("DATABASE_URL is not set or is empty!")DATABASES = {'default': dj_database_url.config(default=db_url,conn_max_age=600)}Even thugh you use the same this can at least say if this is set or not.Let me know if you see an error

max-miller
HOBBYOP

3 months ago

This just get stranger and stranger to me. It seems that the very act of passing the environmental variable is causing the dj_database_url to fail. I've been trying to debug in a separate test.py file. Just testing the variable by itself, for instance, I use just the snippet of code to get the url and test that it isn't null:

db_url = os.environ.get('DATABASE_URL')
if not db_url or db_url == '':
raise ValueError("DATABASE_URL is not set or is empty!")
print(db_url)

This runs, doesn't raise an error and prints out the url. But the dj_database_url.config() call is still crashing, so I try debugging that on its own. If I hard code the database url like this:

db_url = "hardcoded_url"
DATABASES = {'default': dj_database_url.config(default=db_url,
conn_max_age=600)}

And run without passing in an environment variable, it runs no problem, seems like dj_database_url is properly parsing the string. I try comparing the string that the script is getting from environmental variable like this:

db_url = "hardcoded_url"
db_url_test = os.environ.get('DATABASE_URL')

print(db_url)
print(db_url_test)

I discover that, strangely, the string from the environmental variable has extraneous quote marks (like '"url"'), maybe that is my issue, but while testing that I discover that just passing in the environ variable causes the hardcoded version (which previously had worked fine) to crash, as in, the code that was like:

db_url = "hardcoded_url"
DATABASES = {'default': dj_database_url.config(default=db_url,
conn_max_age=600)}

works if I call python test.py,

but errors out if I call DATABASE_URL="..." python test.py


dardameiz
PRO

3 months ago

This is a shell escaping issue, it takes the “..” as well. Can you try it without them?

so just:

DATABASE_URL=postgresql://postgres:password@host.railway.app:port/railway python manage.py makemigrations


dardameiz

This is a shell escaping issue, it takes the “..” as well. Can you try it without them?so just:DATABASE_URL=postgresql://postgres:password@host.railway.app:port/railway python manage.py makemigrations

max-miller
HOBBYOP

3 months ago

Well, that was the final issue. I still don't quite understand why getting the environ variable was causing the function to fail even when it didn't use that variable, but I have a solution that works now, so I'm not going to dwell on it. Thank you for all this troubleshooting help!


mujirin
PRO

3 months ago

Try to create super user in the views, for example in a view function (for example profile), if the username is match you, make yourself as a superuser.


Loading...