如何在FormMixin中添加两个form_class?

时间:2016-12-16 10:58:00

标签: python django django-forms django-views django-generic-views

所以我已经完成了我的register()表格,工作正常。我现在正在尝试使用login()表单,但是字段(usernamepassword)没有显示,因为我无法向form_class添加2个值在BoxesView()。 form_class中已有一个值为寄存器表单,所以我需要添加另一个。说实话,我不完全确定form_class在这里是如何工作的,或者如果可以添加另一个,那么如果有人可以解释这将是伟大的。这是我的代码:

views.py

class BoxesView(ListView, FormMixin):
    template_name = 'polls.html'  # extends base.html
    form_class = UserRegistrationForm

    def get_context_data(self, **kwargs):
        context = super(BoxesView, self).get_context_data()

        question_list = Question.objects.all().order_by('-date')
        choice = Choice.objects.all()
        context['question_list'] = question_list
        context['choice'] = choice

        q_list = []
        returned_list = []

        for i in question_list:
            q_list.append(i)

        for a, b in CATEGORY_CHOICES:
            name = resolve(self.request.path_info).url_name
            if b == name:
                category = a

        search = self.request.GET.get('search')
        posts = Post.objects.all().filter(category=category).order_by('-date')
        if search:
            posts = posts.filter(
                Q(title__icontains=search) |
                Q(content__icontains=search)
            )
        else:
            posts = Post.objects.all().filter(category=category).order_by('-date')

        context['posts'] = posts

        total = 0
        for post in posts:
            returned_list.append(post)
            total += 1
            if total == 4:
                total = 0
                for i in q_list:
                    returned_list.append(i)
                    q_list.remove(i)
                    break

        paginator = Paginator(returned_list, 14)
        page = self.request.GET.get('page')

        try:
            lst = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            lst = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            lst = paginator.page(paginator.num_pages)

        context['lst'] = lst

        return context

    def get_queryset(self):
        pass


def register(request):
    form = UserRegistrationForm(request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        email = form.cleaned_data['email']
        user = User.objects.create_user(username=username, password=password, email=email)
        user.save()
        return redirect('/')
    else:
        form = UserRegistrationForm()
    return redirect('/')


def user_login(request):
    form_login = UserLoginForm(request.POST)
    if form_login.is_valid():
        username = form_login.cleaned_data['username']
        password = form_login.cleaned_data['password']
        user = authenticate(username=username, password=password)
        login(request, user)
    else:
        form_login = UserLoginForm()
    return redirect('/')

forms.py

class UserLoginForm(forms.ModelForm):
    username = forms.CharField(max_length=25)
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User

        fields = [
            'username',
            'password'
        ]


class UserRegistrationForm(forms.ModelForm):
    email = forms.EmailField()
    username = forms.CharField(max_length=25)
    password = forms.CharField(widget=forms.PasswordInput)
    confirm_password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User

        fields = [
            'username',
            'email',
            'password',
            'confirm_password',
        ]

base.html文件

<form method="post" enctype="multipart/form-data" action="{% url 'user_login' %}">{% csrf_token %}
<div class="loginWrapper">
<div class="login">
    <div class="loginBox">
        {{ form_login.username }}
        {{ form_login.password }}
        <input type="submit" value="login" style="margin-left: 10px"/>
    </div>
</div>
</div>
</form>

<form method="post" enctype="multipart/form-data" action="{% url 'register' %}">{% csrf_token %}
<div class="registerWrapper">
<div class="register">
    <div class="registerBox">
        {{ form.errors }}
        {{ form.username|placeholder:"username" }}
        {{ form.email|placeholder:"email" }}
        {{ form.password|placeholder:"password" }}
        {{ form.confirm_password|placeholder:"confirm password" }}
        <input type="submit" value="register" />

    </div>
</div>
    </div>
</form>

1 个答案:

答案 0 :(得分:1)

如果您想知道FormMixin如何使用form_class,您只需阅读代码 - 嘿,这是您知道的开源。

因此,如果您检查FormMixin的代码here,就会发现form_class - 惊喜 - 用于实现您的表单。

现在wrt /你的问题,你主要有两个选择:

  1. 沟渠FormMixin(不是为处理多种形式而设计)并在您的View类中实现您需要的东西
  2. 彻底抛弃基于类的视图并编写一个好的旧视图函数
  3. 不要误会我的意思:基于类的视图适用于很多东西,但有时基于函数的简单视图只是方式更易于编写,读取和维护。