0

嗨,我正在更新现有记录,但每次我这样做时,都会说 Truncated incorrect DOUBLE value: 'user1' 我在这里粘贴我的视图和模型。请帮我

模型

class BasicDetails(models.Model):
   username = models.OneToOneField(User)
   name = models.CharField(max_length = 100, verbose_name = "Name")
   sex = models.CharField(max_length = 10, verbose_name = "Sex", choices = GENDER_CHOICES)
   dob = models.DateField(verbose_name = "Date of Birth")

   class Meta:
      db_table = u'wed_basicdetails'
   def __unicode__(self):
         return u'%s' % (self.username)

看法

def editbasicdetails(request):
  if request.method == 'POST':
      username = User.objects.filter(username = request.user)
      instance = get_object_or_404(User, username = username)
      form = EditBasicDetailsForm(request.POST,instance=instance)
      if form.is_valid():
          form.save()
      return HttpResponseRedirect('/myprofile/')
  else:
      form = EditBasicDetailsForm(request.user)
  return shortcuts.render_to_response('editbasicdetails.html',locals(),
                                    context_instance = context.RequestContext(request))

模型形式

class EditBasicDetailsForm(forms.ModelForm):
  def __init__(self,user, *args, **kwargs):
      super(EditBasicDetailsForm, self).__init__(*args, **kwargs)

      userid = User.objects.filter(username = user).values('id')[0].get('id')
      self.fields['username'] = forms.CharField(initial = user,
                                              widget = forms.TextInput(attrs = {'readonly':'readonly'}))
  class Meta:
      model = BasicDetails

在上面的视图中,我没有传递用户名,我只是从中获取用户名值,request.user我不确定我在这个简单的功能上做错了什么。

-维克拉姆

4

1 回答 1

1

该错误可能与表单 wrt 模型的不一致行为有关。因为,数据库将 OneToOneField 存储为整数,将 CharField 存储为 varchar。

您不必重写表单init方法。您可以使用初始参数直接执行此操作。

form = EditBasicDetailsForm(initial = {'username' : request.user)

更新:

在您的视图代码中,我建议您正确使用 HttpResponseRedirect 语句。否则,如果表单有效,它将不会再次显示。

if form.is_valid():
          form.save()
          return HttpResponseRedirect('/myprofile/')
于 2012-12-09T05:55:07.330 回答