ModelForms を使用している UpdateViews がいくつかあります。各オブジェクトには User への外部キーがあるため、各ユーザーのデータを個別に保持できます。フォームのデータを更新しようとすると、次のようになります。
/finances/transaction/update/4 の AttributeError 'module' オブジェクトに属性 'user' がありません
オブジェクトの作成はうまくいきます。エラーが発生するのは更新です。
そのようなモデルとビューの 1 つが次のようになります。
# 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)
ありがとう、