LoginSignup
0
1

More than 3 years have passed since last update.

Django form ラジオボタン 選択肢動的に変更方法がわからない。→解決

Last updated at Posted at 2019-09-22

 会社の受付フォームを趣味でごりごり作成しております。POSTの時にラジオボタンの選択肢を動的に変更したい。
 具体的には「form.py」→「開催日選択Form」の「data」を「views.py」→「状況View」→「受験者リストView」→「def get(self, request):」の「開催日_年」に変更したい(data=開催日_年)。ですが、わかりません。どなたか様かご教授よろしくお願いします。
→解決しました。「form」に引数が追加することができ、「form」内で変更することができました。
参考URL:https://note.crohaco.net/2015/django-form/

veiws.py
def post(self, request):        
        試験日 = request.POST.get('day')    #試験日        
        self.params['exam'] = 試験日Form(日選択=試験日)
                                    #↑日選択が引数として追加      
    )
form.py
class 試験日Form(forms.Form):
    day = forms.ChoiceField(choices=[],required=False,widget=forms.RadioSelect)
    #↑「choices=[]」は下のコードの中の「self.fields['day'].choices」で生成する。
  
       ##---コード省略---##

    def __init__(self,日選択, **kwargs):
        super(試験日Form, self).__init__(**kwargs)
   #↑「def__init__.... super(....  」はよくわりませんww
     ##---コード省略---##
         self.fields['day'].choices=開催日.objects.filter(開催2日目__gte=start,開催2日目__lte=end).order_by('開催2日目').values_list('id','開催2日目')  

         ##---コード省略---##
form.py
class 開催日選択Form(forms.Form):
    data = 開催日.objects.all().values_list('id','開催2日目')
    evc = forms.ChoiceField(
       label='開催日', choices=data,required=False,
       widget=forms.RadioSelect       
    )
views.py

class 受験者リストView(TemplateView):
    def __init__(self):
        self.params = {
            'eventdate' : 開催日選択Form,                                  
        }
    def post(self, request):
        今年=datetime.date.today().year
        start=datetime.datetime(今年, 1, 1,)
        end=datetime.datetime(今年+1, 3, 31,)
        開催日_年=開催日.objects.filter(開催2日目__gte=start,開催2日目__lte=end).values_list('id','開催2日目')

        開催日選択Form.data=開催日_年    
    #↑ここで「form.py」の「開催日選択Form」の「data」の値を
       #「data=開催日_年」に変更したい。
       #これではうまくいきませんでした。
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1