2011-02-09 97 views
1

這柱延伸的error while submitting data in the form djangoForiegnkey問題提交表單

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) 


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): 
    obj=working() 
    obj.w_name='X' 
    obj.Monday=1 
    obj.Tuesday=2 
    obj.Wednesday =3 
    obj.save() 
    return http.HttpResponse('Added') 

在這裏,我想插入數據直接導入表中,如果人點擊http://127.0.0.1:8000/

但它拋出下面的錯誤有什麼想法?

異常類型:ValueError at/ 異常值:無法分配「u'x'」:「working.w_name」必須是「Profile」實例。

+0

有越來越這裏..感謝您的評論中(http://stackoverflow.com/questions/4934538/error-while-submitting- [錯誤而在Django的形式提交數據]前谷歌這麼多data-in-the-form-django) – akki 2014-01-24 17:25:36

回答

4

我以爲你在說你想要將值注入表單?在這種情況下,很明顯(看它比評論更好),您需要將Profile實例傳遞給您的工作對象,就像我們在其他帖子中以乾淨的方式進行操作一樣。

def index(request): 
    try: 
     profile = Profile.objects.get(pk='X') 
    except Profile.DoesNotExist: 
     assert False # or whatever you wish 
    obj=working() 
    obj.w_name= profile 
    obj.Monday=1 
    obj.Tuesday=2 
    obj.Wednesday =3 
    obj.save() 
    return http.HttpResponse('Added') 
+0

我需要將值插入到工作模型中,使用配置文件名稱作爲FK來w_name,但我越來越working.w_name「必須是」配置文件「實例。 – sush 2011-02-09 04:13:09