【问题标题】:DJango CreateView not setting attributes before data is saved to the DBDJango CreateView 在将数据保存到数据库之前未设置属性
【发布时间】: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?

我需要创建一个表单来配合视图吗?

【问题讨论】:

    标签: python django oracle


    【解决方案1】:

    form_valid() 方法所做的唯一事情就是保存表单。因此,通过设置self.kwargs['tenanted'],您不会对表单进行任何更改。你应该改写get_form_kwargs():

    def get_form_kwargs(self):
        kwargs = super(MyCreateView, self).get_form_kwargs()
        kwargs.update({'tenantid': 10})
        # You also want to add the contactid, since that's the primary key and is 
        # the actual field the database requires.
        kwargs.update({'contactid': ...})
        return kwargs
    

    【讨论】:

    • 感谢您的意见。添加功能后,我得到了一个不同的错误。请参阅帖子的“更新”部分。
    • 将字段 tenantidcontactid 添加到您的字段列表中。
    【解决方案2】:

    进行了以下更改,现在数据可以毫无问题地保存到数据库中。我按照文档中的说明将“get_absolute_url”添加到模型中(以前不存在)

    models.py

    class Mstrstoreheadcontact(models.Model):
      [.. snip ..]
        # as instructed by
        # http://django.readthedocs.io/en/latest/topics/class-based-views/generic-editing.html#model-forms
        def get_absolute_url(self):
            return reverse('masterdata:owner-contact-details', kwargs={'pk': self.contactid}
    

    views.py

    class MstrstoreheadcontactCreateView( CreateView ):
        model = Mstrstoreheadcontact
        fields = [ 'firstname', 'lastname', 'genderid', 'officephoneno', 'cellphoneno']
    
        def form_valid(self, form):
            contact = form.save(commit=False)
            contact.tenantid = Mstrauthowner.objects.get(tenantid=self.kwargs['tenantid'])
            return super(MstrstoreheadcontactCreateView, self).form_valid(form)
    

    urls.py

    urlpatterns = [
        url(r'^owner/(?P<pk>[0-9]+)/contact/details/$', views.MstrstoreheadcontactDetailsView.as_view(), name='owner-contact-details'),
        url(r'^owner/(?P<tenantid>[0-9]+)/contacts/add/$', views.MstrstoreheadcontactCreateView.as_view(),
            name='owner-contact-add'),
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-13
      • 1970-01-01
      • 2012-09-09
      • 2016-11-22
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多