如何在Django中保存多对多字段

时间:2019-04-20 05:42:00

标签: django

我正在尝试从addstudent表单中保存学生,但未在保存学生,而是显示错误消息“表单中的错误”。此代码是否有解决方案。我认为该错误在html模板中。 错误是这样的: / students / add / student /中的AttributeError 'ErrorDict'对象没有属性'status_code' 请求方法:POST 要求网址:http://127.0.0.1:8000/students/add/student/ Django版本:2.1.5 异常类型:AttributeError 异常值:
'ErrorDict'对象没有属性'status_code'

  

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)


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()
  

forms.py

class AddStudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = '__all__'
  

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()
            messages.success(request,'student saved.')
            return redirect('students:add_student')
      #  else:
           # return HttpResponse(form.errors) --> it returns course

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

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>Course <span class="text-danger">*</span></h5>
                        <div class="controls">
                            <select name="course" id="select" required class="form-control">
                                <option value="">Select Your Course</option>
                                {% for course in courses %}
                                <option value="{{course.title}}">{{course.title}}</option>
                                {% endfor %}

                            </select>
                        </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-match-match="password" 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-match-match="password" class="form-control" required> </div>
                    </div>
                      <div class="form-group">
                        <h5>Date <span class="text-danger">*</span></h5>
                        <div class="controls">
                            <input type="date" name="joined_date" data-validation-match-match="password" 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 :(得分:2)

您应该按照注释中的建议输出form.errors的值以发现确切的错误。但是,我看到了两个直接的问题,很可能导致表单验证失败。

首先,由于您的表单包含图像上传,因此必须在模板中将enctype设置为multipart/form-data

<form action="{% url 'students:add_student' %}" method="post" enctype="multipart/form-data">

第二,上载的图像存在于request.FILES中,因此您需要将其传递给表单:

form = AddStudentForm(request.POST, request.FILES)

答案 1 :(得分:0)

保存方法后,您必须保存多对多字段。

if form.is_valid():
        student = form.save(commit=False)
        student.save()
        form.save_m2m()