I'm trying to allocate groups permissions in my register form, but I get this error:
Group matching query does not exist.
forms.py:
class RegisterForm(UserCreationForm):
first_name = forms.CharField(max_length=30, required=False)
last_name = forms.CharField(max_length=30, required=False)
Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ]
group_name = forms.ChoiceField(choices=Group)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'group_name', )
views.py:
def registerView(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
user = form.save()
group = Group.objects.get(name='group_name')
user.groups.add(group)
return redirect('accounts:users')
else:
form = RegisterForm()
return render(request, 'accounts/register.html', {'form': form})
The error occurs at group = Group.objects.get(name='group_name'). No idea how to fix it
group = Group.objects.get(name=request.POST.get('group_name'))
or form.cleaned_data['group_name']
as you are taking a input from the form you need to access the field from the form to get the value of that input name.