我有一些使用 ModelForms 的 UpdateView。每个对象都有一个 User 的外键,所以我可以将每个用户的数据分开。当我尝试更新表单上的数据时,我得到:
/finances/transaction/update/4 'module' 对象的 AttributeError 没有属性 '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)
谢谢,