我一直在使用一個簡單的模型,並且在保存ModelForm數據時遇到了一些麻煩。我想讓用戶創建和編輯數據庫中現有的「組」對象。如果用戶選擇「編輯」現有的組,我希望生成的表單預填充該對象的現有數據。然後,如果他們點擊「保存」,它應該更新任何更改的數據。下面是我使用的模型和視圖。我遇到的問題是form.is_valid()永遠不會返回True。我在這裏做錯了什麼?django ModelForm幫助
模型
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>
非常好的提示,謝謝。現在正在添加新記錄。但是,當我嘗試編輯一個現有的對象,我得到一個django.db.IntegrityError有關名稱是重複的(唯一=真)。它看起來像試圖保存一個全新的記錄,而不是修改現有的記錄。我是否需要在視圖中編寫代碼來檢查它是否已經存在,或者是否有方便的更新函數? – nnachefski 2010-12-11 18:28:29