Search code examples
pythondjangoratingdjango-forms

Django - Rating on Multiple Criteria: Model Formset?


I have a content that I'd like to rate on multiple criteria.
Imagine this kind of model:

class Content(models.Model):
  name = models.CharField(max_length=50)

class Criteria(models.Model):
  name = models.CharField(max_length=50)
  content = models.ForeignKey(Content)

class ContRate(models.Model):
  user = models.ForeignKey(User, help_text="Who rated ?")
  crit = models.ForeignKey(Criteria)
  rate = models.DecimalField()

The user has a page displaying the content.
From this page, he can also rate the content on the criterias set

Rating Criterias

Question are:
Do you suggest to use a Model Formset for this purpose ?
Or should I do a simple Ajax form to post the ratings ?
Any why should I do this ?


Solution

  • I would use a model formset for this kind of problem although you are not going to use my_formset.is_valid() nor my_formset.save() but because it ease the forms construction in the view and the render in the template. No need to worry with the form prefixes etc.

    Your Ajax call on the onclick event (fired by a click on a star) should call a view with the ContRate pk (if present) and the rate as parameters.

    The view will instanciate a ContRateForm (the same used in your previous modelformset_factory) whith those parameters, use the usual mechanisms of ModelForm validation and database insert/update and finally render a json response.