我无法显示我的复选框结果

时间:2018-06-09 06:18:43

标签: python django

enter image description here  我试图让俱乐部活动注册页面。首先我选择俱乐部,然后页面显示复选框中涉及的学生列表。在我选择学生并提交后,我试图显示所有学生的名单和他们的' atclub'。

但它只显示去了家里。我怎么了ㅠㅠ???请帮帮我..

当我没有选中任何内容并提交时,我试图显示错误消息,但它不起作用。它会导致错误。我该如何解决?请帮帮我.. !!

在views.py中

def register(request, club_id):
    club = get_object_or_404(Club, pk=club_id)
    try:
        students = request.POST.getlist('students[]')
    except(KeyError, Student.DoesNotExist):
        return render(request, 'club/detail.html', {
            'club':club,
            'error_message':"You didn't choose any students.."
        })


    else:
        for studentid in students:
            studentss = get_object_or_404(Student, pk=studentid)
            studentss.atclub = club
        return HttpResponseRedirect(reverse('club:results'), )

def results(request):
    a={'Name':'Club'}

    for students in Student.objects.all():
        a.update({students.student:students.atclub})
    return render(request, 'club/results.html', a)
在results.html中

- 这只显示'转到主页'

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Results</title>
</head>
<body>
<ul>
    {% for student in a %}
        <li>{{student.key}}--{{student.value}}</li>
    {% endfor %}
</ul>
<a href="{% url 'club:index'%}">Go to the Home</a>
</body>
</html>

in detail.html - 使用复选框选择学生

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Registration</title>
</head>
<body>
<h1> {{club.club}}</h1>
{% if error_message %}<p><strong>{{error_message}}</strong></p>{% endif %}

<form action="{% url 'club:register' club.id %}" method="post">
    {%csrf_token%}
    {%for student in club.student_set.all%}
    <input type="checkbox" name="students[]" id="student{{ forloop.counter }}"  value="{{ student.id }}"/>
    <label for="student{{ forloop.counter }}">{{student.student}}</label><br />
    {% endfor %}
    <input type="submit" value="submit">
</form>
</body>
</html>

在models.py中,类Student

class Student(models.Model):
    student = models.CharField(max_length=30)
    clubs = models.ManyToManyField(Club)
    class_s = models.ForeignKey(Class, on_delete=models.CASCADE)
    isfilled = models.BooleanField(default=False)
    atclub = models.CharField(max_length=30, blank=True)

    def __str__(self):
        return self.student

    def atclub(self):
        return self.atclub

在整个views.py

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect,HttpResponse
from django.views import View, generic
from django.urls import reverse
from .models import *

from django.core.exceptions import ObjectDoesNotExist

def home(request):
    return HttpResponse(home.html)
#home.html 연결 및 수정

class IndexView(generic. ListView):
    template_name='club/index.html'
    context_object_name = 'club_list'

    def get_queryset(self):
        return Club.objects.all()

class DetailView(generic.DetailView):
    model = Club
    template_name='club/detail.html'
    def get_queryset(self):
        return Club.objects.all()

def register(request, club_id):
    club = get_object_or_404(Club, pk=club_id)
    try:
        students = request.POST.getlist('students[]')
    except(KeyError, Student.DoesNotExist):
        return render(request, 'club/detail.html', {
            'club':club,
            'error_message':"학생을 선택하지 않았습니다."
        })
    #에러 처리가 잘 안된다. 왜지...웨지...걈자...(현타)(말잇못
    #학생 선택 안하면 ValueError

    else:
        for studentid in students:
            studentss = get_object_or_404(Student, pk=studentid)
            #QuerySet으로 가져온다 -> 객체 소환 X
            studentss.atclub = club
        return HttpResponseRedirect(reverse('club:results'), )

def results(request):
    a={'Name':'Club'}

    for students in Student.objects.all():
        a.update({students.student:students.atclub})
    return render(request, 'club/results.html', a)

1 个答案:

答案 0 :(得分:0)

您可以按以下方式更改视图:

def register(request, club_id):
    club = get_object_or_404(Club, pk=club_id)
    error_message = None
    if request.method == 'POST': # When user submit form
         students = request.POST.getlist('students[]')
         if students:
             for studentid in students:
                 studentss = get_object_or_404(Student, pk=studentid)
                 #QuerySet으로 가져온다 -> 객체 소환 X
                 studentss.atclub = club
                 studentss.save()
                 return HttpResponseRedirect(reverse('club:results'))
         else:
             error_message = "You didn't choose any students.."
             # error_message = '학생을 선택하지 않았습니다.'
    context = {'club':club,'error_message':error_message,}
    return render(request, 'club/detail.html', context)

在结果视图中,您实际上不需要迭代查询集:



def results(request):
    a = Student.objects.all()
    return render(request, 'club/results.html', {'a':a})

最后,在您的模板中,a很容易循环:

{% for student in a %}
    <li>{{student.student}}--{{student.atclub}}</li>
{% endfor %}