关于这一点有很多主题,但我无法让它发挥作用。 检查多个帖子后,我创建了一个init方法,但我仍然得到了 电子邮件未在locations = modelform中定义。
查看:
form = GroupCreateForm(request.POST or None, user=request.user)
Forms.py:
class GroupCreateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(GroupCreateForm, self).__init__(*args, **kwargs)
def clean_email_address(self):
email = self.cleaned_data.get('email')
if self.user and self.user.email == email:
return email
locations = forms.ModelMultipleChoiceField(label='',widget=forms.CheckboxSelectMultiple(attrs={'class': 'form-control'}), queryset=LocationData.objects.filter(email=email))
groupname = forms.CharField(label='', required=True ,widget=forms.TextInput(attrs={'rows': '1', 'class': 'form-control', 'placeholder': 'Geben Sie den Gruppen Namen an'}))
class Meta:
model = GroupManagement
fields = ['groupname', 'locations']
答案 0 :(得分:2)
解决这个问题:
Forms.py:
class GroupCreateForm(forms.ModelForm):
locations = forms.ModelMultipleChoiceField(label='',widget=forms.CheckboxSelectMultiple(attrs={'class': 'form-control'}), queryset=None)
groupname = forms.CharField(label='', required=True ,widget=forms.TextInput(attrs={'rows': '1', 'class': 'form-control', 'placeholder': 'Geben Sie den Gruppen Namen an'}))
def __init__(self, user, *args, **kwargs):
super(GroupCreateForm, self).__init__(*args, **kwargs)
self.fields['locations'].queryset = LocationData.objects.all().filter(email=user.email)
class Meta:
model = GroupManagement
fields = ['groupname', 'locations']
Views.py:
form = GroupCreateForm(data=request.POST, user=request.user)
if request.method == 'POST':
if form.is_valid():
mulitple_choice = form.cleaned_data['locations']
print(mulitple_choice)