How to add multiple form field types of choices for a question in django?

Viewed 1176

I'm creating a "Polls" like application. In this application there will be questions and every question will have single or multiple answers choices. The answer choice can be Text, Image, or Video.

I have made one model called Question and different models for different choice types:

class Question(models.Model):
    question_text = models.TextField()
    category = models.ForeignKey(QuestionCategory)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


class ChoiceText(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice = models.CharField(max_length=255)


class ChoiceImage(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice = models.ImageField()
  1. Is this a good way to design the models, or is there a better way to solve this problem ?
  2. It doesn't look so intuitive in the admin side too, any suggestions on the admin side ? I looked at https://docs.djangoproject.com/en/2.1/intro/tutorial07/ but I'm still confused about combining the different choices into a better user-friendly way.
2 Answers

I suggest you to go with same model (Choice). You can have a field named choice_type which selects the type of choice ('image','text','video').

class Choice(models.Model):
    answer_type_choices = (
        ('1','Text'),
        ('2','Image'),
        ('3','Video'),
    )
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_type = model.CharField(max_length=1,choices = answer_type_choices)
    choice = models.CharField(max_length=255)
    choice_media = models.FileField(upload_to='uploads/')

And while adding the data from admin or front you can have form with some customization that has validation rules in clean method ( require fields based on choice type, image field validation, video file validation ) based on choice_type.

This is probably the best way to do it, assuming a question could have multiple answers of the same type, e.g. one question might have 4 text choices and 2 image choices.

Depending on how you plan on using these models, you may want to create a model class called Choice and have the other models subclass from it.

Django's admin form is highly customizable. Since you haven't given us any specifics, feel free to explore the Django admin docs.

Related