フォームとフォームセットDjangoのドキュメントを100倍ほど読みました。これを非常に明確にするために、これはおそらく私がsuper()を使用したり、別のクラスからオーバーロード/継承しようとしたのは初めてです(私にとっては大したことです)。
何が起こっていますか?ビューでdjango-model-formsetを作成し、それをテンプレートに渡します。フォームセットが継承しているモデルは、たまたま多対多の関係です。これらの関係を一意にしたいので、ユーザーがフォームを作成していて、誤って同じオブジェクトをManyToManyに選択した場合、検証に失敗するようにします。
このカスタム「BaseModelFormSet」を(ドキュメントを介して)適切に記述したと思いますが、KeyErrorが発生します。これは、cleaned_data ['tech']が見つからないことを示しており、以下にコメントした行の「tech」という単語でKeyErrorが発生しています。
モデル:
class Tech_Onsite(models.Model):
tech = models.ForeignKey(User)
ticket = models.ForeignKey(Ticket)
in_time = models.DateTimeField(blank=False)
out_time = models.DateTimeField(blank=False)
def total_time(self):
return self.out_time - self.in_time
カスタマイズされたBaseModelFormSet:
from django.forms.models import BaseModelFormSet
from django.core.exceptions import ValidationError
class BaseTechOnsiteFormset(BaseModelFormSet):
def clean(self):
""" Checks to make sure there are unique techs present """
super(BaseTechOnsiteFormset, self).clean()
if any(self.errors):
# Don't bother validating enless the rest of the form is valid
return
techs_present = []
for form in self.forms:
tech = form.cleaned_data['tech'] ## KeyError: 'tech' <-
if tech in techs_present:
raise ValidationError("You cannot input multiple times for the same technician. Please make sure you did not select the same technician twice.")
techs_present.append(tech)
ビュー:(概要)
## I am instantiating my view with POST data:
tech_onsite_form = tech_onsite_formset(request.POST, request.FILES)
## I am receiving an error when the script reaches:
if tech_onsite_form.is_valid():
## blah blah blah..