基于类的视图中的Django绑定窗体-CreateView类 [英] Django Bounded forms in Class based views - CreateView class

查看:95
本文介绍了基于类的视图中的Django绑定窗体-CreateView类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在基于类的视图中,如何覆盖 GET 方法,以生成边界,这意味着在生成的表单中,该字段的某些字段将具有一个预设值(我需要使用一些默认值实例化该表单,并且不使用CreateView默认使用的空白版本的表单) 。

How would I go about overriding the GET method in CreateView class based views to generate a bounded form, by which I mean it would have a preset value for some of its fields in the generated form (I need to instantiate the form with some defaults and not use the blank version of the form that CreateView uses by default).

我尝试查看 https://ccbv.co.uk/projects/Django/1.6/django.views.generic.edit/CreateView/ ,但是不太了解此类中的GET 方法。

I tried looking at https://ccbv.co.uk/projects/Django/1.6/django.views.generic.edit/CreateView/ but dont quite understand the flow of the GET method in this class.

BaseCreateView

def get(self, request, *args, **kwargs):
    self.object = None
    return super(BaseCreateView, self).get(request, *args, **kwargs)

ProcessFormView


处理GET请求并实例化表单的空白版本。

Handles GET requests and instantiates a blank version of the form.



def get(self, request, *args, **kwargs):
    """
    Handles GET requests and instantiates a blank version of the form.
    """
    form_class = self.get_form_class()
    form = self.get_form(form_class)
    return self.render_to_response(self.get_context_data(form=form)) 

我到底在哪里覆盖获取以实例化我的表单,因为CreateView使用modelFormFactory生成空表单。

Where exactly do I override the get to instantiate my form, since CreateView uses modelFormFactory to generate the empty form.

推荐答案

这不是绑定表单:绑定表单就是

This is not a bound form: a bound form is one that's created from POST data and undergoes form validation.

要为新表单提供初始数据,请覆盖 get_initial 方法。或者,如果该数据是静态的,则可以只提供类级别的 initial 字典。

To provide initial data for a new form, you override the get_initial method. Or you can just provide a class-level initial dictionary, if that data is static.

编辑

def get_initial(self):
    if request.GET.get('codereview-get'):
        initial = {'stream_name': 'TROI'}
    else:
        initial = {}
    return initial

这篇关于基于类的视图中的Django绑定窗体-CreateView类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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