python - 如何在 Django 中创建单选按钮,哪些字段在表单和模型中使用

标签 python django forms django-models

我是 Django 和 Python 的新手。我想在我的表单中添加一个单选按钮,但它不起作用。

表单.py:

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.forms.widgets import RadioSelect
from choicebtn.models import myChoice


class myChoiceForm(UserCreationForm):
    name=forms.CharField(max_length=55)
    TYPE_SELECT = (('0', 'Female'),('1', 'male'),)
    gender=forms.ChoiceField(widgets.RadioSelect(choices=TYPE_SELECT))

    class Meta:
           model = myChoice
           fields = ['name','gender']   

模型.py:

from django.db import models
from django.forms.widgets import RadioSelect
from django.urls import reverse


class myChoice(models.Model):
    name=models.CharField(max_length=55)
    TYPE_SELECT = (('0', 'Female'),('1', 'male'),)
    gender=models.CharField(max_length=11,choices=TYPE_SELECT)
    

这只显示下拉列表文本框。它不显示单选按钮。 请帮助我。

最佳答案

在 models.py 中:

class myChoice(models.Model):
    name = models.CharField(max_length=55)
    TYPE_SELECT = (
        ('0', 'Female'),
        ('1', 'male'),
    )
    gender = models.CharField(max_length=11,choices=TYPE_SELECT)

在 forms.py 中:

class myChoiceForm(ModelForm):

    class Meta:
           model = myChoice
           fields = ['__all__']
           widgets = {
               'gender': forms.RadioSelect()
           }   

关于python - 如何在 Django 中创建单选按钮,哪些字段在表单和模型中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45838053/

相关文章:

Python:升级我自己的包

python - 使用 TLS 的 Django LDAP3 安全性 : am I secure?

python - 如何在 Django 中提供可下载的图像文件

html - 为输入元素指定 type = text 是否有任何功能目的?

javascript - 复选框切换时禁用输入字段(JQuery)

python - Pandas - 在列中附加行值的总和(如果总和为偶数)或 NaN(如果为奇数)

python - 从一组(相似的)字符串中确定前缀

mysql - Django ORM 在 SQL Join 中创建 Phantom Alias

ruby - Mechanize 在登录页面找不到表单

python - 让按钮在一段时间后出现