【发布时间】:2020-12-09 10:30:13
【问题描述】:
我有一个 Django 项目,其中每个用户只属于一个组,医生和护士,但不属于两者。
我在前端显示了一个表单,让管理员用户添加用户配置文件,其中每个用户配置文件都由名字、姓氏、电子邮件、组等组成。
我的挑战是当管理员用户从前端将用户配置文件分配给组时,当我检查 Django 管理员时,该用户未添加到组中,即当我单击 Django 管理员上的用户时,我看不到被分配到组的用户。
我的 forms.py 的重要部分是这部分
from django.contrib.auth.models import Group
groups = forms.ModelChoiceField(label='Role', queryset=Group.objects.all(), widget=forms.Select(attrs={'class':'form-control'}))
完整的表格可以在这里看到
from django.contrib.auth.forms import UserCreationForm
from django_starter_app.models import User, Post
from django.contrib.auth.models import Group
class RegisterForm(UserCreationForm):
username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter Username'}))
email = forms.CharField(widget=forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Email'}))
first_name = forms.CharField(label='Firstname', widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Firstname'}))
last_name = forms.CharField(label='Lastname', widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Lastname'}))
groups = forms.ModelChoiceField(label='Role', queryset=Group.objects.all(), widget=forms.Select(attrs={'class':'form-control'}))
password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Password'}))
password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Confirm Password'}))
class Meta():
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'groups', 'password1', 'password2')
def save(self, commit=True):
user = super().save(commit=False)
user.username = self.cleaned_data['username']
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.groups = self.cleaned_data['groups']
user.password1 = self.cleaned_data['password1']
user.password2 = self.cleaned_data['password2']
if commit:
user.save()
return user
我的观点
def register_user(request):
if request.method == 'POST':
reg = RegisterForm(request.POST)
if reg.is_valid():
reg.save()
role= reg.cleaned_data.get('groups')
if role== 1:
doctor_group = Group.objects.get(name='Doctor')
reg.groups.add(doctor_group)
return redirect('register_user')
elif role == 2:
nurse_group = Group.objects.get(name='Nurse')
reg.groups.add(nurse_group)
return redirect('register_user')
else:
reg = RegisterForm()
return render(request, 'django_starter_app/register.html', {'register':reg})
我想知道我在哪里弄错了我怀疑我在哪里进行检查
if role == 1:
doctor_group = Group.objects.get(name='Doctor')
reg.groups.add(doctor_group)
return redirect('register_user')
elif role == 2:
nurse_group = Group.objects.get(name='Nurse')
reg.groups.add(nurse_group)
return redirect('register_user')
【问题讨论】:
-
更改代码后出现错误
Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead.
标签: django django-forms