-1

视图.py

def add_phone(request):
    user=request.user
    try:
        phone = Phone_info.objects.get(user=user.id)
    except Phone_info.DoesNotExist:
        phone = None
    phoneForm = PhoneForm({'user':request.user})
    phone = Phone_info.objects.get(user=request.user)
    phoneForm = PhoneForm(instance=phone)
    if request.method=='POST':
        phoneForm = PhoneForm(request.POST,instance=phone)
        if phoneForm.is_valid():
            phone=phoneForm.save(commit=False)
            phone.save()
            return redirect('/member/contact-list/')

    return render_to_response('incident/add_phone.html',
    {
    'about_menu': True,
    'PhoneForm' :phoneForm
    },
    context_instance=RequestContext(request))

模型.py 是

class Phone_info(models.Model):
    user = models.ForeignKey(User, null=True)
    name1 = models.CharField('Name', max_length=100, null=True, blank=True)
    number1 = models.CharField('Number',max_length=20, null=True, blank=True)
    name2 =  models.CharField('Name', max_length=100, null=True, blank=True)
    number2 = models.CharField('Number', max_length=20, null=True, blank=True)

追溯

Environment:


Request Method: GET
Request URL: http://192.168.100.10/member/add-phone/

Django Version: 1.3.7
Python Version: 2.7.0
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django.contrib.admindocs',
 'django.contrib.humanize',
 'django.contrib.staticfiles',
 'south',
 'collect',
 'incident']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.transaction.TransactionMiddleware',
 'django.middleware.cache.FetchFromCacheMiddleware')

编辑:

Traceback:
File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/root/Projects/ir/incident/views.py" in add_phone
  648.     phone = Phone_info.objects.get(user=request.user)
File "/usr/lib/python2.7/site-packages/django/db/models/manager.py" in get
  132.         return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py" in get
  349.                     % self.model._meta.object_name)

Exception Type: DoesNotExist at /member/add-phone/
Exception Value: Phone_info matching query does not exist.

我无法将数据插入或更新到数据库中,出现以下错误”Phone_info matching query does not exist"

任何人都可以建议我这里出了什么问题。编辑:我更新了回溯。错误在第 6 行。知道会出现什么问题。

4

2 回答 2

1

<Model_name> matching query does not exist意味着它的确切内容。您要查找的记录不存在。因此,首先要确保数据存在。

而且您的代码也有松散的结局-

user=request.user
try:
    # This line is generating error because record doesn't exists[1]
    phone = Phone_info.objects.get(user=user.id)
except Phone_info.DoesNotExist:
    phone = None
phoneForm = PhoneForm({'user':request.user})
# You're making the same query as [1] here, knowing that it might not exist. Redundant, illogical.
phone = Phone_info.objects.get(user=request.user)

我确信您是 django 的新手,但每次都说这些都无济于事。让你的逻辑正确。尝试get(),如果有异常,创建记录。你开始你的PhoneForm三次。数据被覆盖。修复它。

Django 拥有最全面的文档之一。通过它

PS:作为一个额外的提示,让你的编码约定正确。在一个地方,您正在查询Phone_info.objects.get(user=user.id)您刚刚分配的位置user = request.user,就在它旁边,您正在查询Phone_info.objects.get(user=request.user)。不仅您刚刚打破了使用id查询的约定,从前面的行开始,您只是request.user再次使用,尽管您有一个分配它的变量。虽然这两个查询都可以工作,但是在编写代码时必须遵循约定,这使得它以后更易于调试。

于 2013-05-13T11:09:08.833 回答
0

你没有显示你的回溯,所以我们不知道你的错误来自哪里。

但是我会指出你在第二行有一个错误:user未定义,所以user.id总是会失败。你可能的意思是request.user.id。当然,您已经捕获并隐藏了该 try/except 语句中的所有错误,因此您永远不会知道存在名称错误。永远不要那样做。捕获您知道会引发的错误:在这种情况下,它是User.DoesNotExist.

于 2013-05-13T09:12:52.207 回答