为什么我得到匹配的查询不存在?

时间:2015-02-16 17:21:23

标签: django django-queryset

我收到以下错误:

DoesNotExist: PostalCode matching query does not exist

在下面一行:

nearestzips = PostalCode.objects.distance(PostalCode.objects.get(code='self.zipcode').location)

努力解决问题。我进入了我的python shell并且能够运行:

PostalCode.objects.distance(PostalCode.objects.get(code='97202').location)

返回了正确的zipcodes。我认为这意味着我在原始查询中不恰当地使用self.zipcode?我认为我应该使用self.zipcode,因为基本上该视图适用于具有edit_profile字段的zipcode表单。所以我认为self.zipcode将从该表单中获取用户zipcode,然后使用该值运行查询。我在这里做错了什么?

如果有帮助,可以使用以下代码:

views.py

@secure_required
@login_required
def profile_edit(request, username, edit_profile_form=EditProfileForm,
                 template_name='userena/profile_form.html', success_url=None,
                 extra_context=None, **kwargs):
profile = get_profile(user)
form = edit_profile_form(instance=profile, initial=user_initial)
    if request.method == 'POST':
        if form.is_valid()

            nearestzips = PostalCode.objects.distance(PostalCode.objects.get(code='self.zipcode').location)
            zip_codes = list(nearestzips.values_list('code', flat=True))
            user.nearbyzips = zip_codes

            return redirect(redirect_to)

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(forms.ModelForm, 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']

    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

1 个答案:

答案 0 :(得分:1)

''删除self.zipcode。您还说要从zipcode获取form,因此,self未定义,您需要从form变量获取邮政编码

   if request.method == 'POST':
        if form.is_valid()
            zipcode = form.cleaned_data['zipcode']
            nearestzips = PostalCode.objects.distance(PostalCode.objects.get(code=zipcode).location)