2016-10-12 8 views
1

たとえば、名前と仕事経験(テキストエリア)の2つの属性を持つPersonモデルがあります。修正されたフィールドをDjangoのフォームに表示する方法は?

私はPersonを作成するためのフォームを持っており、TextField(仕事の経験)用のカスタム検証ルールを作成しました。

TextFieldに関連したエラー(職務経験)を表示したいのですが(私はすでに行っています) TextFieldの内容を表示したいのですが、修正しました。 。ユーザーがフォームを送信すると

Work at McDonalds for 2 years, Study Customer Service for 1 year 

は、これが原因でTextFieldに私のカスタム検証規則の無効になり *:それを表示する例えば

を、ここでは、ユーザが入力したいくつかの仕事の経験があります。 *訂正された入力をフォームページに表示したいだけです(Tちょうど下の例のためのパラグラフとしてextFieldけど)、**だけユーザーに自分の補正された入力を参照する方法を与えるためには:

- Work at McDonalds for 2 years 
- Study Customer Service for 1 year 

私は、フォームページで補正された入力を表示するために、これを試してみました:

class PersonCreate(CreateView): 
    model = Person 
    form_class = PersonForm 
    success_url = 'my_site/success.html' 
    def get_context_data(self, **kwargs): 
    # I have an error with the following line : 'NoneType' object has no attribute 'job_experiences' 
    job_experiences = self.object.job_experiences 
    #here is my code to get the formatted text 
    formatted_job_experiences = my_code(job_experiences) 
    context = super(PersonCreate, self).get_context_data(**kwargs) 
    context['formatted_job_experiences'] = formatted_job_experiences 
    return context 

答えて

0

オブジェクトを作成する際にインスタンスは存在しません。フォームフィールドの値はdata dictにあります。あなたの答えのための

def get_context_data(self, **kwargs): 
    # on initial GET data will be empty, thus the default value 
    job_experiences = kwargs['form'].data.get('job_experiences', '') 
    return super(PersonCreate, self).get_context_data(
     formatted_job_experiences=my_code(job_experiences), 
     **kwargs 
    ) 
+0

おかげで、私は今、次のエラーがあります:これを試してみてくださいKeyError例外my_site /人//'フォームの – Reveclair

+0

を追加CreateView' 'における基本実装は常にフォーム'とget_context_data' '呼び出す/時= form'、質問に表示されていない方法でこれを上書きしましたか? –

関連する問題