2014-02-05 56 views
0

我無法使用由django admin使用的小部件selectMultiple。我的模板上的Form.html僅顯示「提交」按鈕。如果任何人都可以幫助我:)這裏是我的代碼。Django部件SelectMultiple

models.py

class Subjects(models.Model): 
    sub_name=models.CharField(max_length=100) 
    desc=models.CharField(max_length=100) 

class Student(models.Model): 
    name=models.CharField(max_length=100) 
    subject=models.ManyToManyField(Subjects) 

forms.py

class StudentForm(ModelForm): 
    class Meta: 
     model= Student 
     subject=forms.ModelMultipleChoiceField(Subjects.objects.all()) 


class subAddForm(forms.ModelForm): 
    class Meta: 
     model = Subjects 

views.py

def addSub(request): 
    if request.method == "POST": 
     form = subAddForm(request.POST) 
     if form.is_valid(): 
      event, created = Subjects.objects.get_or_create(**form.cleaned_data) 
      return HttpResponseRedirect('/subject/') 
     else: 
      return render_to_response('accueil/accueil.html', {'form': form}, context_instance=RequestContext(request)) 
    else: 
     form = subAddForm() 
     return render(request, 'accueil/accueil.html', {'form': form}) 

def form(request): 
    stud_form=StudentForm() 
    if request.POST: 
     stud_form=StudentForm(request.POST) 
     stud_form.save() 
     return render_to_response("success.html") 
    else: 
     return render_to_response("test/form.html",{' stud_form': stud_form}) 


def subject(request): 
    subject = Subjects.objects.all() 
    return render(request, 'test/subject.html', {'subject': subject}) 

週一模板form.html

{% extends "base.html" %} 

    {% block content %} 

     <script type="text/javascript">window.__admin_media_prefix__ = "/static/admin/";</script> 

    <script type="text/javascript" src="{{ADMIN_MEDIA_PREFIX}}js/core.js"></script> 
    <script type="text/javascript" src="{{ADMIN_MEDIA_PREFIX}}js/getElementsBySelector.js"></script> 
    <script type="text/javascript" src="{{ADMIN_MEDIA_PREFIX}}js/actions.js"></script> 
    <script type="text/javascript" src="{{ADMIN_MEDIA_PREFIX}}js/SelectBox.js"></script> 
    <script type="text/javascript" src="{{ADMIN_MEDIA_PREFIX}}js/SelectFilter2.js"></script> 
    <script type="text/javascript" src="/static/js/jsi18n.js"></script> 
    <div> 
      <div id="overview"> 
    <form action="" method="POST">{% csrf_token %} 
     {{ form.as_p }} 
     <input type="submit" value="Submit" /> 
     </form> 
     </div> 
     </div> 

{% endblock %} 
+0

可能重複[Django的選擇多(HTTP:/ /stackoverflow.com/questions/21565200/django-select-multiple) –

回答

1

如果你想模板學生和主題,然後在views.py的您的學生的功能,「stud_form」應該是「形式」,而不空間

+0

真的我不明白爲什麼它不起作用^^ – Raphael

+0

,因爲'stud_form'沒有在您的模板中使用。您的模板使用{{form.as_p}}而不是{{stud_form.as_p}}。 –

+0

和'stud_form'在開始處有一個空格。這非常危險。使用'stud_form' –