2016-07-21 56 views
0

属性IBANが一意であるかどうかをチェックするフォームのclean()メソッドをオーバーライドしようとしています。各userにはIBANがあります。なんらかの理由で、djangoによると、フォームにはtrueでない属性IBANはありません。ご覧のとおり、フォームの最初の属性です。例外値: 'フォーム'オブジェクトに属性 '属性'がありません

あなたは何が問題なのですか?

class TranslatorRegistrationForm(forms.Form): 
    IBAN = forms.CharField(max_length=40, required=True) 
    first_name = forms.CharField(max_length=40, required=True) 
    last_name = forms.CharField(max_length=40, required=True) 
    languages = forms.ModelMultipleChoiceField(Language.objects.all(), label='Languages: ', 
               help_text="You can choose from UNKNOWN levels, to gain level, you will be tested") 

    def __init__(self,user,*args, **kwargs): 
     super(TranslatorRegistrationForm, self).__init__(*args, **kwargs) 
     self.user = user 

    def clean(self): 
     cleaned_data = super(TranslatorRegistrationForm, self).clean() 
     if len(UserProfile.objects.filter(IBAN=self.IBAN).exclude(user=self.user))>0: 
      raise ValidationError 
     return cleaned_data 

TRACEBACK:

環境:

Request Method: POST 
Request URL: http://127.0.0.1:8000/register-as-translator/ 

Django Version: 1.8.12 
Python Version: 2.7.10 
Installed Applications: 
('django.contrib.admin', 
'django.contrib.auth', 
'django.contrib.contenttypes', 
'django.contrib.sessions', 
'django.contrib.messages', 
'django.contrib.staticfiles', 
'SolutionsForLanguagesApp', 
'crispy_forms', 
'super_inlines', 
'django_tables2', 
'language_tests', 
'smart_selects', 
'django_extensions', 
'constance', 
'constance.backends.database', 
'nested_inline') 
Installed Middleware: 
('django.contrib.sessions.middleware.SessionMiddleware', 
'django.middleware.common.CommonMiddleware', 
'django.middleware.csrf.CsrfViewMiddleware', 
'django.contrib.auth.middleware.AuthenticationMiddleware', 
'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 
'django.contrib.messages.middleware.MessageMiddleware', 
'django.middleware.clickjacking.XFrameOptionsMiddleware', 
'django.middleware.security.SecurityMiddleware', 
'django.middleware.locale.LocaleMiddleware') 


Traceback: 
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\core\handlers\base.py" in get_response 
    132.      response = wrapped_callback(request, *callback_args, **callback_kwargs) 
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 
    22.     return view_func(request, *args, **kwargs) 
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\SolutionsForLanguagesApp\views.py" in register_as_translator 
    110.   if register_as_translator_form.is_valid(): 
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\forms\forms.py" in is_valid 
    184.   return self.is_bound and not self.errors 
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\forms\forms.py" in errors 
    176.    self.full_clean() 
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\forms\forms.py" in full_clean 
    393.   self._clean_form() 
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\forms\forms.py" in _clean_form 
    417.    cleaned_data = self.clean() 
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\SolutionsForLanguagesApp\forms.py" in clean 
    116.   if len(UserProfile.objects.filter(IBAN=self.IBAN).exclude(user=self.user))>0: 

Exception Type: AttributeError at /register-as-translator/ 
Exception Value: 'TranslatorRegistrationForm' object has no attribute 'IBAN' 
+0

トレースバックを表示できますか? – okuznetsov

+0

[OK]を、質問の末尾にトレースバックを追加しました。 –

+1

'super(TranslatorRegistrationForm、self).clean()'を呼び出すと、 'cleaned_data ['IBAN']'のIBANフィールドの値にアクセスできるはずです。属性 'self.IBAN'は、フィールドの値ではなく、フィールドの定義です。実際、私はこれを答えにします。 – nimasmi

答えて

3

あなたがvalidating the value of a single fieldibanているので、代わりにcleanclean_iban方法を定義する方が良いでしょう:

def clean_iban(self): 
    iban = self.cleaned_data['IBAN'] 
    # Note using exists() is more efficient and pythonic than 'len() > 0' 
    if UserProfile.objects.filter(IBAN=iban).exists(): 
     raise ValidationError('Invalid IBAN') 
    return iban 

clean方法がvalidating fields that depend on each otherのためのものです。 cleanを上書きすると、値がcleaned_dataにあるとはみなせません。

def clean(self): 
    cleaned_data = super(TranslatorRegistrationForm, self).clean() 
    if 'iban' in cleaned_data: 
     iban = cleaned_data['iban'] 
     if len(UserProfile.objects.filter(IBAN=self.IBAN).exclude(user=self.user))>0: 
      raise ValidationError('Invalid IBAN') 
    return cleaned_data 
1

あなたがsuper(TranslatorRegistrationForm, self).clean()呼ばれたら、cleaned_data['IBAN']でIBANフィールドの値にアクセスすることができるはずです。属性self.IBANは、フィールドの値ではなく、フィールドの定義です。

+0

'IBAN'が 'cleaned_data'にあると想定することはできません。 'KeyError'を避けるために、あなたのコードは' if 'IBAN' in cleaned_data'や 'iban = cleaned_data.get( 'IBAN')'のようなものを使うべきです。 – Alasdair

+0

@Alasdair clean()メソッドをオーバーライドするときにIBANがcleaned_dataにないかもしれないと仮定しなければならないし、clean_IBAN()メソッドをオーバーライドする(resp。 (答えによると) –

+0

@ミラノはい、そうです。 ['clean_ '](https://docs.djangoproject.com/en/1.9/ref/forms/validation/#cleaning-a-specific-field-attribute)と['クリーン'](https ://docs.djangoproject.com/en/1.9/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other)を参照してください。 – Alasdair

関連する問題