django ModelForm的帮助

时间:2010-12-10 20:46:30

标签: django django-models django-forms

我一直在使用一个简单的模型,但在保存ModelForm数据时遇到了一些麻烦。我想允许用户在数据库中创建和编辑现有的“组”对象。如果用户选择“编辑”现有组,我希望生成的表单预先填充该对象的现有数据。然后,如果他们点击“保存”,它应该更新任何更改的数据。我正在使用的模型和视图如下。我遇到的问题是form.is_valid()永远不会返回True。我在这做错了什么?

MODEL

class Analyst(models.Model):
    def __unicode__(self):
        return unicode("%s, %s"%(self.last, self.first))
    id = models.AutoField(primary_key=True)
    first = models.CharField(max_length=32)
    last = models.CharField(max_length=32)

class Alias(models.Model):
    def __unicode__(self):
        return unicode(self.alias)
    alias = models.CharField(max_length=32)

class Octet(models.Model):
    def __unicode__(self):
        return unicode(self.num)
    num = models.IntegerField(max_length=3)

class Group(models.Model):
    def __unicode__(self):
        return unicode(self.name)
    name = models.CharField(max_length=32, unique=True) #name of the group
    id = models.AutoField(primary_key=True) #primary key
    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

查看

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": #a group was selected and the submit button clicked on the index page
        form = GroupEditForm(instance = Group.objects.get(name=request.POST['name'])) #create a form and pre-populate existing data for that object
    elif request.method == "GET": #the "add new" button was clicked from the index page
        form = GroupEditForm() #create a new form with no data pre-populated

    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()
            return HttpResponseRedirect('/groups/')

和相关模板

模板

<h1>Edit Group Information</h1>
<form method="post" action="/groups/edit/save/">{% csrf_token %}
<div class="edit">
<br></br>
{{form}}
</div>
<br></br>
<input type="submit" value="Save"> 
<a href="/groups/"><input type="button" name="cancel" value="Cancel" /></a>
</form>

2 个答案:

答案 0 :(得分:2)

尝试使用django-debug-toolbar。将它附加到您的项目中,您将能够看到表单上的内容,也许是为什么它没有通过验证。启动和运行非常容易,所以试一试。

答案 1 :(得分:1)

您的项目是否需要ModelForm类?

如果知道表格,Django会验证你的模型。

http://docs.djangoproject.com/en/1.2/topics/forms/modelforms/

关于您的代码的一些注释:

该方法应在您声明模型后出现,并且您可能错过“unicode”:

def __unicode__(self):
    return unicode("%s, %s"%(self.last, self.first))

成为,

def __unicode__(self):
    return "%s, %s" % (self.last, self.first)

你也不需要这个:

id = models.AutoField(primary_key = True)

django为你做这个,只要你没有指定另一个fiels为“primary_key = True”