【问题标题】:Prepopulating dynamically added formsets in edit view在编辑视图中预填充动态添加的表单集
【发布时间】:2013-01-09 10:51:24
【问题描述】:

我的应用中有不同的模型,主模型有多个其他模型的实例。

models.py:

class Person(models.Model):
    ...

class Pet(models.Model):
    owner = models.ForeignKey(Person)
    ...

forms.py:

class PersonForm(forms.ModelForm):
    class Meta:
        model = Person


PetFormSet = inlineformset_factory(Person, Pet, extra = 1)

views.py:

def add_template(request):
    person_form = PersonForm(prefix = 'person_form')
    pet_form = PetFormSet(instance = Person(), prefix = 'pet_form')
    ... # check is_valid(), render when no POST data is present, etc.

重点是添加完美,将每个实例存储在相应的数据库表中等。我使用jquery.formset-1.2.js来管理“add.html”中表单的动态添加-删除。

但是我稍后想通过视图编辑存储的信息,即从我在请求中传递的对象中加载数据,并使用从数据库中获取的数据渲染表单集(如果有3只宠物与正在编辑的人,显示“宠物”的 3 个表单实例并显示它们的值)。

我还想添加新宠物并删除现有宠物,以及更改现有字段值。

我已经尝试在 FormSet 创建中使用查询集,但它没有显示任何内容。

知道如何缓解这个问题吗?也许使用应用程序来更轻松地管理表单集?

谢谢

【问题讨论】:

    标签: django django-forms formsets


    【解决方案1】:

    我不确定我是否正确理解了您的问题。如果要显示属于Person的所有Pets

    def show_pets(request, person_id=None):
    person = get_object_or_404(Person.objects.select_related(), id=person_id)
    if request.method == 'POST':
       person_form = PersonForm(request.POST, instance=person)
       pet_formset = PetFormSet(request.POST, instance=person)
       # Rest of your code here
    else:
       person_form = PersonForm(instance=person)
       pet_formset = PetFormSet(instance=person)
    return render_to_response('your_template.html', {'person_form': person_form,
                                                            'pet_formset': pet_formset)})
    

    然后你只需要在你的模板中渲染两个表单并添加adddelete功能

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-15
      • 1970-01-01
      • 2015-08-26
      • 1970-01-01
      • 2020-05-19
      • 2022-10-08
      • 1970-01-01
      • 2016-02-05
      相关资源
      最近更新 更多