在CreateView上覆盖Get_Initial时表单上的Django键错误提交

时间:2013-12-14 21:48:37

标签: django forms

我有一个通用的CreateView,它使用一些默认值和其父对象的主键值填充表单。表单填充正确,但在提交时会抛出lumberload_id的KeyError。

调试显示它会覆盖GET和POST上的get_initial方法,这意味着它会尝试访问提交表单时不再存在的lumberload对象。

在我看来,由于它已经完成了GET上的工作,因此无需在帖子上进行get_initial。有没有办法在POST上跳过覆盖get_initial?我试图将覆盖包装在:

中失败了
if request.method == 'GET':

URL:

 url(r'^lumber_load/(?P<pk>\d+)/addlog/$', views.LogDataCreate.as_view(), name='log-data-add'),

查看:     class LogDataCreate(CreateView):         form_class = LogDataForm         model = LogData

    # Set created_by to the current user.
    def form_valid(self, form):
        form.instance.created_by = self.request.user
        return super(LogDataCreate, self).form_valid(form)

    # Set initial values of unit fields.
    def get_initial(self):
        return { 'lumberload': self.kwargs['lumberload_id'],'diameter_unit': '3', 'length_unit': '1' }

    # Return to the load list when done creating a plot.
    def get_success_url(self):
        return reverse('geoapp:lumber_load_list')

型号:

 class LogData(models.Model):
    logdata_id = models.AutoField(primary_key=True)
    lumberload = models.ForeignKey('LumberLoad', blank=True, null=True)
    butt_diameter = models.DecimalField(null=True, max_digits=4, decimal_places=1, blank=True)
    diameter_unit = models.ForeignKey('UnitLengthType', related_name='diameter_unit', null=True)
    log_length = models.DecimalField(null=True, max_digits=3, decimal_places=1, blank=True)
    length_unit = models.ForeignKey('UnitLengthType', related_name='length_unit', null=True)
    speciestreetype = models.ForeignKey('SpeciesTreeType', blank=True, null=True)
    recorded_date = models.DateField(blank=True, null=True)
    created_by = models.ForeignKey(User)
    class Meta:
        db_table = 'log_data'
        ordering = ["logdata_id"]
    def __unicode__(self):
        return unicode(self.logdata_id)

1 个答案:

答案 0 :(得分:1)

以这种方式尝试:

def get_initial(self):
    if self.request.method == 'GET':
        return #initial data
    else:
        return {}