Django形式具有多个模型的条件

时间:2017-05-23 16:55:05

标签: django django-models django-forms

我是Django的新手,我已经用这个表格打了一个多星期了。我首先开始这是因为它是我项目的核心。我最终想要的是一个单一的表单,其中包含用户可以设置的条件,在检查单选框时将数据添加到第二个表单(将在jquery中执行此操作)。我想让管理员能够注册用户,但我有一个特殊的用户子类,称为运算符,需要在单独的模型中提供附加信息。我几乎让它现在正常工作,但所有用户都被添加到特殊的子类中。请帮忙!

编辑:什么不起作用我想让管理员在一个可以创建用户的表单上注册用户,如果他们检查了一个按钮,那么填写表单的其余部分运营商。我有第二部分工作(他们可以创建一个运算符),但我也希望他们能够创建一个具有相同形式的常规用户(不使用运算符模型)。可以这样做吗?

这是我的代码。 注意:我在这段代码中搞砸了密码注册,但我稍后会解决。现在就开始研究这个核心功能。

模型

class UserProfile(AbstractUser):
    bio = models.TextField(max_length=500, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    profile_pic = models.ImageField(null=True, blank=True)
    notes = models.TextField(null=True, blank=True)

    def __str__(self):
        return self.first_name + ' ' + self.last_name

class OperatorProfile(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    cdl = models.ManyToManyField('CDL', blank=True)
    endorsement = models.ManyToManyField('Endorsement', blank=True)
    cdl_expiration = models.DateField(blank=True, null=True)

    def __str__(self):
        return str(self.user)

视图

class OperatorCreateView(CreateView):
    model = OperatorProfile
    template_name = 'pages/operatorprofile_form.html'
    form_class = UserCreationMultiForm
    success_url = reverse_lazy('index')

    def form_valid(self, form):
        # Save the user first, because the profile needs a user before it
        # can be saved.

        user = form['user'].save()
        user.groups.add(Group.objects.get(name='Operators'))
        profile = form['profile'].save(commit=False)
        profile.user = user
        profile.save()
        form['profile'].save_m2m()

        return redirect(reverse_lazy('index'))

表单

# Operator Creation Form
class OperatorProfileForm(forms.ModelForm):

    class Meta:
        model = OperatorProfile
        exclude = ['user']


class UserProfileForm(forms.ModelForm):
    first_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
    last_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
    username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
    password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}))
    password_confirm = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}))
    email = forms.CharField(widget=forms.EmailInput(attrs={'class': 'form-control'}))
    bio = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control'}))

    def clean_password2(self):
        password = self.cleaned_data.get('password1')
        password_confirm = self.cleaned_data.get('password2')

        if not password_confirm:
            raise forms.ValidationError("You must confirm your password")
        if password != password_confirm:
            raise forms.ValidationError("Your passwords do not match")
        return password_confirm

    class Meta:
        model = UserProfile
        fields = ['username', 'password', 'password_confirm', 'first_name', 'last_name', 'bio']


class UserCreationMultiForm(MultiModelForm):
    form_classes = {
        'user': UserProfileForm,
        'profile': OperatorProfileForm,
    }

0 个答案:

没有答案