Search code examples
pythondjangodjango-modelsdjango-formsdjango-file-upload

Is it possible to have an external file input for choicefields in django?


I have ChoiceField in my Django model which consist of several choices and i am using the CheckboxSelectMultiple widget in forms to have multiple select options.

models-

BREAKFAST_CHOICES = (('fruits', 'A bowl of fruits with nuts'),
                           ('tofu', 'Tofu Omlette'),
                           ('1', 'Option 1'),
                           ('2', 'Option 2'),
                           ('3', 'Option 3'),)
    breakfast = MultiSelectField(choices=VBREAKFAST_CHOICES, null=True, blank=True, default=False)

forms-

widgets = {
        'breakfast': forms.CheckboxSelectMultiple,
}

Now, in the future if I want to change the existing choice (options) with some other or add and delete options,how can i do this? Is there an easier way for a non programmer to just externally update a file and achieve this? i.e can my choicefield take an external file containing the list of options which can be edited as and when required.


Solution

  • This is just and sample code. Basically what you do here is u make two model breakfast and breakfast_food.

    In your models.py

    class BreakfastFood(models.Model):
    
       name = models.CharField(max_length=100)
    
    
    class Breakfast(models.Model):
    
       breakfast = models.ForeignKey(BreakfastFood, on_delete=models.CASCADE)
    

    This way you create a dynamic choicefield where you dont have to see through code to add, delete or update the items. Whatever you create or delete in you breakfastFood model name field will automatically get changed in the breakfast field. Try it out once if you got the idea.