django: exclude certain form elements based on a condition

后端 未结 2 1147
闹比i
闹比i 2021-01-18 08:36

I have some form fields that I want to include/exclude based on whether or not a certain condition is met. I know how to include and exclude form elements, but I am having d

2条回答
  •  青春惊慌失措
    2021-01-18 08:58

    You can do what you need by adding your own init where you can pass in the id when you instantiate the form class:

    class ProfileForm(ModelForm):
        def __init__(self, team_id, *args, **kwargs):
            super(ProfileForm, self).__init__(*args, **kwargs)
    
            this_team = Team.objects.get(pk=team_id)
    
            teams = Team.objects.order_by('total_points')
            count = 0
            for team in teams:
                if team.pk == this_team.pk:
                    break
                count += 1
    
            now = datetime.datetime.now().weekday()
            if now >= count:
                # show driver_one, driver_two, driver_three
            else:
                # do not show driver_one, driver_two, driver_three
    
    class Meta:
        model = Team
    
    #views.py
    def my_view(request, team_id):
        profile_form = ProfileForm(team_id, request.POST or None)
        #more code here
    

    Hope that helps you out.

提交回复
热议问题