无法在Django中更新类模型

时间:2016-02-24 03:19:46

标签: django django-models django-forms django-templates django-views

这是我关于堆栈溢出的第一篇文章,所以如果我可以改进我的问题以供将来参考,请告诉我。

我正在使用django 1.8编写一个网络应用程序,允许用户在他们的购物车中添加课程。当然。我创建了模型和课程,但我无法将用户添加到views.py中的课程模型 课程模型如下所示。

class Class(models.Model):

    Student_List = models.ManyToManyField(User) # creates a list of different students associated with a single class 
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE) # subject 
    course_ID = models.ForeignKey(CourseID, on_delete=models.CASCADE) # course ID
    callNumber = models.PositiveIntegerField(primary_key=True) # six digit number
    status = models.CharField(max_length = 50) # status open or closed
    # auto_now_add returns creation of object

    timestamp_updated = models.DateTimeField(auto_now_add=False, auto_now = True)


    def __unicode__(self):
       return str(self.callNumber) + "-----" + str(self.status) + "---------" + str(self.Student_List.all())

    # returns of all students for the class
    def get_student_list(self):
        # gets associated class_list of the Student and then gets the unicode for each class in the list
        return "\n".join([p.__unicode__() for p in self.Student_List.all()])

我遇到的问题是,当我尝试在views.py中更新它时,我无法保存表单,因为它尚未验证。当我尝试发送表单时,它表示"此callNumber已经存在。"那是正确的。我没有尝试添加新课程,而是将用户对象添加到课程对象中。

class ClassForm(forms.ModelForm):

class Meta:
    model = Class 
    fields = ['course_ID', 'callNumber']

这是views.py。

def course_adder(request):

    # Raises error if user not logged in
    if not request.user.is_authenticated():
        raise Http404

    title = "Welcome to TechCheck!"


    # finds the list of courses for the current user using a filter on the queryset 
    course_list = Class.objects.filter(Student_List__email = request.user.email, Student_List__username = request.user.username)

    # forms
    form = ClassForm(request.POST or None) # create instance as a form

    if request.method == 'POST':

        if form.is_valid():
            # Never enter this part of the form because form never validates

            callNumber = form.cleaned_data.get("callNumber")
            course = Class.objects.filter(pk = callNumber)
            print course 
            print request.user 
            print course.Student_List.add(request.user)
            print course 
            print "I added a student to the class"



            callNumber = form.cleaned_data.get("callNumber")
            print callNumber, "is the call number"

            course = get_object_or_404(Class, pk=callNumber)
            Class.User.add(request.user)
            # print course
            return redirect('/user-course-status/')

        else:
            title = 'There was a problem entering your\'e data'
            context = {
            "title": title,
            "form": form,
            "course_list": course_list,
            }
            return render(request, 'html/course_adder.html', context)

    else:

        context = {
            "title": "Please enter the callNumber and correct course ID of the class you would like to get notified about.",
            "form": form,
            "course_list": course_list,
            }

        return render(request, 'html/course_adder.html', context)  

任何人都可以帮我帮我提供具体代码吗?我刚刚开始学习Django一个多月了,过去几天我一直试着解决这个问题。谢谢!

3 个答案:

答案 0 :(得分:1)

如果要更新现有数据库条目但不创建新条目,则需要将实例传递给表单。

instance = Class.objects.get(some parameters here)
form = ClassForm(instance=instance)

答案 1 :(得分:1)

我认为你需要在更新多对多字段后添加instance.save()。

if form.is_valid():
        # Never enter this part of the form because form never validates

        callNumber = form.cleaned_data.get("callNumber")
        course = Class.objects.filter(pk = callNumber)
        print course 
        print request.user 
        print course.Student_List.add(request.user)
        print course 
        print "I added a student to the class"



        callNumber = form.cleaned_data.get("callNumber")
        print callNumber, "is the call number"

        course = get_object_or_404(Class, pk=callNumber)
        Class.User.add(request.user)
        # print course
        #I think this should do the trick.
        course.save()
        return redirect('/user-course-status/')

我自己也不喜欢django,我不确定这是你在找什么。

答案 2 :(得分:0)

@ chem1st给出的答案是正确的,请更改以下代码

您的代码

form = ClassForm(request.POST or None)

替换为此代码

form = ClassForm(request.POST or None, instance=request.user)

如果您不想在您的表单中显示该用户的现有数据,请使用此代码

data = {
    'callNumber': user.callNumber,
    '**extra_fields**': user.**extra_fields**,
}
form = ClassForm(request.POST or None, instance=request.user, initial=data)