Create user Administrator using a view

0

I am currently taking a project that is very advanced and I am also new to django.

I would like to know in what way I can add a user as an administrator from view, normally the developers who started the project did it from the python shell I will show how they did it and what I have in the view but do not add me the user in the administrator model:

## From the Shell, the administrator user is created: ##

def load_examples(apps, schema_editor):

user = PlazasUser.objects.get(id=0)
content_type = ContentType.objects.get_for_model(PlazasUser)
permission = Permission.objects.create(codename='admin',
                                   name='Administrator',
                                   content_type=content_type)
user.user_permissions.add(permission)
user.is_active = True
user.save()
  

This way the administrator users are created from the shell now I want to take it to a view but the user does not register me as administrator:

Models:

class PlazasUser(AbstractBaseUser, PermissionsMixin):

sap_id = models.CharField('Número de SAP', max_length=20)

id = models.CharField('Identificador', max_length=10, primary_key=True, unique=True, null=False)

id_type = models.CharField('Tipo de documento', max_length=1,
                           choices=(('V', 'Venezolano'), ('E', 'Extranjero'), ('J', 'Jurídico')))
email = models.EmailField('Correo electrónico', max_length=255, unique=True)
name = models.CharField('Nombre', max_length=30, null=False)
last_name = models.CharField('Apellido', max_length=30, null=False)
failed_login = models.SmallIntegerField('Intentos fallidos', default=0)
needs_sap_modify = models.BooleanField(default=False)
is_active = models.BooleanField('Está activo', default=False)
want_mails = models.BooleanField('Desea reciibir correos de Automercados Plaza\'s', default=False)
created_at = models.DateTimeField(default=timezone.now)

 Class Customer(models.Model):
    user = models.OneToOneField(PlazasUser, primary_key=True)
phone_regex = RegexValidator(regex=r'^\d{4}-\d{7}$',
                             message="El número telefónico debe tener el formato: '0212-1112233'")

phone_number = models.CharField('Número telefónico', max_length=12, validators=[phone_regex])
mobile_number = models.CharField('Teléfono móvil', max_length=12, validators=[phone_regex])
birthday = models.DateField()
is_suma = models.BooleanField('Es cliente suma', default=False)
is_sap = models.BooleanField('Es cliente SAP', default=False)
want_mails = models.BooleanField('Desea reciibir correos de Automercados Plaza\'s', default=False)

objects = CustomerManager()

def __str__(self):
    return'{}'.format(self.user)
  

Now I'm developing the following view and template but the user does not add me as admin:

VIEW:

def admincreate(request):
   if request.method=='POST':
    form=UserContentForm(request.POST)
    if form.is_valid():
        form = Customer.objects.get()
        content_type = ContentType.objects.get_for_model(Customer)
        permission = Permission.objects.create(codename='admin',name='Administrator',content_type=content_type)
        form.user_permissions.add(permission)
        form.is_active = True
        form.save()
    return redirect('admin')
else:
    form=UserContentForm()
return render(request,'admin_create_user_cont.html',{'form':form})

Template:

 <form method="POST" ">
          <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
          <br>
          <h3>Usuario:</h3>


          <div class="col-md-10"> 
                  <center>     {{form.user}}        </center>



         </div>

Forms:

class UserContentForm(forms.ModelForm): 
   class Meta:

    model=Customer

    fields=[
        'user',

    ]   

    labels={
        'user':'user',

          }
    widgets={

        'user':forms.Select(attrs={'class':'form-control'}),

    }   
    
asked by jpozzo 02.08.2017 в 20:25
source

2 answers

0

from terminal python manage.py shell

>>> from django.contrib.auth.models import User
>>> u = User.objects.get(username='john')
>>> u.is_superuser = True
>>> u.save()

or with this command from the terminal django-admin createsuperuser

If you want a route so that anyone can modify it from the web, you could do something like this:

def newSuperUser(request, id):
    user = User.objects.get(id=id)
    if request.method == 'POST':
        is_superuser = request.POST.get('isSuperuser') #name del input en HTML
        user.is_superuser = is_superuser
        user.save()

the variable is_superuser gets the input data type="checkbox"

    
answered by 04.08.2017 / 01:02
source
0

Ready anyway thanks for your help to be able to add the managed user roll just had to change this line of code

permission = Permission.objects.create(codename='admin',name='Administrator',content_type=content_type)

by:

permission = Permission.objects.get(codename='admin',name='Administrator',content_type=content_type)
    
answered by 04.08.2017 в 22:15