次のコードについてサポートが必要です。もうすぐそこにいると思います。新しいオブジェクトの編集と追加の両方の作品を含むビューを作成しようとしています。ただし、保存すると、以下のエラーが発生します。
誰かが私がどこで間違っているのか教えてくれるのだろうか?
ありがとうございました。
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))