Django ForeignKey 中的表单控件

Form control in Django ForeignKey

我的模特:

class Faculty(models.Model):
    name = models.CharField(max_length=30)


class Program(models.Model):
    name = models.CharField(max_length=30)
    faculty = models.ForeignKey(Faculty)


class Student(models.Model):
    name = models.CharField(max_length=30)
    faculty = models.ForeignKey(Faculty)
    program = models.ForeignKey(Program)

让我有两个教员:

我每个都有 3 个程序:

我想要的是当学生填写表格时,他们可以 Select 教师和课程。所以当用户 select Science as Faculty。那么如何让 django 只提供 selected 学院的程序?这意味着当用户 select 教师领域的科学然后在程序领域计算机、软件和民用应该被显示。

可能吗?那怎么办我想我提出了一个明确的问题。 (很容易理解我的意思)

更新:- @thameem

询问

forms.py

class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = {'name','faculty','program','roll','gender','contact','address','about',}

模板:

<div class="contener">
<form method="post" enctype="multipart/form-data">{% csrf_token %}
            {{form.as_p}}

            <input type="submit" value="Save">
</form>
</div>

urls.py

urlpatterns = [
url(r'^addprofile/$', addprofile, name='addprofile'),
]

您可以使用 ajax

来完成

将此代码放入您的模板中

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>

    $(document).ready(function(){

        $("select[name='faculty']").change(function(){
            var value =  $(this).val();
            var pselect = $("select[name='program']");

            $.ajax({
                method:"get",
                dataType:"json",
                url:'{% url 'profile:suggest_program' %}',
                data:{
                'faculty':value
                },
                success:function(data){
                    pselect.empty();
                    $.each(data, function(index, value){
                        pselect.append("<option value='"+value.pk+"'>"+value.name+"</option>");
                    });
                },

            });
        });

    });
    </script>

在你的 views.py

from django.http import JsonResponse


def suggest_program(request):
    faculty = request.GET.get("faculty")
    programs = [{"data":"nothing found"}]
    if faculty:
        programs = Program.objects.filter(faculty_id=faculty
                                            ).values("pk", "name")
        programs = list(programs)
    return JsonResponse(programs, safe=False)

urls.py

url(r'^suggest-program/$', views.suggest_program, name="suggest_program"),