2010-12-10 15 views
-2

私は単純なモデルで作業していましたが、ModelFormデータを保存する際に問題がありました。私は、ユーザーがデータベース内の既存の "グループ"オブジェクトを作成して編集できるようにしたいと考えています。ユーザーが既存のグループを「編集」することを選択した場合、結果のフォームにそのオブジェクトの既存のデータがあらかじめ設定されていることを確認します。次に、「保存」をクリックすると、変更されたデータが更新されます。私が使っているモデルとビューは以下の通りです。私が持っている問題は、form.is_valid()がTrueを返さないということです。私はここで間違って何をしていますか?django ModelForm help

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

と関連テンプレート

テンプレート

<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

django-debug-toolbarをお試しください。これをプロジェクトにアタッチすると、フォーム上に何が設定されているのか、なぜそれが検証をパスしないのかがわかります。立ち上げて走らせるのはとても簡単ですので、試してみてください。

+0

"primary_key = Trueを" 非常に良いヒントとして別のfielsを指定しないとあなたのためにこれがそうであるように、あなたに感謝。新しいレコードを追加しようとしています。しかし、私は既存のオブジェクトを編集しようとすると、重複している名前についてのdjango.db.IntegrityErrorを取得しています(一意= True)。既存のレコードを変更するのではなく、まったく新しいレコードを保存しようとしているようです。既に存在しているか、または便利な更新機能があるかどうかを確認するために、ビューに何かをコーディングする必要がありますか? – nnachefski

1

あなたのプロジェクトにはModelFormクラスが必要ですか?

Djangoはフォームについて知っていれば、モデルを正常に検証します。

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

あなたのコードにいくつかの注意事項:

、あなたのモデルを宣言し、 "ユニコード" を逃すことができた後、方法は来る必要があります:

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 =真)

Djangoは限り、あなたは

+0

ユニコードを残したり、ユニコードとしてu "でマークすると、あなたの' __unicode__'関数がASCII文字列を返すようになりました。 'self.first'または' self.last'のいずれかにUnicode文字が含まれていると、これは 'UnicodeDecodeError'になります。 –

+0

ヒントありがとう、私はそれを試してみましょう。 – nnachefski

関連する問題