dimanche 28 juin 2015

Django: Form and many2many relationship using through relationshiop

I am trying to sort out a specific problem that involve "many2many" relationship using through specification. I've already tried to use inline_factory but I was not able to sort out the problem.

I have these tables

class Person(models.Model):
    id = models.AutoField(primary_key=True)  
    fullname = models.CharField(max_length=200)
    nickname = models.CharField(max_length=45, blank=True)

    class Meta:
        db_table = 'people'

class Role(models.Model):
        role = models.CharField(max_length=200)
    class Meta:
        verbose_name_plural = 'roles'
        db_table = 'roles'

class Study(models.Model):
    id = models.AutoField(primary_key=True) 
    title = models.CharField(max_length=255)
    description = models.CharField(max_length=1000)
    members = models.ManyToManyField(Person, through='Studies2People')

    class Meta:
        db_table = 'studies'

class Studies2People(models.Model):
    person = models.ForeignKey(Person)
    role = models.ForeignKey(Role)
    study = models.ForeignKey(Study)

    class Meta:
        verbose_name_plural = 'studies2people'
        db_table = 'studies2people'
        unique_together = (('person', 'role', 'study'),)
#forms.py
from .models import Study, Person, Role, Studies2People
class RegisterStudyForm(ModelForm):
    class Meta:
        model = Study
        fields = '__all__'

#View.py
class StudyCreateView(CreateView):
    template_name = 'managements/register_study.html'
    model = Study
    form_class = RegisterStudyForm
    success_url = 'success/'

    def get(self, request, *args, **kwargs):
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        return self.render_to_response(self.get_context_data(form=form))

The code above creates a form like:

Study.Title
Study.description
List of People

I want to create a form to fill in all fields that involve Studies2People Something like this:

Study.Title
Study.description
Combo(people.list)
Combo(Role.list)

Maybe I should start from Studies2People but I don't know how to show the "inline" forms involved.

Thanks in advance C.

Aucun commentaire:

Enregistrer un commentaire