UpdateView不使用现有数据填充表单 [英] UpdateView not populating form with existing data

查看:164
本文介绍了UpdateView不使用现有数据填充表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have my UpdateView set up to send a request object to the form so I can modify a queryset in the form (based on request.user)

我的views.py:

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

我的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')

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

My problem is, in the template, the form is not populated with existing values. How can I fix this?

推荐答案

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

With UpdateView it's a little bit tricky. So, in order to initialize your form's data, you need to do it in the view itself not in the form.

所以这是您可以执行的操作在使用 UpdateView 时完成的:

So here is how you can perform what's you've done when using 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

您的表单将是:

class DataSourceForm(forms.ModelForm):

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

奖金:

为了理解为什么需要初始化表单数据,需要来查看访问的 UpdateView的MRO此文档链接

In order to understand why you need to initialize the form's data, you need to see the `UpdateView's MRO which are Visit this documentation link:


  • ...

  • django.views .generic.edit.FormMixin #=> e正在处理以下形式

  • ...

  • ...
  • django.views.generic.edit.FormMixin # => This one is dealing with the form
  • ...

FormMixin 具有以下属性和方法访问文档链接

And the FormMixin have these attributes and methods visit the documentation link which are:


  • 初始:包含以下内容的字典表格的初始数据。
    ...

  • get_initial():检索表单的初始数据。默认情况下,返回首字母的副本。

  • initial: A dictionary containing initial data for the form. ...
  • get_initial(): Retrieve initial data for the form. By default, returns a copy of initial.

我也建议您查看 FormMixin 具有相似的属性和方法,以了解如何覆盖它们或让Django为您做魔术:D。请参见此文档链接

Also i recommend you to see what the FormMixin have like attributes and methods in order to see how you can override them or let Django do magics for you :D. See this documentation link

这篇关于UpdateView不使用现有数据填充表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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