Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
Use multiple models in a single django form

I have a django application and for a particular form,the data comes from different models with one common field(id) across all models.Instead of using multiple forms and same id for all forms,I want to use a single form to take data from multiple models.How can this be done?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

  1. Specify your form as provided in the django docs: https://docs.djangoproject.com/en/1.10/topics/forms/#building-a-form-in-django
  2. Specify the view e.g.

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. Handle the form in the template as you normally would.
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda