Search code examples
djangodjango-formsdjango-permissions

Set the groups in Django template


I want to register users by using template, i want also, in the moment of registration, set the group(default groups permission provided by Django) of every new user created, I set the group of user in the template but when i look to the group of user in the database i I found it empty.

class ProfileUserManager(BaseUserManager):

def create_user(self, username, password,**extra_fields):

    user = self.model(username=username, **extra_fields)
    user.set_password(password)
    user.save()
    return user

def create_superuser(self, username, password,**extra_fields):

    extra_fields.setdefault('is_staff', True)
    extra_fields.setdefault('is_superuser', True)
    extra_fields.setdefault('is_active', True)

    if extra_fields.get('is_staff') is not True:
         raise ValueError(_('Superuser must have is_staff=True.'))
    if extra_fields.get('is_superuser') is not True:
        raise ValueError(_('Superuser must have is_superuser=True.'))
    return self.create_user(username,password,**extra_fields)

class ProfileUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
username = models.CharField(max_length=255,unique=True)
first_name=models.CharField(max_length=255)
last_name= models.CharField(max_length=255)
departement= models.CharField(max_length=255)


USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []

objects = ProfileUserManager()


def __str__(self):
    return self.username

forms.py

class FormAddAccount(UserCreationForm):

class Meta(UserCreationForm.Meta):
    model = get_user_model()
    fields = ('email', 'password1', 'password2', 'is_staff','username','groups','first_name','last_name','departement')

Solution

  • I just add some lines of code to Views.py when i add a user:

    def createView(request):
    form=FormAddAccount()
    if request.method=="POST":
        form=FormAddAccount(request.POST)
        if form.is_valid():
            user=form.save()
            for element in form.cleaned_data["groups"] :
                group = Group.objects.get(name=element)
                user.groups.add(group)
            user.save()
            redirect("accounts/list.html")
    context={
        'form':form
    }
    
    return render(request,"accounts/addaccount.html",context)