user11345100
user11345100

Reputation:

how to save many to many field in django

I am trying to save students from addstudent form but it is not saving students and it is displaying error message 'error in form'.Is there any solutions for this code.I think the error is in html template. Error is like this: AttributeError at /students/add/student/ 'ErrorDict' object has no attribute 'status_code' Request Method: POST Request URL: http://127.0.0.1:8000/students/add/student/ Django Version: 2.1.5 Exception Type: AttributeError Exception Value:
'ErrorDict' object has no attribute '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>

Upvotes: 0

Views: 523

Answers (2)

tugrulv
tugrulv

Reputation: 31

You have to save many to many field after save method.

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

Upvotes: 0

Will Keeling
Will Keeling

Reputation: 23054

You should output the value of form.errors as suggested in the comments to discover the exact error. However, I can see two immediate issues that are likely causing form validation to fail.

Firstly, because your form contains an image upload you must set the enctype to multipart/form-data in the template:

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

Second, the uploaded image exists in request.FILES so you need to pass that to the form:

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

Upvotes: 2

Related Questions