这篇文章扩展了error while submitting data in the form django
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”必须是“个人资料”实例。
答案 0 :(得分: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')