django ModelForm“unique = True”

时间:2010-12-13 15:15:15

标签: django django-models django-forms

我有一个ModelForm,我可以让用户有机会创建新的或编辑现有的“Group”对象。如果请求“编辑”现有的,我可以使用现有信息预先填充表单数据。当用户转到“保存”现有对象的编辑时,我收到此错误:

“具有此名称的群组已存在。”

我如何告诉Django“更新”对象而不是尝试创建一个具有相同名称的新对象?

MODEL

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,  })

1 个答案:

答案 0 :(得分:1)

您必须在保存操作中获取extining group对象并将表单绑定到该对象。

def save(request, id):
    if request.method == "POST":
       group = get_object_or_404(Group, pk=id)
       form = GroupEditForm(request.POST, instance=group) # A form bound to the POST data
       if form.is_valid():
          form.save(commit=True)
          return HttpResponseRedirect('/groups/')

    return render_to_response('group_save.html',
                           { 'test': form.errors,  })