Django:如何为 FormView 提供上下文? [英] Django: How to provide context for a FormView?

查看:41
本文介绍了Django:如何为 FormView 提供上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新手问题:我有一个 FormView,它显示一个注册表单,使用 Django 的验证等.一切正常,但是,我似乎无法弄清楚如何向模板提供任何数据(上下文).目前,我有:

Newbie Question: I have a FormView which displays a sign-up form, using Django's validations, etc. It all works fine, however, I can't seem to work out how to provide any data (context) to the template. Currently, I have:

from django.shortcuts import render
from django.shortcuts import redirect
from django.http import HttpResponse
from accounts.forms import SignUpForm

class SignUpView(FormView):
    template_name = 'accounts/signup.html'
    form_class = SignUpForm 

    def form_valid(self, form):
        # executes when form validates..
        (...)
        return redirect('/account/')

我尝试通过下面的 get() 添加一些上下文数据,当页面第一次显示时我需要这些数据,哪种工作 除了表单的输入字段不见了(标签都在那里):

I tried adding some context data via get() per below, which I need when the page first displays, which sort of works except the input fields of the form are gone (the labels are all there):

def get(self, request):
    return render(self.request, self.template_name, {'data': data })

有人可以澄清为什么会这样,以及如何让它工作吗?换句话说:当使用 FormView 和 form_valid() 时,我应该将用于初始 GET 请求的代码放在哪里?

Could someone please clarify why that is, and how to get it to work? To put it another way: When using FormView with form_valid(), where do I place code intended for the initial GET request?

推荐答案

你必须有方法去做,如果数据只与那个获取视图相关,那么你可以继续:

You have to methods of doing it, if the data is related only to that get view then you can move on:

def get_context_data(self, **kwargs):
    context = super(SignUpView, self).get_context_data(**kwargs)
    something = something
    context['something'] = something
    return context

或者使用 Mixin:

Or use a Mixin:

class SomeMixin(object):

    def get_context_data(self, **kwargs):
        context = super(SomeMixin, self).get_context_data(**kwargs)
        something = something
        context['something'] = something
        return context

然后:

class SignUpView(SomeMixin, FormView):

    def form_valid(self, form):
        ...

这篇关于Django:如何为 FormView 提供上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆