以django格式提交数据时出错

时间:2011-02-08 14:54:17

标签: django django-forms django-views

我正在尝试将数据插入到数据库中,但它会抛出以下错误,可以解决这个问题。

enter code here

model.py

from django.db import models

# Create your models here.

class Profile(models.Model):
     name = models.CharField(max_length=50, primary_key=True)
     assign = models.CharField(max_length=50)
     doj = models.DateField()

     class Meta:
        db_table= 'profile'


     def __unicode__(self):

       return  u'%s' % (self.name)



class working(models.Model):
   w_name =models.ForeignKey(Profile, db_column='w_name')
   monday =  models.IntegerField(null=True, db_column='monday', blank=True)
   tuesday =  models.IntegerField(null=True, db_column='tuesday', blank=True)
   wednesday =  models.IntegerField(null=True, db_column='wednesday', blank=True)

   class Meta:
        db_table = 'working'



   def __unicode__(self):
      return  u'%s ' % ( self.w_name)

forms.py

from models import *
from django import forms

class WorkingForm(forms.ModelForm):

  def __init__(self,  *args, **kwargs):
        super(WorkingForm, self).__init__(*args, **kwargs)
        self.fields['w_name'] =forms.CharField(initial='x',widget=forms.HiddenInput())

  class Meta:
        model = working
        exclude = ('id')

view.py

# Create your views here.
from forms import *
from django import http
from django.shortcuts import render_to_response, get_object_or_404


def index(request):
  if request.method == "POST":
          form = WorkingForm(request.POST)
          if form.is_valid():
            form.save()
            return http.HttpResponse('Added')
  else:  
    form = WorkingForm()
  return render_to_response('add_workingdays.html',locals())

Error Message:

ValueError at /

Cannot assign "u'x'": "working.w_name" must be a "Profile" instance.

Request Method:     POST
Request URL:    http://127.0.0.1:8000/
Django Version:     1.2.4
Exception Type:     ValueError
Exception Value:    

Cannot assign "u'x'": "working.w_name" must be a "Profile" instance.

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/
Django Version: 1.2.4
Python Version: 2.6.5
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'check']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/core/handlers/base.py" in get_response
  100.                     response = callback(request, *callback_args, **callback_kwargs)
File "/home/xyz/newapp/../newapp/check/views.py" in index
  10.           if form.is_valid():
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/forms/forms.py" in is_valid
  121.         return self.is_bound and not bool(self.errors)
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/forms/forms.py" in _get_errors
  112.             self.full_clean()
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/forms/forms.py" in full_clean
  269.         self._post_clean()
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/forms/models.py" in _post_clean
  320.         self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/forms/models.py" in construct_instance
  51.             f.save_form_data(instance, cleaned_data[f.name])
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/db/models/fields/__init__.py" in save_form_data
  416.         setattr(instance, self.name, data)
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/db/models/fields/related.py" in __set__
  318.                                  self.field.name, self.field.rel.to._meta.object_name))

Exception Type: ValueError at /
Exception Value: Cannot assign "u'x'": "working.w_name" must be a "Profile" instance.

我在两个表之间做了一个外键关系,我试图将数据插入到工作表中,但是不能分配“u'x'”:“working.w_name”必须是“Profile”实例。

如果我删除

def __init__(self,  *args, **kwargs):
    super(WorkingForm, self).__init__(*args, **kwargs)
    self.fields['w_name'] =forms.CharField(initial='x',widget=forms.HiddenInput())

它正常工作,但我想输入隐藏的用户名,但它抛出外键错误

修改

如果出现同样错误的问题,请参阅Foriegnkey issue while submitting the form

1 个答案:

答案 0 :(得分:2)

<强>更新
通常情况下,ForeignKey字段ModelForm生成ModelChoiceField,其to_python方法管理从PK值获取外键实例。

CharField.to_python只返回smart_unicode(value)

我会覆盖ModelForm clean_w_name方法并确保它从您的密钥返回一个Profile对象。

class WorkingForm(forms.ModelForm):

    def __init__(self,  *args, **kwargs):
        super(WorkingForm, self).__init__(*args, **kwargs)
        self.fields['w_name'] =forms.CharField(initial='x',widget=forms.HiddenInput())

    def clean_w_name(self):

        data = self.cleaned_data['w_name']
        try:
            profile = Profile.objects.get(pk=data)
            return profile
        except Profile.DoesNotExist:
            raise forms.ValidationError("Profile doesn't exist")

    class Meta:
        model = working
        exclude = ('id')