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

Why am I getting matching query does not exist?

我收到以下错误:

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)

它返回了正确的邮政编码。我认为这意味着我在原始查询中不恰当地使用了 self.zipcode ?我想我应该使用 self.zipcode 因为基本上视图是针对具有 zipcode 字段的 edit_profile 表单。所以我认为 self.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

self.zipcode 中删除 ''。你还说你想从 form 中获取 zipcode,所以,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)