Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

View saving to same model but different instances – not working

I have a view that saves form details through a html page to two different Person objects (which have different IDs), but which reside in the same table (on different rows)

View

person = Person.objects.filter(pk = user.related_person_id).first()
medical_emergency_person = Person.objects.filter(related_entity=medical_emergency_entity).first()

if request.method == "POST":
   form1 = PersonUpdateForm(request.POST, instance=person)
   form5 = MedicalPersonUpdateForm(request.POST, instance=medical_emergency_person)

   form1.save()
   form5.save()
else:
    form1 = PersonUpdateForm(
        initial= {
           "title": person.title,
           "first_name": person.first_name,
           "last_name": person.last_name,
           "alias": person.alias
        }
    )
    form5 = MedicalPersonUpdateForm(
        initial= {
           "title": medical_emergency_person.title,
           "first_name": medical_emergency_person.first_name,
           "last_name": medical_emergency_person.last_name,
        }
    )

context['personal_person_form'] = form1
context['personal_medical_emergency_person_form'] = form5

Forms

class MedicalPersonUpdateForm(forms.ModelForm):

# FORM META PARAMETERS
class Meta:
    model = Person
    fields = ('title', 'first_name', 'last_name')
    labels = {
        'title': _("Title*"),
        'first_name': _("Emergency Contact First Name*"),
        'last_name': _("Emergency Contact Last Name*")
        }

# FORM INITIALISATION TO SET HTML STYLING
def __init__(self, *args, **kwargs):
    super(MedicalPersonUpdateForm, self).__init__(*args, **kwargs)
    self.fields['title'].widget.attrs['class'] = 'input'
    self.fields['first_name'].widget.attrs['class'] = 'input is-danger'
    self.fields['last_name'].widget.attrs['class'] = 'input is-danger'


class PersonUpdateForm(forms.ModelForm):

# FORM META PARAMETERS
class Meta:
    model = Person
    fields = ('title', 'first_name', 'last_name', 'alias')
    labels = {
        'title': _("Title*"),
        'first_name': _("First Name*"),
        'last_name': _("Last Name*"),
        'alias': _("Alias")
        }

# FORM INITIALISATION TO SET HTML STYLING
def __init__(self, *args, **kwargs):
    super(PersonUpdateForm, self).__init__(*args, **kwargs)
    self.fields['title'].widget.attrs['class'] = 'input'
    self.fields['first_name'].widget.attrs['class'] = 'input is-danger'
    self.fields['last_name'].widget.attrs['class'] = 'input is-danger'
    self.fields['alias'].widget.attrs['class'] = 'input is-danger'

Result

The behaviour I am getting through is that in the database, both Person records get written with the details from Form 5? And then when the page reloads on the request.post, for the fields on the page, both sets of the firstname and lastname fields show the details from just Form 5, not, both Form 1 and Form 5. What am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Both have the same field names. You can avoid that by working with a prefix=…:

if request.method == 'POST':
    form1 = PersonUpdateForm(request.POST, prefix='person', instance=person)
    form5 = MedicalPersonUpdateForm(request.POST, prefix='medical', instance=medical_emergency_person)
    if form1.is_valid() and form5.is_valid():
        form1.save()
        form5.save()
        return redirect('name-of-some-view')
    
else:
    form1 = PersonUpdateForm(prefix='person', instance=person)
    form5 = MedicalPersonUpdateForm(prefix='medical', instance=medical_emergency_person)
context['personal_person_form'] = form1
context['personal_medical_emergency_person_form'] = form5

Note: In case of a successful POST request, you should make a redirect
[Django-doc]

to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading