'how to change form field from dropdown list to radio button in django if the options in dropdown are being inherited from another model?

i am working on an application where i can select item from drop-down list and buy them. i have a form field which is a drop-down list(items are connected to other model via foreign key.i want to make those options appear as radio buttons instead of drop down list

my models.py

class Plans(models.Model):
    plan_name = models.CharField(max_length=50)
    speed = models.IntegerField()
    price = models.FloatField()

    def __str__(self):
        return self.plan_name

def get_deadline():
    return dt.today() + timedelta(days=30)


class Orders(models.Model):
    user = models.ForeignKey(CustomUser, primary_key=True, on_delete = models.CASCADE)
    pack = models.ForeignKey(Plans, on_delete = models.CASCADE)
    start_date = models.DateField(auto_now_add=True)
    end_date = models.DateField(default=get_deadline())
    is_active = models.BooleanField(default=True)

    def __str__(self):
        name = str(self.user.username)
        return name

    def get_absolute_url(self):
        return reverse('home-home')

my forms.py(i tried using the init method but my drop down list vanishes when i use it)

class BuyPlanForm(forms.ModelForm):
    error_css_class = 'error-field'
    required_css_class = 'required-field'

    class Meta():
        model = Orders
        fields = ['pack']
        

    #def __init__(self, *args, **kwargs):
     #   super(BuyPlanForm, self).__init__(*args, **kwargs)
      #  for field in self.fields.values():
       #     if isinstance(field.widget, forms.Select):
         #       field.widget = forms.RadioSelect()

my views.py

class UserBuyPlan(LoginRequiredMixin, CreateView):
    template_name = 'plans/plan.html'
    form_class = BuyPlanForm

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

please help.(sorry i tried my best to explain the problem i am having but my english isn't that great)enter image description here



Solution 1:[1]

so i had to just add widget to my form field >>> pack = forms.ModelChoiceField(Plans.objects.all(), widget=forms.RadioSelect())

so my full form class looks like

class BuyPlanForm(forms.ModelForm):
    error_css_class = 'error-field'
    required_css_class = 'required-field'
    pack = forms.ModelChoiceField(Plans.objects.all(), widget=forms.RadioSelect())

    class Meta():
        model = Orders
        fields = ['pack']

Solution 2:[2]

You can try something like this in your template:

{% for plan in order.plan_set.all %}
            <input type="radio" name="plan" id="choice{{ forloop.counter }}" value="{{ plan.id }}">
            <label for="plan{{ forloop.counter }}">{{ plan.choice_text }}</label><br>
        {% endfor %}

For further information check https://docs.djangoproject.com/en/4.0/intro/tutorial01/ , I modified this code from there

Solution 3:[3]

So try to do this in your form:

class BuyPlanForm(forms.Form):
    
    park = forms.MultipleChoiceField(
          widget=forms.CheckboxSelectMultiple,
          choices = Orders.pack,
          label = 'pack'
         )

Remove forms.ModelForm and replace it by forms.Form and manage the adding in your view.

Tell me if it works. Thanks

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shiva Kharbanda
Solution 2 davide
Solution 3 richard kangamba