【发布时间】:2010-12-13 15:15:14
【问题描述】:
我有一个 ModelForm,让用户有机会创建新的或编辑现有的“组”对象。如果请求“编辑”现有信息,我会使用现有信息预先填充表单数据。当用户在现有对象上“保存”编辑时,我收到此错误:
“同名的组已经存在。”
我如何告诉 Django “更新”对象而不是尝试创建一个具有相同名称的新对象?
型号
class Analyst(models.Model):
first = models.CharField(max_length=32)
last = models.CharField(max_length=32)
def __unicode__(self):
return "%s, %s" % (self.last, self.first)
class Alias(models.Model):
alias = models.CharField(max_length=32)
def __unicode__(self):
return "%s" % (self.alias)
class Octet(models.Model):
num = models.IntegerField(max_length=3)
def __unicode__(self):
return "%s" % (self.num)
class Group(models.Model):
name = models.CharField(max_length=32, unique=True) #name of the group
octets = models.ManyToManyField(Octet, blank=True) #not required
aliases = models.ManyToManyField(Alias, blank=True) #not required
analyst = models.ForeignKey(Analyst) #analyst assigned to group, required
def __unicode__(self):
return "%s" % (self.name)
查看
class GroupEditForm(ModelForm):
class Meta:
model = Group
def index(request):
if request.method == 'GET':
groups = Group.objects.all().order_by('name')
return render_to_response('groups.html',
{ 'groups': groups, },
context_instance = RequestContext(request),
)
def edit(request):
if request.method == "POST":
form = GroupEditForm(instance = Group.objects.get(name=request.POST['name']))
elif request.method == "GET":
form = GroupEditForm()
return render_to_response('group_edit.html',
{ 'form': form, },
context_instance = RequestContext(request),
)
def save(request):
if request.method == "POST":
form = GroupEditForm(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect('/groups/')
return render_to_response('group_save.html',
{ 'test': form.errors, })
【问题讨论】:
标签: django django-models django-forms