首先,我的英语借口^^
我不明白我如何在django中使用select multiple小部件。 我的意思是,我没有说明哪些文件和功能是必要的。
示例,我有两个类:
class Student(models.Model):
name=models.CharField(max_length=100)
subject=models.ManyToManyField(Subjects)
class Subjects(models.Model):
sub_name=models.CharField(max_length=100)
desc=models.CharField(max_length=100)
现在,我想使用select multiple小部件,那么哪些文件和函数是必需的?
我希望你明白我在问什么^^
Tks:)
答案 0 :(得分:0)
首先,您需要在models.py
中拥有StudentForm
class StudentForm(ModelForm):
subject = forms.ModelMultipleChoiceField(queryset=Subjects.objects.all())
#this would use widget 'SelectMultiple' by default
class Meta:
model = Plan
fields = ['name','subject']
如果你想使用复选框widget:
subject = forms.ModelMultipleChoiceField(queryset=Subjects.objects.all(),widget=CheckboxSelectMultiple())
然后在views.py中:
class StudentFormView(View):
form_class = StudentForm
template_name = 'your_template.html'
def get(self, request):
form = self.form_class()
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('whatever_url_you_like/')
return render(request, self.template_name, {'form': form})
你的urls.py中的添加:
url(r'url_to_your_form^$',StudentFormView.as_view())
在your_template.html中在正文中添加:
<form action="." method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />