vendredi 27 février 2015

Edit manytomany relationship in a single form with main model

I have the following Django models:



class Topping
name = models.CharField(max_length=30)

class Pizza
name = models.CharField(max_length=30)
topping = models.ManyToManyField(Topping, blank=True)


I now want the user to be able to create a new pizza and assign toppings in one form or more importantly in one page (I don't mind using FormSets).



class PizzaForm(forms.ModelForm):
class Meta:
model = Pizza


This works fine except that I get a MultiSelect box which is very hard to use if you have a lot of toppings. I also don't want to use a MultiSelect with checkboxes for the same reason. I rather would prefer to use something like an inlineformset where I have an add more button etc.


While I was writing this I finally discovered the first half of the answer. The solution is this formset:



ToppingFormSet = inlineformset_factory(Pizza,
Pizza.toppings.through,
extra = 1)


The only thing left is the "Add another topping" button. For this I have some custom javascript which copies the last row and increases the ids. But I would hope to find an easier Django way of adding this so any tips here would be great.


Aucun commentaire:

Enregistrer un commentaire