pythondjangomodelcharimagefield

How to put Image reference in Character Field in Django db?


I am making an E-learning website using Django. The website would have questions along with answer options from which the user has to choose the correct answer. Most of the answer options are texts because of which I have declared the options in my model as CharField.

class Question(models.Model):
question = models.CharField(max_length=250)
option_1 = models.CharField(max_length=50)
option_2 = models.CharField(max_length=50)
option_3 = models.CharField(max_length=50)
option_4 = models.CharField(max_length=50)

But I realized that in some questions, instead of text fields there are images as options. For example, there will be four images instead of texts and the user has to choose one answer among them. How do I include both ImageField and CharField in my model as answer choices?


Solution

  • One option would be to insert 8 fields and set blank=True on all of them. Then when you add your questions you can decide which fields to use.

    Like this:

    class Question(models.Model):
        question = models.CharField(max_length=250, blank=True)
        text_1 = models.CharField(max_length=50, blank=True)
        text_2 = models.CharField(max_length=50, blank=True)
        text_3 = models.CharField(max_length=50, blank=True)
        text_4 = models.CharField(max_length=50, blank=True)
        image_1 = models.ImageField(upload_to='question_images', blank=True)
        image_2 = models.ImageField(upload_to='question_images', blank=True)
        image_3 = models.ImageField(upload_to='question_images', blank=True)
        image_4 = models.ImageField(upload_to='question_images', blank=True)
    

    I'm sure there are more elegant ways to achieve this, but this is the first that came to mind.

    But by the way, it would be better to have separate question and answer models.