Django ChoiceField

后端 未结 4 1300
醉话见心
醉话见心 2020-12-02 10:42

I\'m trying to solve following issue:

I have a web page that can see only moderators. Fields displayed on this page (after user have registered):
Username, Firs

4条回答
  •  一个人的身影
    2020-12-02 11:10

    If your choices are not pre-decided or they are coming from some other source, you can generate them in your view and pass it to the form .

    Example:

    views.py:

    def my_view(request, interview_pk):
        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})
    

    forms.py

    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', )
    

    template:

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

    No rounds found

    {% endif %}

提交回复
热议问题