Django 模型表单帮助

发布于 2024-10-06 18:20:43 字数 2924 浏览 0 评论 0原文

我一直在使用一个简单的模型,但在保存 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

VIEW

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/')

及相关模板

Template

<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>

I've been working with a simple model and was having some trouble saving the ModelForm data. I want to allow users to create and edit existing "Group" objects in the database. If the user chooses to "Edit" an existing group, i want the resulting form to be pre-populated with that objects existing data. Then, if they click on "Save", it should update any changed data. The model and view I'm using is below. The problem I'm having is that form.is_valid() never returns True. What am i doing wrong here?

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

VIEW

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/')

and the relevant template

Template

<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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南渊 2024-10-13 18:20:43

尝试使用 django-debug-toolbar。将其附加到您的项目中,您将能够看到表单上正在设置的内容,也许是它未通过验证的原因。启动和运行非常容易,所以请尝试一下。

Try using the django-debug-toolbar. Attach it to your project and you'll be able to see what is being set through on your form, perhaps why it's not passing validation. It's very easy to get up and running so give it a try.

寄与心 2024-10-13 18:20:43

您的项目需要 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),

因为只要您不将另一个字段指定为“primary_key=True”,django 就会为您执行此操作

Does your project require a ModelForm class?

Django will validate your models fine if it knows about the form.

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

A few notes on your code:

The method should come after you declare your model and you can miss out the "unicode":

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

becomes,

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

Also you don't need this:

id = models.AutoField(primary_key=True)

as django does this for you as long as you don't specify another fiels as "primary_key=True"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文