如何使用Django在Databse中使用复选框值存储许多字段

时间:2019-04-20 14:59:18

标签: django many-to-many

使用此代码我想将多个课程存储到学生表中,但是此代码不起作用,也不会引发任何错误也不会保存任何数据。主要问题是单击提交按钮时提交按钮不执行任何操作根本没有加载提交按钮。我该如何解决? 我认为问题出在add_student.html模板中。当我返回form.error时,它抛出了航向。我是否需要更改任何内容?但是我想保持这样的设计

  

models.py

class Course(models.Model):
    title = models.CharField(max_length=250)
    basic_price = models.CharField(max_length=100)
    advanced_price = models.CharField(max_length=100)
    basic_duration = models.CharField(max_length=50)
    advanced_duration = models.CharField(max_length=50)

    def __str__(self):
        return self.title


class Student(models.Model):
    name = models.CharField(max_length=100)
    course = models.ManyToManyField(Course)
    address = models.CharField(max_length=200)
    email = models.EmailField()
    phone = models.CharField(max_length=15)
    image = models.ImageField(upload_to='Students',blank=True)
    joined_date = models.DateField()

    def __str__(self):
        return self.name
  

views.py

def addstudent(request):
    courses = Course.objects.all()
    if request.method == 'POST':
        form = AddStudentForm(request.POST,request.FILES)
        if form.is_valid():
            student = form.save()
            student.save()
            # student.course.set(courses)
            messages.success(request, 'student saved.')
            return redirect('students:add_student')
        else:
            return HttpResponse(form.errors) # it returns course.i think the problem is while saving the course

    else:
        form = AddStudentForm()
    return render(request,'students/add_student.html',{'form':form,'courses':courses})
  

forms.py

class AddStudentForm(forms.ModelForm):
    course = forms.ModelMultipleChoiceField( queryset=Course.objects.all(), widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = Student
        fields = ['name','course','email','address','phone','image','joined_date']
  

add_student.html

 <form action="{% url 'students:add_student' %}"
 method="post" enctype="multipart/form-data">
                        {% csrf_token %}
                        <div class="form-group">
                            <h5>Full Name <span class="text-danger">*</span></h5>
                            <div class="controls">
                                <input type="text" name="name" class="form-control" required data-validation-required-message="This field is required"> </div>
                        </div>
                     <div class="form-group">
                       <h5>Courses <span class="text-danger">*</span></h5>
                       <div class="controls">
                         {% for course in courses %}
                         <input name ="course" type="checkbox" id="{{course.title}}" required value="{{course.id}}">
                         <label for="{{course.title}}">{{course.title}}</label>
                         {% endfor %}
                       </div>
                     </div>
                        <div class="form-group">
                            <h5>Address<span class="text-danger">*</span></h5>
                            <div class="controls">
                                <input type="text" name="address" class="form-control" required data-validation-required-message="This field is required"> </div>
                        </div>
                        <div class="form-group">
                            <h5>Phone Number <span class="text-danger">*</span></h5>
                            <div class="controls">
                                <input type="text" name="phone" data-validation-required-message="This field is required" class="form-control" required> </div>
                        </div>
                        <div class="form-group">
                            <h5>Email <span class="text-danger">*</span></h5>
                            <div class="controls">
                                <input type="email" name="email"  data-validation-required-message="This field is required" class="form-control" required> </div>
                        </div>
                          <div class="form-group">
                            <h5>Joined Date <span class="text-danger">*</span></h5>
                            <div class="controls">
                                <input type="date" name="joined_date" data-validation-required-message="This field is required" class="form-control" required> </div>
                        </div>
                        <div class="form-group">
                            <h5>Image <span class="text-danger">*</span></h5>
                            <div class="controls">
                                <input type="file" name="image" class="form-control" > </div>
                        </div>
                        <div class="text-xs-right">
                            <button type="submit" class="btn btn-info">Submit</button>
                        </div>
                    </form>

2 个答案:

答案 0 :(得分:0)

我建议此解决方案:

courses = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset= Course.objects.all())

views.py

if form.is_valid():
    student = form.save(commit=False)
    courses = form.cleaned_data['courses']
    student.course = courses
    student.save()

ps。最好将m2m字段命名为复数形式: courses = models.ManyToManyField(Course)

这是我对模板的意思: 在 add_student.html

  1. 注释掉整个<form>块并将其替换为Django的{{ form }},并查看其渲染方式
  2. 您有一个在上下文中传递给模板的课程的查询集。尝试从以下位置进行更改:

                    {% for course in courses %}
                     <input name ="course" type="checkbox" id="{{course.title}}" required value="{{course.title}}">
                     <label for="{{course.title}}">{{course.title}}</label>
                     {% endfor %}
    

只是:

{{ form.cource }}

答案 1 :(得分:0)

尝试基于类的视图

class CreateStudent(CreateView):
    model = Student
    form_class = AddStudentForm
    template_name = "add_student.html"