如何设置表单字段值 - django

don*_*yor 10 forms django

如果没有要显示的内容,我想显示空表单字段,否则显示值为inside的表单字段:

{% if somevalue %}
  {{form.fieldname}} #<---- how do i set the `somevalue` as value of fieldname here?
{% else %}
  {{form.fieldname}}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

Ale*_*kov 16

在你看来,如果它的CBV

class YourView(FormView):
    form_class = YourForm

    def get_initial(self):
        # call super if needed
        return {'fieldname': somevalue}
Run Code Online (Sandbox Code Playgroud)

如果它的通用视图,或不是FormView你可以这样做

form = YourForm(initial={'fieldname': somevalue})
Run Code Online (Sandbox Code Playgroud)


Ale*_*ich 8

有多种方式以django形式提供初始数据.
至少其中一些是:

1)提供初始数据作为字段参数.

class CityForm(forms.Form):
    location = ModelChoiceField(queryset=City.objects.all(), initial='Munchen')
Run Code Online (Sandbox Code Playgroud)

2)在表单的init方法中设置它:

class CityForm(forms.Form):
    location = ModelChoiceField(queryset=City.objects.all())

    def __init__(self, *args, **kwargs):
        super(JobIndexSearchForm, self).__init__(*args, **kwargs)
        self.fields['location'].initial = 'Munchen'
Run Code Online (Sandbox Code Playgroud)

3)在实例化表单时传递具有初始值的字典:

#views.py
form = CityForm(initial={'location': 'Munchen'})
Run Code Online (Sandbox Code Playgroud)

在你的情况下,我想这样的事情会起作用..

class CityForm(forms.Form):
    location = ModelChoiceField(queryset=City.objects.all())

    def __init__(self, *args, **kwargs):
        super(JobIndexSearchForm, self).__init__(*args, **kwargs)
        if City.objects.all().exists():
            self.fields['location'].initial = ''
        else:
            self.field['location'].initial = City.objects.all()[:1]
Run Code Online (Sandbox Code Playgroud)

这一切只是为了演示,你必须适应你的情况.