Python - Django - 表单选择字段和cleaned_data

发布于 2024-10-26 06:40:46 字数 3718 浏览 2 评论 0原文

我对 clean_data 的工作方式有疑问。我想将 clean_data 存储在会话中,以便稍后可以重新填充表单对象。问题是我的选择字段似乎存储下拉列表的显示名称而不是实际值。例如:

<select name="dropdown_element">
<option value="1">Red</option>
<option value="2">Blue</option>
</select>

如果我选择 Red 并使用 form.cleaned_data['dropdown_element'] 我将得到显示名称 Red 而不是值 1。有没有办法获取值而不是标签?

编辑

视图:

 def vehicle_add_fleet(request):
        if request.POST:
            fleet_form = FleetForm(request.POST, prefix='fleet')
            count_form = CountForm(request.POST, prefix='count', label='# of Odometer Readings')
            if fleet_form.is_valid() and count_form.is_valid():
                request.session['add'] = {}
                request.session['add']['fleet'] = fleet_form.cleaned_data
                return HttpResponseRedirect('/vehicle/add/general/%s/' % (count_form.cleaned_data['count']))
        else:
            fleet_form = FleetForm(prefix='fleet')
            count_form = CountForm(prefix='count', label='# of Odometer Readings')
        return render_to_response('add/fleet.html', {'fleet_form': fleet_form, 'count_form': count_form})

表单:

class FleetForm(forms.models.ModelForm):
    home_location = forms.ModelChoiceField(queryset=Location.objects.filter(home_only=True), required=False, label=_('Home Location'))
    number = forms.IntegerField(max_value=99999, label=_('Fleet Number'))
    ari_number = forms.IntegerField(max_value=999999, required=False, label=_('ARI Number'))
    class Meta:
        model = Fleet
        exclude = ('status')

模型:

class Fleet(models.Model):
     #One-to-Many
        status = models.ForeignKey(Status, verbose_name=_('Status'), default=3)
        pwgsc_spec_code = models.ForeignKey(PWGSCSpecCode, verbose_name=_('PWGSC Specification Code'))
        current_location = models.ForeignKey(Location, related_name='fleet_current', blank=True, null=True, verbose_name=_('Current Location'))
        home_location = models.ForeignKey(Location, related_name='fleet_home', blank=True, null=True, verbose_name=_('Home Location'))
        #Fields
        number = models.PositiveIntegerField(verbose_name=_('Fleet Number'))
        pool_identifier = models.CharField(max_length=1, verbose_name=_('Pool Identifier'))
        ari_number = models.PositiveIntegerField(blank=True, null=True, verbose_name=_('ARI Number'))
        credit_card_number = models.CharField(max_length=16, blank=True, verbose_name=_('Credit Card Number'))
        credit_card_expiry_date = models.DateField(blank=True, null=True, verbose_name=_('Credit Card Expiry Date'))
        company_name = models.CharField(max_length=16, blank=True, verbose_name=_('Company Name'))
        in_service_date = models.DateField(blank=True, null=True, verbose_name=_('In Service Date'))
        reason = models.TextField(blank=True, verbose_name=_('Reason'))

        class Meta:
            verbose_name = _('Fleet')
            verbose_name_plural = _('Fleets')

所以基本上我想将车队表单数据(cleaned_data)添加到会话中。但是,当我到达要保存舰队表单的页面时,我尝试填充它:

def vehicle_add(request):
    #save non-partial forms
    form = FleetForm(request.session['add']['fleet'])
    if form.is_valid():
        return HttpResponse('valid')
    else:
        return HttpResponse('invalid')

并且在 form.is_valid() 行上收到错误:

/vehicle/add/fleet/ int() 处出现类型错误 参数必须是字符串或数字

我当前的理论是fleet_form.cleaned_data[“home_location”](例如)存储显示值而不是值字段中的整数

其他信息:

我正在使用django 1.1 并升级到 django 1.3。在所有其他示例中,我看到人们似乎获得了下拉值,而不是下拉显示值。希望这是足够的信息!

感谢您的帮助

I'm having an issue with how cleaned_data seems to work. I want to store the cleaned_data in a session so I can repopulate the form object later. The problem is my choice fields seems to store the display name of the dropdown not the actual value. For example:

<select name="dropdown_element">
<option value="1">Red</option>
<option value="2">Blue</option>
</select>

If I selected Red and used form.cleaned_data['dropdown_element'] I will get the display name Red and not the value of 1. Is there a way to get the value instead of the label?

EDIT

VIEW:

 def vehicle_add_fleet(request):
        if request.POST:
            fleet_form = FleetForm(request.POST, prefix='fleet')
            count_form = CountForm(request.POST, prefix='count', label='# of Odometer Readings')
            if fleet_form.is_valid() and count_form.is_valid():
                request.session['add'] = {}
                request.session['add']['fleet'] = fleet_form.cleaned_data
                return HttpResponseRedirect('/vehicle/add/general/%s/' % (count_form.cleaned_data['count']))
        else:
            fleet_form = FleetForm(prefix='fleet')
            count_form = CountForm(prefix='count', label='# of Odometer Readings')
        return render_to_response('add/fleet.html', {'fleet_form': fleet_form, 'count_form': count_form})

FORM:

class FleetForm(forms.models.ModelForm):
    home_location = forms.ModelChoiceField(queryset=Location.objects.filter(home_only=True), required=False, label=_('Home Location'))
    number = forms.IntegerField(max_value=99999, label=_('Fleet Number'))
    ari_number = forms.IntegerField(max_value=999999, required=False, label=_('ARI Number'))
    class Meta:
        model = Fleet
        exclude = ('status')

MODEL:

class Fleet(models.Model):
     #One-to-Many
        status = models.ForeignKey(Status, verbose_name=_('Status'), default=3)
        pwgsc_spec_code = models.ForeignKey(PWGSCSpecCode, verbose_name=_('PWGSC Specification Code'))
        current_location = models.ForeignKey(Location, related_name='fleet_current', blank=True, null=True, verbose_name=_('Current Location'))
        home_location = models.ForeignKey(Location, related_name='fleet_home', blank=True, null=True, verbose_name=_('Home Location'))
        #Fields
        number = models.PositiveIntegerField(verbose_name=_('Fleet Number'))
        pool_identifier = models.CharField(max_length=1, verbose_name=_('Pool Identifier'))
        ari_number = models.PositiveIntegerField(blank=True, null=True, verbose_name=_('ARI Number'))
        credit_card_number = models.CharField(max_length=16, blank=True, verbose_name=_('Credit Card Number'))
        credit_card_expiry_date = models.DateField(blank=True, null=True, verbose_name=_('Credit Card Expiry Date'))
        company_name = models.CharField(max_length=16, blank=True, verbose_name=_('Company Name'))
        in_service_date = models.DateField(blank=True, null=True, verbose_name=_('In Service Date'))
        reason = models.TextField(blank=True, verbose_name=_('Reason'))

        class Meta:
            verbose_name = _('Fleet')
            verbose_name_plural = _('Fleets')

So basically I want to add the fleet form data (cleaned_data) to the session. However, when I get to the page where I want to save the fleet form, I try and populate it:

def vehicle_add(request):
    #save non-partial forms
    form = FleetForm(request.session['add']['fleet'])
    if form.is_valid():
        return HttpResponse('valid')
    else:
        return HttpResponse('invalid')

And I get an error on the form.is_valid() line:

TypeError at /vehicle/add/fleet/ int()
argument must be a string or a number

My current theory is that fleet_form.cleaned_data["home_location"] (for example) stores The display value and not the integer in the value field

Other information:

I was using django 1.1 and upgraded to django 1.3. In all the other examples I see people seem to get the dropdown value and not the dropdown display value. Hope this is enough information!

Thanks for any help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

む无字情书 2024-11-02 06:40:46

假设您的模型是:

class SomeModel(models.Model):
    colour = models.IntegerField(choices=[(1, 'Red'), (2, 'Blue'),])

您的表单:

class SomeModelForm(forms.ModelForm):
    class Meta:
        model = SomeModel

在模板中显示上述表单并在 GET/POST 之后应该会给出颜色的整数值。

Assuming your model is:

class SomeModel(models.Model):
    colour = models.IntegerField(choices=[(1, 'Red'), (2, 'Blue'),])

Your form:

class SomeModelForm(forms.ModelForm):
    class Meta:
        model = SomeModel

Displaying the above form in the template and after a GET/POST should give you the integer value of the colour.

青春有你 2024-11-02 06:40:46

看起来给您的表单添加前缀会导致一些奇怪的行为。我不太熟悉使用前缀,所以我不能给你任何建议,但你没有在vehicle_add_view中添加前缀。

编辑

我做了一些测试

不带前缀

>>> from test.forms import TestForm
>>> form = TestForm(data={'test_field':'test_data'})
>>> form.__dict__
{'files': {}, 'is_bound': True, 'error_class': <class 'django.forms.util.ErrorList'>,
'empty_permitted': False, 'fields': {'test_field': <django.forms.fields.CharField 
object at 0x99d05ac>}, 'initial': {}, 'label_suffix': ':', 'prefix': None, 
'_changed_data': None, 'data': {'test_field': 'test_data'}, '_errors': None, 
'auto_id': 'id_%s'}
>>> form.is_valid()
True
>>> form.cleaned_data
{'test_field': u'test_data'}
>>>    

带前缀:

>>> form = TestForm(data={'test_field':'test_data'}, prefix="foo")
>>> form.__dict__
{'files': {}, 'is_bound': True, 'error_class': <class 'django.forms.util.ErrorList'>,
'empty_permitted': False, 'fields': {'test_field': <django.forms.fields.CharField object 
at 0x99d03cc>}, 'initial': {}, 'label_suffix': ':', 'prefix': 'foo', '_changed_data': 
None, 'data': {'test_field': 'test_data'}, '_errors': None, 'auto_id': 'id_%s'}
>>> form.is_valid()
True
>>> form.cleaned_data
{'test_field': u''}
>>> 

注意到cleaned_data缺少值,即使它看起来像数据在形式。希望这能让您在解决问题时朝着正确的方向前进。

Looks Like prefixing your form is causing some strange behavior. I'm not that familiar with using prefix so i can't give you any advice on that, but you aren't prefixing in your vehicle_add_view.

edit

I did some testing

without prefix:

>>> from test.forms import TestForm
>>> form = TestForm(data={'test_field':'test_data'})
>>> form.__dict__
{'files': {}, 'is_bound': True, 'error_class': <class 'django.forms.util.ErrorList'>,
'empty_permitted': False, 'fields': {'test_field': <django.forms.fields.CharField 
object at 0x99d05ac>}, 'initial': {}, 'label_suffix': ':', 'prefix': None, 
'_changed_data': None, 'data': {'test_field': 'test_data'}, '_errors': None, 
'auto_id': 'id_%s'}
>>> form.is_valid()
True
>>> form.cleaned_data
{'test_field': u'test_data'}
>>>    

with prefix:

>>> form = TestForm(data={'test_field':'test_data'}, prefix="foo")
>>> form.__dict__
{'files': {}, 'is_bound': True, 'error_class': <class 'django.forms.util.ErrorList'>,
'empty_permitted': False, 'fields': {'test_field': <django.forms.fields.CharField object 
at 0x99d03cc>}, 'initial': {}, 'label_suffix': ':', 'prefix': 'foo', '_changed_data': 
None, 'data': {'test_field': 'test_data'}, '_errors': None, 'auto_id': 'id_%s'}
>>> form.is_valid()
True
>>> form.cleaned_data
{'test_field': u''}
>>> 

notice that the cleaned_data is missing the value even tho it looks like the data is in the form. Hope that gets you off in the right direction as far as troubleshooting the problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文