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:
python manage.py shellfrom 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
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:
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:
INSERT INTO employees_user (Username, Password, RoleId_id)
VALUES ('admin',
'pbkdf2_sha256$870000$k3J9xQ2mP1aB$Zr8f0...paste-your-full-hash...=',
1); -- 1 = the RoleId of AdminKeep 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
| Symptom | Cause |
|---|---|
| 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 fails | The RoleId_id value doesn’t exist in employees_role |
Unknown column 'RoleId' | Use RoleId_id in the users table |
Table doesn't exist | Run SHOW TABLES; and use the real names |
Duplicate entry | The username is already taken (Username is unique) |
Notes
- 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.
- 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.
- Use SQL only for seeding test data. For normal user creation, use the
/api/register/endpoint (Admin only), which hashes the password for you. - 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