Django multiple forms for different models


Simon

I'm new to Django, but I've been stuck with it because I haven't been able to solve my problem for a day.

I have to create a form with a lot of fields. The fields are from different models and I want to save them all at once. I want to display it in a slick way so that the user experience will be better and not overwhelmed by a lot of populated fields. The smooth part is not a problem. My problem is rendering multiple forms in multiple divs on the same page. In this case I want to display not only the candidate details but also the candidate details form.

Here my actual code only works for one valid form.

form:

class CandidateApplicationForm(ModelForm):
position = forms.ChoiceField(choices=POSITION, widget=forms.RadioSelect)

class Meta:
    model = Candidate
    fields = ['firstName',
              'lastName',
              'mailAddress',
              'address',
              'city',
              'country',
              'nationality',
              'position',
              ]
    widgets = {
        'firstName': forms.TextInput(attrs={'class': 'input'}),
        'lastName': forms.TextInput(attrs={'class': 'input'}),
        'address': forms.TextInput(attrs={'class': 'input'}),
        'city': forms.TextInput(attrs={'class': 'input'}),
        'nationality': forms.TextInput(attrs={'class': 'input'}),
        'Type of programme': forms.TextInput(attrs={'class': 'input'}),
    }

CandidateDetailsForm(ModelForm)类:

class Meta:
    model = CandidatesDetail
    fields = ['birthPlace',
              'birthDate',
              'nationality',
             ]

View:

类RegisterCandidate:

def __init__(self):
    self.method = None

def candidateapply(request):

    apply = candidateregistrationform.CandidateApplicationForm()

    if request.method == 'POST':
        form_candidate = candidateregistrationform.CandidateApplicationForm(request.POST)
        if form_candidate.is_valid():

            candidate = form_candidate.save(commit=False)
            candidate.save()

        else:
            apply = candidateregistrationform.CandidateApplicationForm()
    return render(request,
                  'candidateapplication.html',
                  {'form': apply})


def candidatedetails(request):
    apply = candidateregistrationform.CandidateDetailsForm()

    if request.method == 'POST':
        form_candidatedetails = candidateregistrationform.CandidateDetailsForm(request.POST)
        if form_candidatedetails.is_valid():

            candidate = form_candidatedetails.save(commit=False)
            candidate.save()

        else:
            apply = candidateregistrationform.CandidateApplicationForm()
    return render(request,
                  'candidateapplication.html',
                  {'form': apply})

Japanese HTML:

{% csrf_token %}
  {% for field in form %}
  <p>
    {{ field.label_tag }}<br>
    {{ field }}
    {% for error in field.errors %}
      <p style="color: red">{{ error }}</p>
    {% endfor %}

  {% endfor %}

thank you for your help.

Alexis Dubniak

Like dirkgroten said, yep creates a single-view function with two forms:

def candidatedetails(request):
    candidate_application_form = candidateregistrationform.CandidateApplicationForm()
    candidate_details_form = candidateregistrationform.CandidateDetailsForm()

    ...

    return render(request,
                  'candidateapplication.html',
                  {'candidate_application_form': candidate_application_form, 
                    'candidate_details_form', candidate_details_form})

Now you will be able to render these forms or specific fields

{{ candidate_application_form }}

Related


Django multiple forms for different models

Simon I'm new to Django, but I've been stuck with it because I haven't been able to solve my problem for a day. I have to create a form with a lot of fields. The fields are from different models and I want to save them all at once. I want to display it in a sl

Django multiple forms for different models

Simon I'm new to Django, but I've been stuck with it because I haven't been able to solve my problem for a day. I have to create a form with a lot of fields. The fields are from different models and I want to save them all at once. I want to display it in a sl

Django multiple forms for different models

Simon I'm new to Django, but I've been stuck with it because I haven't been able to solve my problem for a day. I have to create a form with a lot of fields. The fields are from different models and I want to save them all at once. I want to display it in a sl

Django multiple forms for different models

Simon I'm new to Django, but I've been stuck with it because I haven't been able to solve my problem for a day. I have to create a form with a lot of fields. The fields are from different models and I want to save them all at once. I want to display it in a sl

Django - Handling multiple nested models at different levels

CH Andre Meloa I have some questions about Django nested models. As far as I know, to handle nested data structures, I have to deserialize each data and then create objects that will be concatenated with the ForeignKeyField. I can handle this by overriding the

Django - Handling multiple nested models at different levels

CH Andre Meloa I have some questions about Django nested models. As far as I know, to handle nested data structures, I have to deserialize each data and then create objects that will be concatenated with the ForeignKeyField. I can handle this by overriding the

Django - Handling multiple nested models at different levels

CH Andre Meloa I have some questions about Django nested models. As far as I know, to handle nested data structures, I have to deserialize each data and then create objects that will be concatenated with the ForeignKeyField. I can handle this by overriding the

Django - Handling multiple nested models at different levels

CH Andre Meloa I have some questions about Django nested models. As far as I know, to handle nested data structures, I have to deserialize each data and then create objects that will be concatenated with the ForeignKeyField. I can handle this by overriding the

Django forms without models

Lilia I want to upload image from form without model. I tried doing: In the template: det.html Upload image <form enctype="multipart/form-data" action="" method="post">{% csrf_token %} <input type="file" name="myfile" id="myfile" /> <input

Create separate forms for models belonging to different models?

Graham S. So I have two models Roomand Reservation. The Roomobject is pre-created by the person who owns the room and is stored in the database. I want to allow other users to later create reservations in that room that belong to this room (on a different page

Create separate forms for models belonging to different models?

Graham S. So I have two models Roomand Reservation. The Roomobject is pre-created by the person who owns the room and is stored in the database. I want to allow other users to later create reservations in that room that belong to this room (on a different page

Create separate forms for models belonging to different models?

Graham S. So I have two models Roomand Reservation. The Roomobject is pre-created by the person who owns the room and is stored in the database. I want to allow other users to later create reservations in that room that belong to this room (on a different page

Multiple new forms of models - Rails

Fool I have two models. Products and product prices (with table products and product prices), each product has a price. I want to create a form for both models, but after copying the solution to a similar situation, my form still doesn't show the price field.

Implementing Django forms without models

Amanda_K96 This is a continuation of the previous question Coding mind block with specific Django task the answer is: A pure Django solution would be: Create a form with three integer fields (like num1, , num2and result) In your opinion, fill num1and num2add t

Filter relational models in Django forms

Yahya ST18 I have a model that has a foreign key relationship with two oder models, one of which is "level". The view knows what level you are at based on the session variable, and then filters the class. Here's the class model: class Lesson(models.Model): lev

Django template with multiple models

João Areias I have a template from which I need to render information from multiple models. My models.py looks like this: # models.py from django.db import models class foo(models.Model): ''' Foo content ''' class bar(models.Model): ''' Bar content '

Django - CreateView with multiple models

Mirko Brombin Can I use Django CreateViews to make forms that add data to multiple tables? I created a model called UserMeta to store some additional information about my users. question I want to use CreateViews to create a view that shows the fields for crea

Django - CreateView with multiple models

Mirko Brombin Can I use Django CreateViews to make forms that add data to multiple tables? I created a model called UserMeta to store some additional information about my users. question I want to use CreateViews to create a view that shows the fields for crea

Django: get multiple models

Joe This is my first project in Django and I want to recreate a static HTML/CSS/js website as a dynamic website using the admin panel. However, I'm having a hard time understanding the view/url. On my index I have Main News, Events, Mini News - 3 categories. I

Django template with multiple models

João Areias I have a template from which I need to render information from multiple models. My models.py looks like this: # models.py from django.db import models class foo(models.Model): ''' Foo content ''' class bar(models.Model): ''' Bar content '

Django template with multiple models

João Areias I have a template from which I need to render information from multiple models. My models.py looks like this: # models.py from django.db import models class foo(models.Model): ''' Foo content ''' class bar(models.Model): ''' Bar content '

Django template with multiple models

João Areias I have a template from which I need to render information from multiple models. My models.py looks like this: # models.py from django.db import models class foo(models.Model): ''' Foo content ''' class bar(models.Model): ''' Bar content '

Django - CreateView with multiple models

Mirko Brombin Can I use Django CreateViews to make forms that add data to multiple tables? I created a model called UserMeta to store some additional information about my users. question I want to use CreateViews to create a view that shows the fields for crea

Django: get multiple models

Joe This is my first project in Django and I want to recreate a static HTML/CSS/js website as a dynamic website using the admin panel. However, I'm having a hard time understanding the view/url. On my index I have Main News, Events, Mini News - 3 categories. I

Query multiple Django models

Chris Shelton I'm looking for some advice on how to perform a query on multiple objects and then use them together in a detailed view of their related objects . Here's what I'm using now: -- app/models.py -- class Material(models.Model): created = models.Da