简体   繁体   中英

Django having problem in adding user to specific group

forms.py

class UserForm(UserCreationForm):
    email = forms.EmailField(required=True)

class Meta:
    model = User
    fields = ('username','email','password1','password2')

def save(self,commit=True):
    user = super(UserForm,self).save(commit=False)
    user.set_password = self.cleaned_data['password1']
    user.email = self.cleaned_data['email']
    
    if commit:
        user.save()

views.py

def register_view(request):
    form = UserForm()
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            user = form.save()

            customer_group = Group.objects.filter(name='CUSTOMER').exists()
            if customer_group:
                Group.objects.get(name='CUSTOMER').user_set.add(user)
            else:
                Group.objects.create(name='CUSTOMER')
                Group.objects.get(name='CUSTOMER').user_set.add(user)
          
            messages.success(request,'註冊成功! 請按指示登入!')
            return redirect('login')
        else:
            messages.error(request,'註冊無效! 請再試過!')
    context = {'form':form}
    return render(request,'customer/register.html',context)

When I try to register a new user, the form can be successfully saved and the group CUSTOMER can be added but I have a problem if I want to add that user to the group so are there any methods in order to add the user to the group automatically after that user had registered a new account along with the User model?

As @Iain Shelvington says , the form.save() method should return the user object. But there is no need to override the save() method: the UserCreationForm already does that.

class UserForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ('username','email')

    # no save method

In the view you can simplify the logic to:

def register_view(request):
    form = UserForm()
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            user = form.save()
            customer_group, __ = Group.objects.get_or_create(name='CUSTOMER')
            customer_group.user_set.add(user)
          
            messages.success(request,'註冊成功! 請按指示登入!')
            return redirect('login')
        else:
            messages.error(request,'註冊無效! 請再試過!')
    context = {'form':form}
    return render(request,'customer/register.html',context)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM