หากไม่มี superuser ในการโยกย้าย Django จะสร้างขึ้นมา
I have a migration that creates a superuser if it does not exist. <code>def create_superuser(apps, schema_editor): User = apps.get_model('auth', 'User') if not User.objects.filter(username='admin').exists(): User.objects.create_superuser('admin', 'admin@example.com', 'password') class Migration(migrations.Migration): dependencies = [ ('myapp', '0001_initial'), ] operations = [ migrations.RunPython(create_superuser), ] </code>
บรรทัดแรกสร้างฟังก์ชันที่จะสร้าง superuser ถ้าไม่มีอยู่แล้ว
บรรทัดที่สองรับ User model จากแอป 'auth'
บรรทัดที่สามตรวจสอบเพื่อดูว่ามีผู้ใช้ที่มีชื่อผู้ใช้ว่า "admin" อยู่หรือไม่ ถ้าไม่,
บรรทัดที่สี่สร้าง superuser ด้วยชื่อผู้ใช้ 'admin' ที่อยู่อีเมล 'admin@example.com' และรหัสผ่าน 'password'
บรรทัดที่ห้าและหกสร้างคลาสการย้ายข้อมูลและระบุว่าขึ้นอยู่กับการย้ายข้อมูล '0001_initial' ในแอป 'myapp'
บรรทัดที่เจ็ดระบุว่าการย้ายข้อมูลควรเรียกใช้ฟังก์ชัน 'create_superuser'
Superuser คืออะไร
superuser คือผู้ใช้ที่มีสิทธิ์ระดับผู้ดูแลระบบบนไซต์ Django พวกเขาสามารถทำสิ่งต่างๆ เช่น สร้างและจัดการโมเดล มุมมอง และแอปพลิเคชัน