UpdateView不使用现有数据填充表单

时间:2019-01-13 02:50:27

标签: python django

因此,我已将UpdateView设置为向表单发送request对象,以便可以修改表单中的查询集(基于request.user

我的views.py:

class DataSourceUpdateView(UpdateView):
    model = DataSource
    form_class = DataSourceForm
    template_name = 'engine/datasource_update.html'

    def get(self, request, *args, **kwargs):

        obj = DataSource.objects.get(pk=kwargs['pk'])
        self.object = None
        form = DataSourceForm(request)
        return self.render_to_response(
            self.get_context_data(form=form,
                                  object=obj))

    def post(self, request, *args, **kwargs):

        form = DataSourceForm(request, request.POST, request.FILES)

        if form.is_valid:
            return self.form_valid(form)
        else:
            return self.form_invalid(form)  

我的表格.py:

class DataSourceForm(forms.ModelForm):

    def __init__(self, request, *args, **kwargs):
        self.request = request
        super(DataSourceForm, self).__init__(*args, **kwargs)  
        self.fields['dataset_request'].queryset = DatasetRequest.objects.filter(
            creator=self.request.user)

    class Meta:
        model = DataSource
        exclude = ('creator', 'vote_score', 'num_vote_up',
                   'num_vote_down', 'file_size', 'slug')

我的问题是,在模板中,表单未填充现有值。我该如何解决?

1 个答案:

答案 0 :(得分:1)

使用thread_instance = None有点棘手。因此,为了初始化表单的数据,您需要在视图本身而不是表单中进行操作。

因此,在使用UpdateView时,您可以执行以下操作:

UpdateView

您的表格将是:

class DataSourceUpdateView(UpdateView):
    model = DataSource
    form_class = DataSourceForm
    template_name = 'engine/datasource_update.html'
    # An empty dict or add an initial data to your form
    initial = {}
    # And don't forget your success URL
    # or use reverse_lazy by URL's name
    # Or better, override get_success_url() method
    # And return your success URL using reverse_lazy
    sucess_url = '/' 

    def get_initial(self):
        """initialize your's form values here"""

        base_initial = super().get_initial()
        # So here you're initiazing you're form's data
        base_initial['dataset_request'] = DatasetRequest.objects.filter(
            creator=self.request.user
        )
        return base_initial

        #... The rest of your view logic

奖金:

为了理解为什么需要初始化表单的数据,需要查看`UpdateView的MRO,它们为Visit this documentation link

  • ...
  • django.views.generic.edit.FormMixin #=>这个正在处理表单
  • ...

class DataSourceForm(forms.ModelForm): class Meta: model = DataSource exclude = ( 'creator', 'vote_score', 'num_vote_up', 'num_vote_down', 'file_size', 'slug' ) 具有以下属性和方法visit the documentation link

  • 初始:包含表单初始数据的字典。 ...
  • get_initial():检索表单的初始数据。默认情况下,返回缩写的副本。

我也建议您查看FormMixin具有相似的属性和方法,以了解如何覆盖它们或让Django为您做魔术:D。看到这个documentation link