Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Many to Many through intermediary table form like admin's TabularInline form?

I'd like to have a form to add, edit and delete values for a many to many relationship using a specified intermediary table just like what I can get from Django's admin TabularInline form. Is there a way to do this? I have not found it in Django's documentation.

I have created a form to edit the UserProfile and would like to be able to add, edit and delete the many to many with UserProfile_Language (both language and proficiency). How do I make a form for this? How do I handle this in the view?

My Models are as follows:

class Language(models.Model):
    LANGUAGE_ENGLISH = 1
    LANGUAGE_FRENCH = 2
    LANGUAGE_CHOICES = (
        (LANGUAGE_ENGLISH, 'English'),
        (LANGUAGE_FRENCH, 'French')
    )

    language = models.SmallIntegerField(choices=LANGUAGE_CHOICES)

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    languages = models.ManyToManyField(Language, null=True, blank=True, through='UserProfile_Language')

class UserProfile_Language(models.Model):
    FLUENT = 1
    OK = 2
    PROFICIENCY_CHOICES = (
        (FLUENT, 'Fluent'),
        (OK, 'Okay')
    )

    userprofile = models.ForeignKey(UserProfile)
    language = models.ForeignKey(Language)
    proficiency = models.SmallIntegerField(choices=PROFICIENCY_CHOICES)
like image 285
user636381 Avatar asked Nov 05 '22 02:11

user636381


1 Answers

I assuming the you mean on the front end and not in the admin. I believe that you can do this using a form set. (http://docs.djangoproject.com/en/dev/topics/forms/formsets/). You would create a form for the through table to use in the formset.

Also, you may have simplified your models for posting, but if the language model is really just one choice field, why not just combine language and userprofile_language into one? You can replace the ForeignKey with the choice field and get the same behavior. That would make your display easier. (ignore this is language actually has more fields)

like image 62
lovefaithswing Avatar answered Nov 09 '22 03:11

lovefaithswing