如果下拉列表中的选项是从另一个模型继承的,如何在 Django 中将表单字段从下拉列表更改为单选按钮?

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

我正在开发一个应用程序,我可以从下拉列表中 select 项目并购买它们。我有一个表单字段,它是一个下拉列表(项目通过外部连接到其他模型 key.i 想让这些选项显示为单选按钮而不是下拉列表

我的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')

我的forms.py(我尝试使用 init 方法,但是当我使用它时我的下拉列表消失了)

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()

我的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)

请帮忙。(抱歉,我尽力解释了我遇到的问题,但我的英语不是很好)

你可以在你的模板中尝试这样的东西:

{% 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 %}

有关更多信息,请查看 https://docs.djangoproject.com/en/4.0/intro/tutorial01/,我从那里修改了此代码

所以尝试在您的表格中这样做:

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

删除forms.ModelForm并替换为forms.Form 并在您的视图中管理添加。

告诉我它是否有效。谢谢

所以我不得不将小部件添加到我的表单字段 >>> pack = forms.ModelChoiceField(Plans.objects.all(), widget=forms.RadioSelect())

所以我的完整表格 class 看起来像

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']