首页 > 解决方案 > 如何在 Django 表单中使用自定义值填充/填充 ChoiceField

问题描述

我一直在尝试制作用于删除项目的表单,但我不知道如何将字段连接到模型,这就是我正在做的事情:

class StudentForm(forms.ModelForm):
    queryset = Student.objects.filter().values('name')
    choices = [('', var) for var in queryset]
    names = forms.ChoiceField(choices=choices)

    class Meta:
        model = Student
        fields = '__all__'

我使用这个类连接到 Student 模型并使用它的字段,但是我想向它添加一个我自己的字段,即names = forms.ChoiceField(choices=choices),但我想知道的是,我将如何连接这个列出所有名称的字段,例如,制作它以便我可以选择一个对象的名称,然后我可以相应地更改/删除它?

class StudentRegister(generic.FormView):
    template_name = 'students/student_form.html'
    form_class = StudentForm
    success_url = '/'

    def form_valid(self, form):
        form.save(commit=True)
        return super().form_valid(form)

这是我的views.py,如您所见,它会自动设置表单的值,因为这些值已经“绑定”到模型字段,而不是我添加的选择字段。我将如何纠正这一点?

标签: pythondjangodjango-modelsdjango-forms

解决方案


1)使用查询集的方法

class StudentForm(forms.ModelForm):
    name = forms.ChoiceField(queryset=Student.objects.all())

    or

    name = forms.ChoiceField([("%s" % stud['id'], "%s" % stud['name']) for stud in
                       Student.objects.all().values('id', 'name')])


class Student(models.Model):

    # existing fields comes here

    def __str__(self):
        return self.name

2)使用ajax动态加载

class StudentForm(forms.ModelForm):
    name = forms.ChoiceField()


class Student(models.Model):

    # existing fields comes here

    def __str__(self):
        return self.name

使用ajax加载数据

<script>
(function($){

//get your data
function get_data(){
    $("#<id_of_choice_field>").empty();
        $.ajax ({
            type: "POST",
            url: "<url_for_getting_data>",
            data: { "csrfmiddlewaretoken": "{{ csrf_token }}" },
            cache: false,
            success: function(json) {
                if (json) {
                    for (var source in json) {
                       $("#id_of_choice_field").prepend("<option value='"+json[source].id+"'>"+json[source].name+"</option>");
                    }

                }
            }
        });
    $("#id_of_choice_field").prepend("<option value='' selected='selected'>--------------</option>");
}
get_data();

}(django.jQuery));
</script>

AJAX URL 和方法

url(r'^get-all-student/$', get_all_student)

def get_all_student(request):
    """

    :param request:
    :return:
    """
    if request.method == "POST" and request.is_ajax():
        all_student = []
        for student in Student.objects.all().values('id', 'name'):
            all_student.append({'id': student['id'], 'name': student['name']})
        return HttpResponse(json.dumps(all_student), content_type="application/json")
    return HttpResponseNotAllowed(['GET'])

推荐阅读