python - Django 模型实例未保存但未抛出错误

标签 python django apache django-models django-views

我有一个非常简单的观点:

from models import Item, Tag, Category, User
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

def save_item(request):
    try:
            print request.GET
        i = Item()
        i.user = User.objects.get_or_create(email=request.GET['user_email'][0])
        i.save()

        print i
    except Exception as e:
        print e.message()

    return HttpResponse()

使用这些非常简单的模型:

class User(models.Model):
    email = models.EmailField()

class Item(models.Model):
    category = models.ForeignKey(Category, null=True, blank=True)
    tags = models.ManyToManyField(Tag, null=True, blank=True)
    address = models.CharField(max_length = 512, null=True, blank=True)
    user = models.ForeignKey(User)
    data = models.CharField(max_length = 1024, null=True, blank=True)

打印是我的 error.log 中唯一显示的内容:

[Wed May 16 01:23:40 2012] [error] <QueryDict: {u'website': [u''], u'comment': [u''], u'rating': [u''], u'phone number': [u''], u'address': [u''], u'user_email': [u'cc.emeraldeyes@gmail.com']}>

但是没有创建 Item 模型实例!

我可以在管理员或 shell 中手动创建一个:

ubuntu@ip-10-196-47-228:~/WeShouldServer$ ./manage.py shell
Python 2.7.3 (default, Apr 20 2012, 22:39:59) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from RemoteStorage.models import Item
>>> i = Item()
>>> from RemoteStorage.models import User
>>> i.user = User.objects.get(pk=1)
>>> i.save()
# THIS WORKS

但是试图在 View 中保存一个只是……失败了。默默。为什么??!!!

最佳答案

get_or_create返回元组

 user, created = User.objects.get_or_create(email=request.GET['user_email'][0])

关于python - Django 模型实例未保存但未抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10613198/

相关文章:

php - 在 xampp 上安装 zend 框架

python - 如何知道哪个Python受到pip命令的影响?

django - 使用 pytest 测试 Django Rest 框架序列化程序

apache - Amazon EC2 错误或应用程序错误 - swapon :/dev/sda3: read swap header failed

python - 如何使用 Django-Rest-Framework 序列化用户组

django - 运行测试时导入两次

apache - 如何调试浏览器缓存问题?

python 的 os.getcwd() 随机停止工作

python - 如何在Python 3.5中选择小数点后的第一个数字?

python - 使用 requests.get() 时缺少 Cookie 的某些部分?