6

当我尝试从数据库更新一些记录时,我遇到了一个小问题。奇怪的是,form.errors如果表单无效(我不明白为什么),它就是空的。

这里有

形式

class PetitionUpdateForm(forms.ModelForm):
  owner = forms.ModelChoiceField(
    label=_('Petition creator'),
    queryset=User.objects.all(),
    widget=forms.HiddenInput()
  )

  class Meta:
    fields = ('title', 'petition_text', 'description',
              'category', 'num_signs', 'date_to', 'owner',)
    model = Petition

模型

class Petition(models.Model):
  PETITION_STATUSES = (
    ('N', _('New petition')), # New one
    ('M', _('Moderation')),   # On moderation
    ('R', _('Rejected')),     # Failed petition
    ('S', _('Success'))       # Succeeded petition
  )

  title = models.CharField(max_length=512)
  slug = models.SlugField(max_length=512, editable=False, blank=True)
  description = models.TextField()
  petition_text = models.TextField(blank=True, null=True)
  petition_picture = models.ImageField(upload_to=get_upload_path, blank=True)
  petitioning = models.ManyToManyField(PetitionTarget, editable=False)
  signs = models.ManyToManyField(User, editable=False, related_name='petition_signs')
  num_signs = models.IntegerField(max_length=11, default=100, blank=True)
  category = models.ForeignKey(Category, blank=True, null=True, related_name='petition_category')
  date_to = models.DateTimeField(blank=True, null=True)

  videos = models.ManyToManyField(Video, editable=False)
  photos = models.ManyToManyField(Photo, editable=False)
  audios = models.ManyToManyField(Audio, editable=False)
  documents = models.ManyToManyField(Document, editable=False)

  created = models.DateTimeField(auto_now_add=True, editable=False)
  changed = models.DateTimeField(auto_now=True, editable=False)
  status = models.CharField(max_length=1, choices=PETITION_STATUSES, default='M', blank=True)
  owner = models.ForeignKey(User, related_name='petition_owner')

  def __unicode__(self):
    return u'{0}: {1}'.format(_('Petition'), self.title)

更新视图

@login_required
@render_to('petition/edit-petition.html')
def update_petition(request, slug):
  p = get_object_or_404(Petition, slug=slug)
  form = PetitionUpdateForm(request.POST or None, instance=p)
  import pdb
  pdb.set_trace()
  if form.is_valid():
    form.save()
    messages.success(request, _('Petition saved'))
  else:
    print form.errors # errors are empty
    messages.success(request, _('Some error happened'))

  return {'form': form, 'petition': p}

我的代码有什么问题?

我已经尝试null为大多数模型字段设置属性,从基于类的视图切换到标准视图,但我无法更新我的记录。

苏丹,

谢谢

4

1 回答 1

12

If there is no POST data, then request.POST or None is None, so the form is unbound.

Unbound forms are always invalid, but do not have any errors.

In your case, you may want to change the else: clause to elif request.POST:

See the docs on bound and unbound forms for more details.

于 2012-07-25T16:06:32.447 回答