I have a model Question which can have several Answer instances, each one with a given coefficient.
What I want is an admin in which I can add as many answers as I want, and creating a new one everytime one is added.
I tried with a many-to-many field, as shown below, but the default admin is a multiple select with all the answers in the db.
What I would like ideally is a button “add answer” in my Question admin, which would allow me to create a new answer and add it to my question.
How can I achieve this?
Thanks
class Question(models.Model):
answer = models.ManyToManyField(Response)
class Answer(models.Model):
text = models.TextField()
coefficient = models.IntegerField()
I think you may be interested in Admin Inlines form.
In this case you need to remove the ManyToMany field and add
a ForeignKey field to your Answer model and then tell the admin
to add an ‘inline’ admin form to your Question admin view.
models.py
admin.py
This should do exactly what you asked for.
In the Question object you will have a ‘answer_set’ object which behave like
a ManyToMany handler.
The following example explain how to get a queryset containing all the answer related to your question.