Saturday, October 24, 2026

Creating users directly in MySQL FOR JWT

 

Creating users directly in MySQL

Yes, it works, with one catch: the Password column must contain a Django password hash, not the plain password. Your check_password() compares the typed password against a hash. If you insert Admin@123 as plain text, login always fails with “Invalid username or password.”

Step 1: Generate a hash

Run this in the Django shell, which only creates the hash and saves nothing:

bash
python manage.py shell
python
from django.contrib.auth.hashers import make_password
print(make_password('Admin@123'))

The output looks like this (yours will differ, because each hash has a random salt):

pbkdf2_sha256$870000$k3J9xQ2mP1aB$Zr8f0...long-string...=

Copy the whole line.

Step 2: Check the table and column names

sql
SHOW TABLES;
DESCRIBE employees_user;

Django names tables <app>_<model>, so yours should be employees_role and employees_user. The foreign key column is RoleId_id, because your field is called RoleId and Django adds _id.

Step 3: Insert the data

Roles first, because users reference them:

sql
INSERT INTO employees_role (RoleName) VALUES ('Admin'), ('Manager'), ('Employee');
SELECT * FROM employees_role;     -- note the RoleId values (usually 1, 2, 3)

Then the user, pasting your own hash:

sql
INSERT INTO employees_user (Username, Password, RoleId_id)
VALUES ('admin',
        'pbkdf2_sha256$870000$k3J9xQ2mP1aB$Zr8f0...paste-your-full-hash...=',
        1);                       -- 1 = the RoleId of Admin

Keep the hash inside single quotes. It contains $, which is fine in MySQL but can be mangled if you paste it into a bash command line.

Step 4: Test login

POST http://127.0.0.1:8000/api/login/
{"Username": "admin", "Password": "Admin@123"}

You should get roleid, username, token and refresh.

Common problems

SymptomCause
Always “Invalid username or password”Plain text stored instead of a hash, or the hash was cut off when pasting
Cannot add or update a child row: a foreign key constraint failsThe RoleId_id value doesn’t exist in employees_role
Unknown column 'RoleId'Use RoleId_id in the users table
Table doesn't existRun SHOW TABLES; and use the real names
Duplicate entryThe username is already taken (Username is unique)

Notes

  1. One hash, many users is fine. If several test users should share a password, reuse the same hash. Each real user should have their own.
  2. Don’t store plain text and “fix it later.” Passwords stored as plain text are a real security risk, and your login will never accept them anyway.
  3. Use SQL only for seeding test data. For normal user creation, use the /api/register/ endpoint (Admin only), which hashes the password for you.
  4. Don’t create users in the Django admin unless you register a custom form. The default admin form would save the typed password as plain text, which fails login for the same reason.

No comments:

Post a Comment