我有这个型号:
class Auth(models.Model):
TYPES = (
('agent', 'Agent'),
('broker', 'Broker'),
)
user = models.ForeignKey(User, unique=True)
type = models.CharField(max_length=20, choices=TYPES)
applied = models.BooleanField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object=generic.GenericForeignKey('content_type', 'object_id')
每当我做这样的事情时:
User.objects.create_user(username="myuser", password="myuser", email="myemail.com")
u = User.objects.get(username="myuser")
profile = Auth(user=u)
profile.save()
当然我会收到错误:
IntegrityError: (1048, "Column 'content_type_id' cannot be null")
出于我的目的,我无法避免使用contenttypes,因为Auth是一个Broker和Agent类继承的类,它允许我做多个自定义配置文件。
我想知道是否有一种方式不需要内容类型。
提前致谢!
答案 0 :(得分:4)
content_type = models.ForeignKey(ContentType, null=True, blank=True)
null=True
在数据模型中使其成为可选项,blank=True
使其在使用管理表单时可选(否则您将收到验证错误)。
答案 1 :(得分:1)
要么只为该字段指定default=...
值,要么将其设置为null=True
。
答案 2 :(得分:1)
答案 3 :(得分:1)
好的,我今天用django 1.8来解决同样的问题
models.py:
class Author(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=50)
sig = models.CharField(max_length=150)
up_num = models.IntegerField(default=0)
def __unicode__(self):
return self.user.username
views.py:
def register(request):
if request.method == 'POST':
form = registerFrom(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
name = form.cleaned_data['name']
sig = form.cleaned_data['sig']
u = User.objects.create_user(username, email, password)
add_blog_permission = Permission.objects.create(codename='add_blog')
change_blog_permission = Permission.objects.create(codename='change_blog')
delete_blog_permission = Permission.objects.create(codename='delete_blog')
add_comment_permission = Permission.objects.create(codename='add_comment')
add_message_permission = Permission.objects.create(codename='add_message')
delete_message_permission = Permission.objects.create(codename='delete_message')
u.user_permissions.add(add_blog_permission, change_blog_permission, delete_blog_permission, add_comment_permission, add_message_permission, delete_message_permission)
Author.objects.create(user=u, name=name, sig=sig)
return HttpResponseRedirect(reverse('login', args=()))
form = registerFrom()
return render(request, 'register.html', {'form': form})
在运行服务器后的注册页面上,提交数据时:
IntegrityError: (1048, "Column 'content_type_id' cannot be null")
最后,我发现我的代码中存在错误:
add_blog_permission = Permission.objects.create(codename='add_blog')
应该是:
add_blog_permission = Permission.objects.get(codename='add_blog')