我对django很新,我在使用django.contrib.auth.model的Django构建的User模型的扩展子表时遇到了问题。子表是UserProfile,并且继承自User。 (见下面的模型)
我无法弄清楚如何将数据放在这些表中,除了管理站点,这显然不够好。
我将获取我的用户对象并为其分配一些变量,例如u = User.objects.get(username = 'jane_smith'
,然后使用命令up = u.userprofile
尝试访问子表中的数据。我得到以下错误奖励:DoesNotExist: UserProfile matching query does not exist.
我尝试通过终端手动输入数据来解决问题,up = UserProfile(user_ptr = User.objects.get(username = 'jane_smith'), country = 'USA', num_meals_hosted = 0, cook_rating = 5, image = None, zipcode =91011)
后跟up.save()
但是,我得到了以下堆栈跟踪
>>> up.save()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Python/2.6/site-packages/django/db/models/base.py", line 460, in save
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/Library/Python/2.6/site-packages/django/db/models/base.py", line 504, in save_base
self.save_base(cls=parent, origin=org, using=using)
File "/Library/Python/2.6/site-packages/django/db/models/base.py", line 526, in save_base
rows = manager.using(using).filter(pk=pk_val)._update(values)
File "/Library/Python/2.6/site-packages/django/db/models/query.py", line 491, in _update
return query.get_compiler(self.db).execute_sql(None)
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 869, in execute_sql
cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 735, in execute_sql
cursor.execute(sql, params)
File "/Library/Python/2.6/site-packages/django/db/backends/util.py", line 34, in execute
return self.cursor.execute(sql, params)
File "/Library/Python/2.6/site-packages/django/db/backends/mysql/base.py", line 86, in execute
return self.cursor.execute(query, args)
File "build/bdist.macosx-10.6-universal/egg/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "build/bdist.macosx-10.6-universal/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
IntegrityError: (1062, "Duplicate entry '' for key 'username'")
有人帮忙吗?只是想找到一种通过API将数据放入这些表的方法。以下是我的模特。如果需要,很乐意在评论中发布更多信息。
from django.db import models
from django.contrib.auth.models import User
class UserProfile(User):
address = models.CharField(max_length=100, blank=True)
city = models.CharField(max_length = 50, blank=True)
state = models.CharField(max_length = 15, blank=True)
zipcode = models.IntegerField(blank=True)
country = models.CharField(max_length = 50, blank=True)
num_meals_hosted = models.IntegerField()
cook_rating = models.IntegerField()
diet_restrict = models.CharField(max_length = 600, blank=True)
blurb = models.CharField(max_length = 10000, blank=True)
website = models.URLField(blank=True)
image_height = models.IntegerField(blank = True)
image_width = models.IntegerField(blank = True)
def __unicode__(self):
return self.id
答案 0 :(得分:0)