下記 どうしても自力解決が難しく、お力添えいただけますよう、よろしくおねがいします。
【やりたいこと】
リレーションされた2つのテーブルにCreateViewにて同時に登録する
【課題点(エラーにより困っていること)】
子テーブルへINSERT処理をする際に、親テーブルで登録した主キーが取得できずにAttributeErrorが発生します。
確認内容をソースコード内でコメントとしています。
【エラーメッセージ】
AttributeError at /quotation/registration/
'RegistrationForm' object has no attribute 'quotation_id'
【form内容(下記print確認内容)】
<tr><th><label for="id_client_id">顧客:</label></th><td><select name="client_id" required id="id_client_id"> <option value="">---------</option> <option value="1" selected>顧客名</option></select></td></tr>
<tr><th><label for="id_username">作成者:</label></th><td><select name="username" required id="id_username"> <option value="">---------</option> <option value="1" selected>aaaa</option></select></td></tr>
<tr><th><label for="id_expiry">見積有効期限:</label></th><td><input type="text" name="expiry" value="ご下命後1ヶ月間" maxlength="255" id="id_expiry"></td></tr> <tr><th><label for="id_recipient">宛名:</label></th><td><input type="text" name="recipient" value="宛名" maxlength="255" id="id_recipient"></td></tr> <tr><th><label for="id_title">件名:</label></th><td><input type="text" name="title" value="件名" maxlength="255" id="id_title"></td></tr> <tr><th><label for="id_delivery_time">納期:</label></th><td><input type="text" name="delivery_time" value="納期" maxlength="255" id="id_delivery_time"></td></tr> <tr><th><label for="id_payment_term">取引条件:</label></th><td><input type="text" name="payment_term" value="取引条件" maxlength="255" id="id_payment_term"></td></tr> <tr><th><label for="id_consumption_tax">消費税額:</label></th><td><input type="number" name="consumption_tax" value="1" required id="id_consumption_tax"></td></tr> <tr><th><label for="id_remark">備考:</label></th><td><textarea name="remark" cols="40" rows="10" id="id_remark"> 備考</textarea></td></tr>
【ソースコード】
【Views.py】 import logging from django.urls import reverse_lazy from django.views import generic from .forms import QuotationsForm, RegistrationForm, Quotations_details_formSet from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from .models import Quotations, Quotations_details from django.db import transaction logger = logging.getLogger(__name__) class RegistrationView(LoginRequiredMixin, generic.CreateView): model = Quotations, Quotations_details template_name = "registration.html" form_class = RegistrationForm form_class_Quotations_details = Quotations_details_formSet success_url = reverse_lazy('quotation:registration') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) Quotations_details_form = self.form_class_Quotations_details(self.request.GET or None) context.update({'Quotations_details_form':Quotations_details_form}) return context def form_valid(self, form): Quotations_details_form = self.form_class_Quotations_details(self.request.POST or None) if Quotations_details_form.is_valid(): with transaction.atomic(): form.save() #【この親テーブルへのinsert処理までは正常に行われています。 公式ドキュメントでは、このタイミングで主キーの設定値を保存していると表記あり(https://djangoproject.jp/doc/ja/1.0/ref/models/instances.html)最新のドキュメントでも同じような実装が確認できました。(https://docs.djangoproject.com/ja/3.1/intro/tutorial02/)】 print(form) #【RegistrationFormでfieldsとして、quotation_idが存在していますが、formの中身を確認すると存在していませんでした。】 Quotations_details_form.insrance.quotation_id = form.quotation_id #【ここでAttributeErrorが発生します。】 Quotations_details_form.save() messages.success(self.request,'登録が完了しました。') logger.info('Inquiry sent by{}'.format(form.cleaned_data['name'])) else: self.form_invalid(form) return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form): messages.error(self.request,'登録ができませんでした。') return super().form_invalid(form)
【models.py】 from django.db import models from client.models import Clients from accounts.models import Users class Quotations_manager(models.Manager): def check_enabled(self): return self.filter(is_enabled=True) class Quotations_details_manager(models.Manager): def check_enabled(self): return self.filter(is_enabled=True) class Quotations(models.Model): quotation_id = models.AutoField(primary_key=True) client_id = models.ForeignKey(Clients, on_delete=models.DO_NOTHING, db_column='client_id') username = models.ForeignKey(Users, on_delete=models.DO_NOTHING, db_column='username') created_datetime = models.DateTimeField(auto_now_add=True) updated_datetime = models.DateTimeField(auto_now=True) expiry = models.CharField(max_length=255, blank=True, null=True, default="ご下命後1ヶ月間") recipient = models.CharField(max_length=255, blank=True, null=True) title = models.CharField(max_length=255, blank=True, null=True) delivery_time = models.CharField(max_length=255, blank=True, null=True) payment_term = models.CharField(max_length=255, blank=True, null=True) consumption_tax = models.IntegerField(default=0) remark = models.TextField(blank=True, null=True) is_active = models.BooleanField(default=True) def __str__(self): return self.name class Meta: verbose_name_plural = "quotations" objects = Quotations_manager() class Quotations_details(models.Model): quotation_id = models.ForeignKey(Quotations, on_delete=models.CASCADE, db_column='quotation_id') item_id = models.AutoField(primary_key=True) merchandise = models.CharField(max_length=255, blank=True, null=True) merchandise_description = models.TextField(blank=True, null=True) quantity = models.IntegerField(default=0) unit = models.CharField(max_length=255, blank=True, null=True) sales_unit_price = models.IntegerField(default=0) purchase_unit_price = models.IntegerField(default=0) def __str__(self): return self.name class Meta: verbose_name_plural = "quotations_details" objects = Quotations_details_manager()
【forms.py】 from django import forms from .models import Quotations, Quotations_details class QuotationsForm(forms.ModelForm): class Meta: model = Quotations fields = '__all__' class Quotations_detailsForm(forms.ModelForm): class Meta: model = Quotations_details fields = '__all__' class RegistrationForm(forms.ModelForm): class Meta: model = Quotations fields = ('quotation_id','client_id','username','expiry','recipient','title','delivery_time','payment_term','consumption_tax','remark') labels={ 'client_id':'顧客', 'username':'作成者', 'expiry':'見積有効期限', 'recipient':'宛名', 'title':'件名', 'delivery_time':'納期', 'payment_term':'取引条件', 'consumption_tax':'消費税額', 'remark':'備考', } Quotations_details_formSet = forms.inlineformset_factory( parent_model = Quotations, model = Quotations_details, fields = '__all__',#('client_id','username','expiry','recipient','title','delivery_time','payment_term','consumption_tax','remark','merchandise','merchandise_description','quantity','unit','sales_unit_price','purchase_unit_price'), extra = 1 )
あなたの回答
tips
プレビュー