django查看完整性错误
Posted
技术标签:
【中文标题】django查看完整性错误【英文标题】:django view integrityError 【发布时间】:2013-03-13 16:44:43 【问题描述】:我需要有关以下代码的帮助。我想我快到了。我正在尝试创建一个用于编辑和添加新对象的视图。但是,在保存时,我收到下面列出的错误。
我想知道是否有人可以告诉我哪里出错了?
谢谢。
view.py
def group(request, id=None):
if id:
group = get_object_or_404(Groups, pk=id)
else:
group = Groups()
# If we had a POST then get the request post values.
if request.method == 'POST':
form = GroupFrom(request.POST)
# Check we have valid data
if form.is_valid():
group = Groups(
name=form.cleaned_data['name'],
description=form.cleaned_data['description'],
active=form.cleaned_data['active'],
user=request.user
)
group.save()
else:
form = GroupFrom(instance=group)
context = 'form': form
return render_to_response('contacts/group.html', context, context_instance=RequestContext(request))
urls.py
(r'^group/new/$', 'contacts.views.group', , 'group_new'),
(r'^group/edit/(?P<id>\d+)/$', 'contacts.views.group', , 'group_edit'),
model.py
class Groups(models.Model):
"""
Stores all groups.
"""
name = models.CharField(max_length=60)
description = models.TextField(max_length=250)
active = models.BooleanField()
modified = models.DateTimeField(null=True, auto_now=True, help_text="Shows when object was modified.")
created = models.DateTimeField(auto_now_add=True, help_text="Shows when object was created.")
#FK
user = models.ForeignKey(User, unique=True, related_name="user")
def __unicode__(self):
return self.name
错误
/contacts/group/edit/1/ 处的 IntegrityError (1062,“密钥“user_id”的重复条目“1”)
更新: 所以这就是我现在所拥有的,它可以工作,但只能在编辑时而不是添加。添加时我仍然收到相同的错误:
def group(request, id=None):
if id:
# If we have an id try and get it and populate instance.
group = get_object_or_404(Groups, pk=id)
# If we have an instance check that it belongs to the login.
if group.user != request.user:
return HttpResponseForbidden()
else:
# If we don't have an id get the instance (which is blank here) and populate it with the user.
group = Groups(user=request.user)
# If we had a POST then get the request post values.
if request.method == 'POST':
# Populate the form with the instance.
form = GroupFrom(request.POST, instance=group)
# Check we have valid data before saving trying to save.
if form.is_valid():
group.save()
messages.add_message(request, messages.SUCCESS, 'Successfully Created/Updated Group')
else:
# Populate from at this point group with either be blank or have values.
form = GroupFrom(instance=group)
context = 'form': form
return render_to_response('contacts/group.html', context, context_instance=RequestContext(request))
【问题讨论】:
【参考方案1】:你可以大大缩短你的代码:
class GroupForm(forms.ModelForm):
class Meta:
model = Group
def __init__(self, *args, **kwargs)
user = kwargs.pop('user')
super(GroupForm, self).__init__(*args, **kwargs)
self.user = user
def group(request, id=None):
if id:
instance = get_object_or_404(Groups, pk=id)
else:
instance = None
form = GroupFrom(request.POST or None, instance=instance, user=request.user)
if request.method == 'POST':
if form.is_valid():
group = form.save()
return render_to_response('contacts/group.html', 'form': form,
context_instance=RequestContext(request))
GroupForm 的__init__
的简单覆盖允许您从请求中提交用户,从而使您不必手动分配视图中的值。表单初始化中的 or
语句允许您在一个地方进行实例化,而不是在 GET 请求时使用单独的方法。
您的用户外键属性上有unique=True
。在视图中手动分配它不会捕获任何验证。在实例化表单时分配属性应该会在表单提交之前触发验证错误。
【讨论】:
是的,它是唯一的=True,我更新了我的问题以纳入您的想法(一些什么),并且效果很好。谢谢布兰登。【参考方案2】:尝试替换
group = Groups(
name=form.cleaned_data['name'],
description=form.cleaned_data['description'],
active=form.cleaned_data['active'],
user=request.user
)
作者:
group.name=form.cleaned_data['name']
group.description=form.cleaned_data['description']
group.active=form.cleaned_data['active']
group.user=request.user
您的 group = Groups(
只是删除了 group 变量的先前值。
【讨论】:
我已更新以反映(请参阅问题更新),但在保存新对象时仍然出现错误。以上是关于django查看完整性错误的主要内容,如果未能解决你的问题,请参考以下文章
完整性错误:更新或删除违反外键约束。 Django + PostgreSQL
将现有站点更新为新的 Django 1.5 用户模型后 django_admin_log 上的完整性错误