Friday, 29 January 2021

Multiple models in Django form

I have the following models:

class Category(models.Model):
    label = models.CharField(max_length=40)
    description = models.TextField()


class Rating(models.Model):
    review = models.ForeignKey(Review, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    rating = models.SmallIntegerField()


class Review(models.Model):
    author = models.ForeignKey(User, related_name="%(class)s_author", on_delete=models.CASCADE)
    coach = models.ForeignKey(User, related_name="%(class)s_coach", on_delete=models.CASCADE)
    comments = models.TextField()

I'd like to create a front-end form which allows a user to review a coach, including a rating for some pre-populated categories.

In my head, the form would look something like:

 Coach: _______________         # Selection of all coach users from DB, this works as standard

 Category: "Professionalism"    # These would be DB entries from the Category model
 Rating: _ / 5

 Category: "Friendliness"
 Rating: _ / 5

 Category: "Value"
 Rating: _ / 5

 Comments:
 _________________________________
 _________________________________

 Submit

I've seen Django Formsets in the documentation but these appear to exist for creating multiple forms from the same model as a single form?

Not looking for a full answer, but if someone could point me in the right direction, it'd be hugely appreciated.

EDIT: Vineet's answer (https://stackoverflow.com/a/65883875/864245) is almost exactly what I'm looking for, but it's for the Admin area, where I need it on the front-end.



from Multiple models in Django form

No comments:

Post a Comment