Tomasz Brzezina
Tomasz Brzezina

Reputation: 1534

form with manytomany object creation

I'm trying to make own form adding object Announcement

models.py:

class Announcement(models.Model):
  person = models.ForeignKey('Person')
  source = models.CharField(max_length=30)
  date = models.DateField(default=datetime.now())
  valid_date = models.DateField(null=True,blank=True)

class Person(models.Model):
  names = models.ManyToManyField('Name')
  birth_date = models.DateField(null=True, blank=True)

class Name(models.Model):
  first_name = models.CharField(max_length=50,blank=True)
  middle_name = models.CharField(max_length=50, blank=True)
  last_name = models.CharField(max_length=50, blank=True)

(It maybe loos weird, but in my concept each Person can have more than one Name, and also the same Name can be assigned to different Persons)

forms.py

from django import forms
from backoffice.models import Announcement

class AnnouncementForm(forms.ModelForm):
  class Meta:
    model = Announcement
    fields = ('person','signature','organisation','source', 'date')

And everything works perfectly but I have to choose Person from selectbox. And it is expected behaviour.

But in my case i'm definetely sure, that person doesn't exists in base (all announcements are for different person for very long time - so i want to change person select box to three fields, and create new person (with new names) everytime I save the announcement.

I think I know how to save many to many, that's why i don't put the views.py, but I don't know how to set the forms.py to get fields.

I tried

class AnnouncementForm(forms.ModelForm):
  class Meta:
    model = Announcement
    fields = ('person__names__first_name','signature','organisation','source', 'date')

but got Unknown field(s) (person__names__first_name) specified for Announcement

Upvotes: 0

Views: 62

Answers (1)

Dean Christian Armada
Dean Christian Armada

Reputation: 7384

  • person__name__first_name will not really work in the forms, that only works for the django admin
  • you have to create a custom field for the first name and then create a logic for saving on either

    def clean(self):
     // logic here
    

    or

    def save(self, commit=True):
     // put clean data here
     announcement_form = super(AnnouncementForm, self).save(commit=False)
     announcement_form.save()
    

Upvotes: 1

Related Questions