django - 将用户ID添加到UpdateView

时间:2013-07-26 12:20:32

标签: python django django-forms django-views

我有一些使用ModelForms的UpdateView。每个对象都有一个用户的外键,因此我可以将每个用户的数据分开。当我尝试更新表单上的数据时,我得到:

  

/ FINances / transaction / update / 4中的AttributeError   'module'对象没有'user'属性

创建对象的工作正常。这是给我错误的更新。

其中一个模型和视图如下所示:

# Model
class Transaction(models.Model):
    item_description = models.CharField(max_length=255)
    payment_type = models.CharField(max_length=1, choices=PAYMENT_CHOICES, verbose_name="Payment Type")
    amount = models.DecimalField(max_digits=8, decimal_places=2, verbose_name="Estimated Amount")
    actual_amount = models.DecimalField(max_digits=8, decimal_places=2, verbose_name="Actual Amount")
    due_date = models.DateField(verbose_name="Due Date")
    is_credit = models.BooleanField(verbose_name="Is Asset")
    is_paid = models.BooleanField(verbose_name="Paid/Received?")
    account = models.ForeignKey(Account)
    user = models.ForeignKey(User)

#ModelForm
class TransactionForm(ModelForm):
    class Meta:
        model = Transaction
        fields = ['is_paid', 'item_description', 'due_date', 'amount', 'actual_amount', 'is_credit', 'account',]

#View
class TransactionUpdate(UpdateView):
    model = Transaction
    form_class = TransactionForm
    template_name = 'finances/transaction_update.html'

    def __init__(self, **kwargs):
        self.kwargs = kwargs

    def form_valid(self, form):
        transaction = form.save(commit=False)
        transaction.user = self.request.user
        transaction.save()
        return super(TransactionUpdate, self).form_valid(form)

谢谢,

1 个答案:

答案 0 :(得分:1)

我不认为它正在初始化财产。尝试更改__init__()方法 -

def __init__(self, **kwargs):
    self.kwargs = kwargs
    return super(TransactionUpdate, self).__init__(**kwargs)