首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法在Django中更新类模型

无法在Django中更新类模型
EN

Stack Overflow用户
提问于 2016-02-24 11:19:46
回答 3查看 209关注 0票数 1

这是我关于堆栈溢出的第一篇文章,所以请让我知道我是否可以改进我提出问题的方式,以便将来参考。

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

代码语言:javascript
运行
复制
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已存在”。这是正确的。我并不是要添加新课程,而是要将user对象添加到课程对象中。

代码语言:javascript
运行
复制
class ClassForm(forms.ModelForm):

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

这是views.py。

代码语言:javascript
运行
复制
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,在过去的几天里我一直在尝试修复这个问题。谢谢!

EN

回答 3

Stack Overflow用户

发布于 2016-02-24 12:50:31

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

代码语言:javascript
运行
复制
instance = Class.objects.get(some parameters here)
form = ClassForm(instance=instance)
票数 1
EN

Stack Overflow用户

发布于 2017-04-29 18:52:52

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

代码语言:javascript
运行
复制
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的新手,我不确定这就是你要找的。

票数 1
EN

Stack Overflow用户

发布于 2017-04-29 03:26:47

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

你的代码

代码语言:javascript
运行
复制
form = ClassForm(request.POST or None)

替换为此代码

代码语言:javascript
运行
复制
form = ClassForm(request.POST or None, instance=request.user)

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

代码语言:javascript
运行
复制
data = {
    'callNumber': user.callNumber,
    '**extra_fields**': user.**extra_fields**,
}
form = ClassForm(request.POST or None, instance=request.user, initial=data)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35592603

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档