Django:提交表单(POST)后在表单上设置初始名称

时间:2019-07-03 18:06:08

标签: django django-forms django-views

 class MyView(FormView):
             # get works
         def post(self, request, *args, **kwargs):
                field1 = self.kwargs.get('field1', None)
                if(not field1):
                    field1 = request.POST['field1']  # field1 exists in the URL, and also as an input on the form
                    field2 = 'Test2'
                    field3 = 'Test3'

                initial={'field1': field1, 'field2': field2, 'field3': field3}

                # Not bound, but data does not get set
                input_form = MyForm()
                print(form.is_bound) # False
                form.initial = initial # does not work!

                form2 = MyForm(initial, initial = initial)
                # Also tried 
                # form2 = MyForm(request.POST, initial = initial, initial) with same results
                print(form2.is_bound) # True
                print(form2.has_changed()) # true 
                print(form2.changed_data) # field2, field3 - not set 
                return render(
                    self.request,
                    'template.html',
                    context = {
                        'form': form # form2
                    }
                )

表格:

class MyForm(forms.ModelForm):
    class Meta:
        model = models.MyModel


        initial_fields = [
            'field1',
            'field2',
            'field3'
        ]

        fields = [
            'field1',
            'field2',
            'field3'
        ]

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super().clean()
        return cleaned_data

模板: 什么都没用-ckeaned_data在get请求中设置的URL中只有args。

{{form.cleaned_data}}
{{form.field2.value }}
{{ form.field3 }}
{% if form.field3.value %}
<div class="row">
    <div class="col-md-12">
        <h5> Field3: </h5> {{form.field3.value}}
    </div>
</div>
{% endif %}

0 个答案:

没有答案