'django model form clean method with foreign key

I try override clean method for model form with foreign key.

Model:

class Doc(Model):
   name = CharField()
   doc_type = ForeignKey(DictDocType)

Form:

class DocForm(ModelForm):
           
    class Meta:
        model = Doc
        fields = '__all__'
    
    def clean_doc_type(self)
        doc_type_name = self.cleaned_data['doc_type']
    
        try:
            DictDocType.objects.get(name=doc_type_name)
        except DictDocType.DoesNotExist:
            msg = '{0} does not exist in dictdoc {1}.'.format(
                doc_type_name, self.cleaned_data['name'])
            raise ValidationError(msg)
        return name

In the test I get an error:

KeyError: 'name'.

If I remove self.cleaned_data['name'] from msg - I do not get self.cleaned_data['doc_type'].

Where I'm wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source