Is it possible to make my own createsuperuser command in django?

我怕爱的太早我们不能终老 提交于 2019-12-11 09:57:55

问题


I'm working on an app in which I've made my customized 'User' model which takes email as user name and it is dependent on another model called 'Company'. When running command 'python manage.py createsuperuser' I need that django asks me for company first and create company instance, than asks for User model fields in which 'company' is a foreign key and then user provides company id possibly '1' which the user already created when making company object.

I'm trying to implement above by creating management folder in my app, but it doesn't seems to work.

Can anybody please tell me the correct approach to do it.

Thanks in Advance.


回答1:


Most definitely! The createsuperuser function isn't too special; it just creates a user with the is_superuser flag set to True. You can write your own method that creates users and sets the superuser flag, along with whatever else you want, by following the instructions in the first link.




回答2:


Yes you can, these commands are called management commands and you can write one following guide in docs Writing custom django-admin commands

Asking for user input can be done with input() function:

#/django/contrib/auth/management/commands/createsuperuser.py

from django.utils.six.moves import input
def get_input_data(self, field, message, default=None):
        """
        Override this method if you want to customize data inputs or
        validation exceptions.
        """
        raw_value = input(message)
        if default and raw_value == '':
            raw_value = default
        try:
            val = field.clean(raw_value, None)
        except exceptions.ValidationError as e:
            self.stderr.write("Error: %s" % '; '.join(e.messages))
            val = None

        return val

Full source code for Django's createsuperuser can be found on Github.



来源:https://stackoverflow.com/questions/33215065/is-it-possible-to-make-my-own-createsuperuser-command-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!