2017-06-21 13 views
0

私はviews.pyのビューと私のforms.pyのフォームを持っています。 ビューの[]リストを私のフォームのMultipleChoiceFieldに渡す必要があります。ビューからフォームへのリストの受け渡し

これは私のコードですが、私は確かに何か...

多くのおかげ

views.py

def view_favorite(request): 
     media = settings.MEDIA 
     game_logo = settings.GAME_LOGO 
     if request.user.is_authenticated(): 
      if request.method == 'POST' : 
       return render(request, 'favorite.html', locals()) 
      else: 
       favs = FavoriteGames.objects.filter(user_id=request.user.id).values_list('game_id', flat=True) 
       list = [] 
       for fav in favs: 
        game = Games.objects.get(id=fav) 
        list.append((game.id, game.guid, game.title, game.logo, "checked"),) 
        nogame = Games.objects.filter(~Q(id__in=favs)).values_list('id', 'guid', 'title', 'logo') 
       form = GamesEditorForm(list) 

forms.py

class GamesEditorForm(forms.Form): 
    def __init__(self, list, *args, **kwargs): 
     super(GamesEditorForm, self).__init__(*args, **kwargs) 

    favorite_games = forms.MultipleChoiceField(
     required=True, 
     initial=True, 
     widget=forms.CheckboxSelectMultiple(), 
     choices=list, 
     ) 
+0

あなたの問題を正しく理解していれば、フォームに初期データが必要です。最初のデータを含むフォームを作成するには、ビューでform = YourForm(initial = {"form_field":initial_data)を使用してフォームを作成してください。 –

+0

myMultipleChoiceFieldに変数リスト[]を渡すだけです。 – GrandGTO

答えて

0

を欠場あなたを渡すことができます機能のパラメータとして直接データ

あなたは何ができるか

views.py

from .forms import my_func 

def some_func(request): 
    my_list = [1,2,3] 
    my_func(request, my_list) 

forms.py

def my_func(request, my_list): 
    #Do something with my_list 
0

フォームのデフォルトのinitメソッドをオーバーライドし、フォームが作成されたときにすべてのロジックを処理しています。

class YourOwnForm(forms.Form): 
    a_field = forms.IntegerField(
     label="field", 
     widget=forms.HiddenInput()) 

    def __init__(self, your_custom_list=None, *args, **kwargs): 
     """ 
     Intantiation service. 
     This method extends the default instantiation service. 
     """ 
     super(CustomizationForm, self).__init__(*args, **kwargs) 
     if your_custom_list: 
      do stuff... 
     else: 
      error... 

my_form = YourOwnForm(data, your_custom_list=[5,8,9]) 
+0

はい私はあなたの方法を試しましたが、私が思う何かが間違っています。 – GrandGTO

+0

私は 'self.list = list'を '__init__'関数の中に作る必要があると思います。フォーム内の各フィールドの初期化の前にself.listにデータを持たせる必要があるので、 'super()'を呼び出す前にその割り当てを行います –

関連する問題