Django - 如何 运行 连续表格?

Django - How to run consecutive forms?

我有一张用户注册表,要求提供用户信息,还问了一个问题:“您是 PSMC 会员吗?”

选项是:

    rank = [
    ('Supporter', 'Supporter (non-member)'),
    ('Anak', 'Anak'),
    ('Uso', 'Uso'),
    ('Chief', 'Chief'),
]

如果选择Supporter,则注册表会继续并保存用户信息等。这部分工作正常。但是,如果选择了 Anak,我希望它将用户带到另一种询问其他问题的表单。

在我的 forms.py 中,我有 class RegisterForm 这是所有用户的主要注册表格。我还有 class AnakRegisterForm ,这是我希望它继续进行的。我根据从他们网站上读到的内容使用了 Django 的 AuthenticationForm(但我可能是错的)。我知道问题出在 views.py register 函数中。具体来说:

if rank == 'Anak':
   anak_register(response)

在我的调试会话期间,将 response 移动到 anak_register 函数后,它会得到一堆混乱的信息。我很迷茫,任何帮助将不胜感激。这是我的代码:

forms.py

class RegisterForm(UserCreationForm):
    email = forms.EmailField(
        initial='',
        required=True,
        help_text='Please enter a valid email address'
    )

    rank = forms.ChoiceField(
        label='Are you a PSMC member?',
        choices=SavBlock.models.User.rank,
        initial=False,
        required=True,
        help_text='Member accounts will be validated with your HC.'
    )

    class Meta:
        model = User
        # username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
        fields = ['username', 'first_name', 'last_name', 'email',
                  'rank', 'password1', 'password2']

    def save(self, commit=True):
        user = super(RegisterForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.ranking = self.cleaned_data['rank']
        if commit:
            user.save()
        return user


class AnakRegisterForm(AuthenticationForm):
    tribe = forms.ChoiceField(
        label='What tribe are you from, Uce?',
        choices=SavBlock.models.Anak.tribe,
        initial=False,
        required=True,
        help_text='Member accounts will be validated with your HC.'
    )

    class Meta:
        model = Anak
        fields = ['tribe']

    def save(self, commit=True):
        user = super(AnakRegisterForm, self).save(commit=False)
        user.tribe = self.cleaned_data['tribe']
        if commit:
            user.save()
        return user

class UsoRegisterForm(AuthenticationForm):
    pass


class ChiefRegisterForm(AuthenticationForm):
    pass

views.py

def register(response):
    context = {}
    if response.method == "POST":
        form = RegisterForm(response.POST)
        if form.is_valid():
            form.save()
            rank = form.cleaned_data.get('rank')
            if rank == 'Anak':
                anak_register(response)
            else:
                form.save()
            messages.success(response, 'Registration successful. Please login.')
            return redirect('login')
        else:
            context['register'] = form
    else:
        form = RegisterForm()
        context['register'] = form

    return render(request=response, template_name='register/register.html', context={'form': form})


def anak_register(response):
    # context = {}
    if response.method == "POST":
        form = AnakRegisterForm(response.POST)
        if form.request.is_valid():
            form.save()
            messages.success(response, 'Registration successful. Please login.')
            return redirect('login')
        else:
            '''
            context['register'] = form
            '''
    else:
        form = AnakRegisterForm()
        # context['register'] = form
        # messages.error(request, 'Unsuccessful registration. Invalid information.')
    # form = RegisterForm

    return render(request=response, template_name='register/register.html', context={'form': form})

models.py

class User(AbstractBaseUser, PermissionsMixin):

    rank = [
        ('Supporter', 'Supporter (non-member)'),
        ('Anak', 'Anak'),
        ('Uso', 'Uso'),
        ('Chief', 'Chief'),
    ]

    tribe = [
        ('NaKoaHema', 'Na Koa Hema'),
        ('Alakai', 'Alaka\'i')
    ]

    username = models.CharField("user name", max_length=50, default='', unique=True)
    email = models.EmailField("email address", max_length=30, unique=True, blank=True)
    first_name = models.CharField("first name", max_length=50)
    last_name = models.CharField("last name", max_length=50)
    is_active = models.BooleanField('active', default=True)
    # password = models.CharField("password", unique=True, max_length=32, default='')
    id = models.AutoField(primary_key=True)
    is_staff = models.BooleanField('staff status', default=False)
    date_joined = models.DateField('date_joined', default=timezone.now)
    ranking = models.CharField(choices=rank, max_length=50, default="Supporter")

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email', 'password', 'ranking']


    # Magic method returns string of self
    def __str__(self):
        return f"User {self.first_name} {self.last_name} rank {self.rank}".strip()

    @property
    def get_full_name(self):
        return f"{self.first_name} {self.last_name}".strip()


class Anak(User):
    def __init__(self, first_name, last_name, tribe):
        super().__init__(first_name, last_name)
        self.tribe = tribe.title()
        self.rank = User.rank[1]

编辑

我将 AuthenticationForm 更改为 UserCreationForm,现在它接受表单。但是,当我尝试 运行 它时,出现以下错误:

TypeError at /register/
__init__() missing 1 required positional argument: 'tribe'

如果有人能指出正确的方向,我将不胜感激!

不确定我是怎么错过这个的,但我找到的最佳解决方案是实施 Django 表单向导。可以在这里找到更多信息:

https://django-formtools.readthedocs.io/en/latest/wizard.html