다음 코드는 도움이 필요합니다. 나는 거의 다 왔다고 생각해. 편집 및 새 개체 추가 작업에 대한보기를 만들려고 해요. 그러나 절약에 나는 아래 나열된 오류가 발생합니다.django보기 integrityError
누군가 내가 잘못 가고있는 것을 보여줄 수 있는지 궁금합니다.
감사합니다.
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
오류
IntegrityError은/연락처/그룹/편집에서/1/ (1062, "중복 항목을 '1'키 'USER_ID'에 대한")는
는 UPDATE : 그래서 이것은 무엇이다 I 지금 가지고 있고, 작동하지만 편집에만 추가하지 마라.
group.name=form.cleaned_data['name']
group.description=form.cleaned_data['description']
group.active=form.cleaned_data['active']
group.user=request.user
귀하의 group = Groups(
그냥 그룹 변수의 이전 값을 삭제한다 :
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))
네, 그것은 독특했습니다 = True, 그리고 당신의 아이디어 (일부)와 t가 완벽하게 작동하도록 내 질문을 업데이트했습니다. Brandon, 고마워. – jason