我的模特:
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个程序:
而我想要的是当学生填写表格时他们可以选择教师和课程。因此,当用户选择Science as Faculty时。然后如何使django只从选定的教师那里获得课程?这意味着当用户在教师领域选择科学然后在计划领域计算机,软件和民用应该显示。
有可能吗?那怎么样?我想我提出了一个明确的问题。 (很容易理解我的意思)
按<@memeem 的要求更新:
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'),
]
答案 0 :(得分:1)
你可以使用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"),