首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Django MultipleChoiceField ModelForm保存ModelForm数据

如何使用Django MultipleChoiceField ModelForm保存ModelForm数据
EN

Stack Overflow用户
提问于 2022-09-30 19:38:36
回答 1查看 105关注 0票数 1

我正在尝试从具有ModelForm的MultipleChoiceFields中保存数据。我希望用户能够选择多个timeframes并将数据保存到数据库中。

到目前为止,在使用MultipleChoiceField提交表单时,我没有得到任何返回。

这是我的models.py:

代码语言:javascript
复制
class InfoFormModel(models.Model):
    YES_NO = (
        ('yes', 'Yes'),
        ('no', 'No'),
    )
    TIMEFRAME = (
        ('1_weeks', '1 Week'),
        ('2_weeks', '2 Weeks'),
        ('3_weeks', '3 Weeks'),
        ('4_weeks_plus', '4 Weeks+'),
    )
    PAGES_NEEDED = (
        ('about_page', 'About Page'),
        ('contact_page', 'Contact Page'),
        ('blog_page', 'Blog Page'),
        ('map_page', 'Map Page'),
        ('ecommerce_page', 'Ecommerce Page'),
    )
    brand_name = models.CharField(
        blank=False, null=False, max_length=500, default='')
    logo = models.CharField(choices=YES_NO, blank=False,
                            null=False, max_length=500, default='no')
    what_is_the_service = models.TextField(
        blank=False, null=False, max_length=5000, default='')
    contact_number = models.BigIntegerField(blank=True, null=True, default='')
    email = models.EmailField(blank=True, null=True,
                              max_length=300, default='')
    timeframe = models.CharField(
        choices=TIMEFRAME, max_length=100, blank=False, null=False, default='')
    aim = models.TextField(blank=False, null=False,
                           max_length=5000, default='')
    products_product_images = models.CharField(
        choices=YES_NO, blank=False, max_length=500, null=False, default='')
    products_info = models.CharField(
        choices=YES_NO, blank=False, null=False, max_length=500, default='')
    pages_needed = models.CharField(
        choices=PAGES_NEEDED, blank=True, null=True, max_length=500, default='')

    def __str__(self):
        return self.brand_name

forms.py:

代码语言:javascript
复制
class InfoForm(forms.ModelForm):
    YES_NO = (
        ('yes', 'Yes'),
        ('no', 'No'),
    )
    TIMEFRAME = (
        ('1_weeks', '1 Week'),
        ('2_weeks', '2 Weeks'),
        ('3_weeks', '3 Weeks'),
        ('4_weeks_plus', '4 Weeks+'),
    )
    PAGES_NEEDED = (
        ('about_page', 'About Page'),
        ('contact_page', 'Contact Page'),
        ('blog_page', 'Blog Page'),
        ('map_page', 'Map Page'),
        ('ecommerce_page', 'Ecommerce Page'),
    )
    brand_name = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder' : 'Business/Brand Name?'}))
    logo = forms.CharField(label='Do you have a logo?', widget=forms.RadioSelect(choices=YES_NO))
    what_is_the_service = forms.CharField(label='', widget=forms.Textarea(attrs={'placeholder' : 'What service are you providing?'}))
    contact_number = forms.CharField(label='', widget=forms.NumberInput(attrs={'placeholder' : 'Contact number'}))
    email = forms.CharField(label='', widget=forms.EmailInput(attrs={'placeholder' : 'Email address'}))
    timeframe = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                          choices=TIMEFRAME)
    aim  = forms.CharField(label='', widget=forms.Textarea(attrs={'placeholder' : 'What will be the aim for your website?'}))
    products_product_images = forms.CharField(label='Do you have any product images?', widget=forms.RadioSelect(choices=YES_NO))
    products_info = forms.CharField(label='Do you your product info (eg, product names, pricing, descriptions etc.)?', widget=forms.RadioSelect(choices=YES_NO))
    pages_needed = forms.CharField(label="Select which pages you'll need?", widget=forms.RadioSelect(choices=PAGES_NEEDED))


    class Meta:
        model = InfoFormModel
        fields = (
            'brand_name',
            'logo',
            'what_is_the_service',
            'contact_number',
            'email',
            'timeframe',
            'aim',
            'products_product_images',
            'products_info',
            'pages_needed',
        )

views.py

代码语言:javascript
复制
def home(request):
    submitted = False
    if request.method == 'POST':
        form = InfoForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'thanks.html')
            # return HttpResponseRedirect('/?submitted=True')
    else:
        form = InfoForm()
        if 'submitted' in request.GET:
            submitted = True

    form = InfoForm

    context = {
        'form': form,
        'submitted': submitted,
    }
    return render(request, 'home.html', context)

任何帮助都将不胜感激。谢谢!

EN

回答 1

Stack Overflow用户

发布于 2022-10-01 16:29:28

我认为您的模型字段和表单字段之间存在差异。

在您的模型中,您将timeframe字段定义为:

代码语言:javascript
复制
timeframe = models.CharField(choices=TIMEFRAME, max_length=100, blank=False, null=False, default='')

在表单代码中,您将timeframe字段定义为:

代码语言:javascript
复制
timeframe = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=TIMEFRAME)

在验证数据之后,MultipleChoiceField将尝试将一个列表分配给InfoFormModel上的timeframe属性(顺便说一句,糟糕的命名)。这个模型属性应该包含一个字符串。

我认为有两种方法可以解决这个问题。

  1. 在模型中使用posgtres的ArrayFieldArrayField支持将列表分配给它。别忘了迁移并运行它们。另外,请注意,只有当您使用PostgreSQL DB.

时,这才有效。

代码语言:javascript
复制
from django.contrib.postgres.fields import ArrayField


class InfoFormModel(models.Model):
    ...
    timeframe = ArrayField(CharField(choices=TIMEFRAME, max_length=100), default=[])
    ...

  1. 重写MultipleChoiceField以返回字符串而不是列表。通过重写,可以使字段以逗号分隔字符串的形式返回列表。这也意味着您需要从模型代码中的字段中删除choices kwarg,因为如果保存了多个选项,这些字段将不会通过验证。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73913318

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档