使用CreateView后,在另一个模型中自动创建记录

时间:2016-01-08 21:27:47

标签: python django

我有两个模型(确定3个模型,因为AssignedAsset是资产的子类),一个跟踪资产,另一个跟踪资产所有者的历史记录。当我使用CreatView创建新资产时,我想自动创建一个历史记录。

models.py

class Asset(models.Model):
    make = models.CharField(max_length=100)
    model = models.CharField(max_length=100)
    serial_number = models.CharField(max_length=100)
    po = models.ForeignKey('purchaseorders.PurchaseOrder', default=None, blank=True, null=True)
    location = models.ForeignKey('locations.Plant')
    slug = models.SlugField(blank=True, unique=True)

    def __str__(self):
        return self.slug

    def save(self):
        forslug = "{0.make}-{0.model}-{0.serial_number}".format(self)
        self.slug = slugify(forslug)
        super(Asset, self).save()

class AssignedAsset(Asset):

    user = models.ForeignKey(User)

    def __str__(self):
        return self.slug

class AssignedHistory(models.Model):
     assset = models.ForeignKey('Asset')
     user = models.ForeignKey(User)
     date = models.DateField()
     slug = models.SlugField(blank=True, unique=True)

     def __str__(self):
         return self.slug

    def save(self):
        forslug = "{0.asset}-{0.date}".format(self)
        self.slug = slugify(forslug)
        super(AssignedHistory, self).save()

以下是我的观点。

class NewAssignedAsset(CreateView):
    form_class = AssignedAssetForm
    template_name = 'createassignedasset.html'
    success_url = '/assets'

我的forms.py

class AssignedAssetForm(forms.ModelForm):

    class Meta:
        model = AssignedAsset
        fields = ['make', 'model', 'serial_number', 'location', 'user', 'po']

     def __init__(self, *args, **kwargs):
        super(AssignedAssetForm, self).__init__(*args, **kwargs)
        #Filter out PO's that have packingslips (otherwise you will quickly have a ridicously big drop-down of every PO in the system)
        self.fields['po'] = forms.ModelChoiceField(required=False, queryset=PurchaseOrder.objects.filter(packing_slip=''))

我想也许我可以在获得成功网址时创建历史记录,所以我在我的视图中尝试了这个:

import time

def today():
    return time.strftime ("%m/%d/%Y")

class NewAssignedAsset(CreateView):
    form_class = AssignedAssetForm
    template_name = 'createassignedasset.html'
    def get_success_url(self):
        history = AssignedHistory.objects.create(assset=self.object, user=self.object.user, date=today())
        return '/assets'

但这引发了一个TypeError:

save()得到了一个意外的关键字参数' force_insert'

任何可以指向正确方向的东西都会受到赞赏。

2 个答案:

答案 0 :(得分:2)

您应该将Asset.save()AssignedHistory.save()写为:

def save(self, **kwargs):
   ...
   super(YourModel, self).save(**kwargs)
   ...

请注意**kwargs。它们允许您接受可选参数(以及Model.save() has a few)。

答案 1 :(得分:2)

您可以在多个级别(数据库级别,表单级别)执行此操作。

在您的情况下,我会说您只需要覆盖save()的{​​{1}}。 (假设您在表单的上下文中设置AssignedAssetForm

user

**我不确定上下文部分,您可能需要研究如何在表单中使用def save(self, *args, **kwargs): assigned_asset = super(AssignedAssetForm, self).save(*args, **kwargs) user = self.context.get(u'user') if user: assigned_asset_history = AssignedHistory(asset=assigned_asset, user=user, date=datetime.date.today()) assigned_asset_history.save() return assigned_asset