2011-02-09 102 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