django模型来自无线电选择

Dar*_*ech 0 django django-forms

我有一个简单的模型形式:

 class ProductSelectionForm(ModelForm):
     class Meta:
         model = Product
Run Code Online (Sandbox Code Playgroud)

和模型:

class Product(models.Model):
     name = models.CharField(max_length=155)

     def __unicode__(self):
         return self.name
Run Code Online (Sandbox Code Playgroud)

但是如果我使用{{ form.as_p }}标记渲染表单, 它只是将表单呈现为单个文本输入.如何将表单呈现为无线电选择选项,使用name选项标签和pk值?我尝试过widget但没有快乐.

任何帮助非常感谢.

Dan*_*man 8

你不需要一个模型形式.它们用于创建和编辑模型实例.相反,您似乎想要的是一个选择现有实例的表单:为此,使用带有ModelChoiceField的普通表单:

class ProductSelectionForm(forms.Form):
    choice = forms.ModelChoiceField(queryset=Product.objects.all(), 
                                    widget=forms.RadioSelect)
Run Code Online (Sandbox Code Playgroud)