在单个django表单中使用多个模型

时间:2017-04-21 07:00:19

标签: django django-models django-forms

我有一个django应用程序,对于一个特定的表单,数据来自不同的模型,所有模型都有一个公共字段(id)。而不是为所有表单使用多个表单和相同的id,我想使用单个表单从多个模型中获取数据。如何做到这一点?

1 个答案:

答案 0 :(得分:1)

  1. 指定django文档中提供的表单:https://docs.djangoproject.com/en/1.10/topics/forms/#building-a-form-in-django
  2. 指定视图,例如
  3. view.py

    def get_name(request):
        id = request.kwargs['id']  # Get the id from url or however you want to get the id
        item = Item.objects.get(name_id=id)
        item2 = Item2.objects.get(name_id=id)
    
        # if this is a POST request we need to process the form data
        if request.method == 'POST':
            # create a form instance and populate it with data from the request:
            form = NameForm(request.POST)
    
            # check whether it's valid:
            if form.is_valid():
                # process the data in form.cleaned_data as required
                 # ... e.g.
                item.name = form.cleaned_data['name']
                item2.name = form.cleaned_data['name2']
                item.save()
                item2.save()
                # redirect to a new URL:
                 return HttpResponseRedirect('/thanks/')
    
            # if a GET (or any other method) we'll create a blank form
        else:
            # This is for updating the "name" objects            
            form = NameForm(initial={'name': item.name, 'name2': item2.name})
            # for creating: (but I guess you don't need creating)
            # form = NameForm()
    
        return render(request, 'name.html', {'form': form})
    
    1. 像往常一样处理模板中的表单。