Django Forms: pass parameter to form

后端 未结 3 1467
悲哀的现实
悲哀的现实 2020-12-01 06:02

How do I pass a parameter to my form?

someView()..
    form = StylesForm(data_dict) # I also want to pass in site_id here.

class StylesForm(forms.Form):
             


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 06:55

    This is what worked for me. I was trying to make a custom form . This field in the model is a charfield but I wanted a choice field generated dynamically .

    The Form:

    class AddRatingForRound(forms.ModelForm):
    
        def __init__(self, round_list, *args, **kwargs):
            super(AddRatingForRound, self).__init__(*args, **kwargs)
            self.fields['name'] = forms.ChoiceField(choices=tuple([(name, name) for name in round_list]))
    
        class Meta:
            model = models.RatingSheet
            fields = ('name', )
    

    The Views:

        interview = Interview.objects.get(pk=interview_pk)
        all_rounds = interview.round_set.order_by('created_at')
        all_round_names = [rnd.name for rnd in all_rounds]
        form = forms.AddRatingForRound(all_round_names)
        return render(request, 'add_rating.html', {'form': form, 'interview': interview, 'rounds': all_rounds})
    

    The Template:

    {% csrf_token %} {% if interview %} {{ interview }} {% if rounds %} {{ form.as_p }} {% else %}

    No rounds found

    {% endif %}

提交回复
热议问题