【问题标题】:how to save many to many field in django如何在 django 中保存多对多字段
【发布时间】:2019-04-20 05:42:00
【问题描述】:

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

【问题讨论】:

  • 这对我没有帮助
  • 尝试输出form.errors。它将显示问题所在。另外不推荐使用fields='__all__',而是创建一个你想要的字段列表。
  • 感谢您的回复。我现在更新了我的问题。请检查一下。

标签: django


【解决方案1】:

您应该按照 cmets 中的建议输出 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)

【讨论】:

  • 感谢您的回复。现在我已经更新了我的问题和错误。请检查一下
  • 您无法从视图中返回form.errors。您应该从 form.is_valid() 测试中删除整个 else 块。
  • 我认为错误是在保存课程时。我使用了 HttpResponse(form.errors) 并打印出了课程
  • 一旦我在models.py中使用课程作为CharField,它保存数据没有任何错误,但是在我更改为ManytoManyField并迁移之后它给了我错误
  • 我删除了 else 块,现在它既不抛出任何错误也不保存数据
【解决方案2】:

你必须在保存方法后保存多对多字段。

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

【讨论】:

    猜你喜欢
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 2018-09-30
    • 1970-01-01
    • 2023-04-02
    • 2019-10-24
    • 2017-01-17
    相关资源
    最近更新 更多