【发布时间】:2018-04-03 04:50:59
【问题描述】:
在这里使用 Django 的新手。我正在尝试创建一个将数据保存到数据库的 DJango 表单。为此,我使用CreateView
当调用要“工作”的 URL 时,我将其设置如下(因此,也传递了一个参数)
url(r'^owner/contacts/add/(?P<tenantid>[0-9]+)/$', views.MstrstoreheadcontactCreateView.as_view(), name='owner-contact-add'),
问题:
尝试将数据保存到数据库时,我收到一个错误,似乎是由于某些字段设置不正确
我得到的确切错误信息是:
上述异常(ORA-02291:完整性约束 (ORAAPPS.SYS_C009216)违反 - 未找到父键)是直接 原因
这是模型的定义方式:
class Mstrstoreheadcontact(models.Model):
tenantid = models.ForeignKey('Mstrauthowner', models.DO_NOTHING, db_column='tenantid', blank=True, null=True)
contactid = models.BigIntegerField(primary_key=True)
genderid = models.BigIntegerField(blank=True, null=True)
firstname = models.CharField(max_length=20, blank=True, null=True)
lastname = models.CharField(max_length=20, blank=True, null=True)
officephoneno = models.CharField(max_length=20, blank=True, null=True)
cellphoneno = models.CharField(max_length=20, blank=True, null=True)
class Meta:
managed = False
db_table = 'MstrStoreHeadContact'
它是使用inspectdb 选项创建的(用于为数据库中已存在的表自动生成类)
这就是在 views.py 中定义 CreateView 的方式
class MstrstoreheadcontactCreateView( CreateView ):
model = Mstrstoreheadcontact
fields = [ 'firstname', 'lastname', 'officephoneno', 'cellphoneno']
def form_valid(self, form):
self.kwargs['tenantid'] = 10
# returning rendered page
super(MstrstoreheadcontactCreateView, self).form_valid(form)
return render(self.request, self.template_name,
self.get_context_data(form=form))
def get_context_data(self, **kwargs):
ctx = super(MstrstoreheadcontactCreateView, self).get_context_data(**kwargs)
ctx['tenantid'] = self.kwargs['tenantid']
return ctx
我的理解是
用“字段”定义的属性是要在表单上看到的属性。然而,在执行“保存”时,其他字段看起来好像被忽略了(如错误日志中所示)。
现在,self.kwargs['tenantid'] = 10 正在CreateView 代码中手动设置。我该如何解决这个问题,以便它采用与 URL 一起传递的值。为什么在插入时字段看起来好像设置为无?
更新
@dirkgroten - 感谢您的回复!我按照说明添加了该功能。这是我得到的错误。
TypeError at /masterdata/owner/contacts/add/10/ __init__() got an unexpected keyword argument 'tenantid'
Request Method: GET
Request URL: http://127.0.0.1:8000/masterdata/owner/contacts/add/10/
Django Version: 1.11.1
Exception Type: TypeError
Exception Value: __init__() got an unexpected keyword argument 'tenantid'
我也看到了:Getting __init__() got an unexpected keyword argument 'instance' with CreateView of Django
How to set ForeignKey in CreateView?
我需要创建一个表单来配合视图吗?
【问题讨论】: