获取与使用ModelMultipleChoiceField时添加的对象相关的所有对象

时间:2019-01-22 18:16:52

标签: django django-models django-forms

我正在尝试创建一个注册表单,用户可以从列表中指定许多类别和语言,但是当我从列表中选择一个或两个对象进行注册时,我发现新用户与所有对象。就像我检查了所有对象一样。

forms.py

class SignUpForm(UserCreationForm, ModelForm): 
    categories=forms.ModelMultipleChoiceField(queryset=Category.objects.all(),
                     widget=forms.CheckboxSelectMultiple(), required=True)
    languages = forms.ModelMultipleChoiceField(queryset=Language.objects.all(), 
                     widget=forms.CheckboxSelectMultiple(), required=True) 

    class Meta:
        model = User
        fields = ['username', 'email','categories', 'languages']

models.py

class User(AbstractUser, models.Model):
    password1 = models.CharField(max_length=50)
    categories = models.ManyToManyField('Category')
    languages = models.ManyToManyField('Language')

    def __str__(self):
        return self.username

class Category(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name


class Language(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

views.py

class SignUp(CreateView):
    form_class = SignUpForm
    success_url = reverse_lazy('index')
    template_name = 'registration/signup.html'

0 个答案:

没有答案