2011-02-08 25 views
0

我想插入數據到數據庫它會拋出錯誤,任何請修復此問題。錯誤,同時提交表格中的數據django

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’必須是一個‘檔案’實例。

如果我刪除

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對於拋出相同錯誤的問題。

回答

2

更新:
看起來像通常爲ForeignKey領域ModelForm生成ModelChoiceField,其中其to_python方法管理從PK值獲取外鍵實例。

CharField.to_python剛剛返回smart_unicode(value)

我會重寫ModelFormclean_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') 
+0

這裏name是PK name = models.CharField(max_length = 50,primary_key = True),它將名稱保存在w_name工作表中。 – sush 2011-02-08 15:12:25