How to store many to many fields with checkbox values in databse using django

雨燕双飞 提交于 2020-01-06 05:40:32

问题


With this code i want to store multiple courses to the student table.But this code is not working.Neither it throws any error neither saves any data.The main problem is while clicking submit button the submit button does not perform any action at all.It does not load the submit button.How can i solve this?? I think the problem is in add_student.html template.When i return form.error it throws course.Is there anything i have to change??but i want to keep my design like this

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>

回答1:


I'd recommend this solution:

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

in views.py

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

ps. it's a good practice to name m2m fields in plural: courses = models.ManyToManyField(Course)

here's what I meant with templates: in add_student.html

  1. Comment out whole <form> block and replace it with Django's {{ form }} and see how it'd render
  2. You have a queryset of courses passed in context to template. Try to change it from:

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

to just:

{{ form.cource }}



回答2:


Try a Class Based View

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


来源:https://stackoverflow.com/questions/55774722/how-to-store-many-to-many-fields-with-checkbox-values-in-databse-using-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!