如何在Django中创建和保存具有多选值的模型

xdyibdwo  于 2023-01-10  发布在  Go
关注(0)|答案(1)|浏览(134)

我正在尝试创建一个模型,以便通过表单将一周中的多天分配给客户。但是,当我尝试保存它时,出现以下错误。

django.db.utils.DataError: value too long for type character varying(2)

我使用django-multiselectfield包来创建多个选择复选框。
https://pypi.org/project/django-multiselectfield/
model.py

from multiselectfield import MultiSelectField

DAYS_OF_THE_WEEK_CHOICES = [

('Mo', 'Monday'),
('Tu', 'Tuesday'),
('We', 'Wednesday'),
('Th', 'Thursday'),
('Fr', 'Friday'),
('Sa', 'Saturday'), 
('Su', 'Sunday'), 
]

class Customer(models.Model):
    days_of_the_week = MultiSelectField(choices=DAYS_OF_THE_WEEK_CHOICES)

forms.py

RECURRINGDAYS = [
        ('Mo','Monday'),
        ('Tu','Tuesday'),
        ('We','Wednesday'),
        ('Th','Thursday'),
        ('Fr','Friday'),
        ('Sa','Saturday'),
        ('Su','Sunday')
        ]

class CustomerCreateForm(forms.Form):
    days_of_the_week = forms.MultipleChoiceField(required=False, choices=RECURRINGDAYS, widget=forms.CheckboxSelectMultiple(), label="Recurring Day(s)?")

views.py

from .models import Customer
from .forms import CustomerCreateForm
def create_customer(request):
    form = CustomerCreateForm(request.POST or None)
    if request.POST:
        if form.is_valid():
           recurringDays = form.cleaned_data['days_of_the_week']

           newCustomer = Customer(
                        days_of_the_week = recurringDays
                        )
           newCustomer.save()

return render(request, "customer.html", context)

如果有人填写表单并选择Monday和Tuesday,我如何将其保存到数据库Customer模型中?

vktxenjb

vktxenjb1#

这个代码的作品,我只是花了几个小时,发现我忘了使migrations.
哎呀。

相关问题