为什么我无法在提交时为表单字段分配值?

时间:2015-02-19 18:31:09

标签: django

我有一个名为nearbyzips1的模型字段,我有一个在zip_codes中调用的整数列表。我试图将zip_codes [1]的值传递给nearbyzips1,但由于某种原因它不会保存。当我填写表单并点击提交时,我可以看到每个字段中的所有值,除了Nearbyzips1,它返回None。

if form.is_valid():

    cleanzipcode= form.cleaned_data['zipcode']
    nearestzips = PostalCode.objects.distance(PostalCode.objects.get(code=cleanzipcode).location).order_by('distance')[:8]

    zip_codes = list(nearestzips.values_list('code', flat=True))
    //print zip_codes
    form.cleaned_data['nearbyzips1'] = zip_codes[1]
    //print form.cleaned_data['nearbyzips1']
    profile = form.save()

我添加了一些打印语句进行故障排除,zip_codes按预期打印一个简短的整数列表。 form.cleaned_data [' nearbyzips']从列表中返回其中一个整数。那么为什么不节约呢?我很困惑。

我怀疑这个问题出现在上面的代码中,但以防万一我从forms.py和models.py中包含了一些其他代码,以防它有用。

models.py

class MyProfile(UserenaBaseProfile):
    user = models.OneToOneField(User,
                                unique=True,
                                verbose_name=_('user'),
                                related_name='my_profile')
    streetaddress=models.CharField(null=True, blank=True, max_length=30)
    city = models.CharField(null=True, blank=True, max_length=20)
    state = models.CharField(null=True, blank=True, max_length=20)
    zipcode = models.IntegerField(_('zipcode'),
                                       max_length=5, null=True, blank=True)
    nearbyzips1=models.IntegerField(null=True, blank=True, max_length=10)

forms.py

class EditProfileForm(forms.ModelForm):
    """ Base form used for fields that are always required """
    first_name = forms.CharField(label=_(u'First name'),
                                 max_length=30,
                                 required=False)
    last_name = forms.CharField(label=_(u'Last name'),
                                max_length=30,
                                required=False)

    def __init__(self, *args, **kw):
        super(EditProfileForm, self).__init__(*args, **kw)
        # Put the first and last name at the top
        new_order = self.fields.keyOrder[:-2]
        new_order.insert(0, 'first_name')
        new_order.insert(1, 'last_name')
        self.fields.keyOrder = new_order

    class Meta:
        model = get_profile_model()
        exclude = ['user', 'privacy']
        widgets = {
            'deliveryoption': forms.RadioSelect(choices=[
            (True, '  Yes'),
            (False, '  No')             
        ])}


    def save(self, force_insert=False, force_update=False, commit=True):
        profile = super(EditProfileForm, self).save(commit=commit)
        # Save first and last name
        user = profile.user
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']

        user.save()

        return profile

我是否可以尝试从forms.py内部而不是views.py中将值传递给nearbyzips1?

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

# --- Replace this ---
# form.cleaned_data['nearbyzips1'] = zip_codes[1]
# print form.cleaned_data['nearbyzips1']
# profile = form.save()
# --- whith this ---
profile = form.save(commit=False)
profile.nearbyzips1 = zip_codes[1]
profile.save()

我真的不喜欢将业务逻辑放入ModelForm.save,更喜欢将所有业务逻辑放入视图中。