Django Bounded forms in Class based views - CreateView class

六眼飞鱼酱① 提交于 2020-02-08 02:46:25

问题


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).

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

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)) 

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


回答1:


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

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.

Edit

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


来源:https://stackoverflow.com/questions/30241157/django-bounded-forms-in-class-based-views-createview-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!