Django request.method =='POST'返回false

时间:2018-11-11 16:40:50

标签: javascript django web-applications django-forms django-views

当前正在我的第一个Django Web应用程序上工作,因此仍然很生锈。 尝试创建允许讲师创建新班级的页面,然后将该班级添加到讲师班级列表中。

据我所知,通过阅读教程,我的views.py中的request.method应该返回POST,但当前正在返回GET。

因此,创建的新类永远不会保存到数据库中。

这是我的views.py

def create_class(request):
if request.user.is_lecturer:

    print(" ")
    print("user is lecturer")
    form = classForm()
    print(request.method)
    if request.method == 'POST':
        print("")
        print("request method equals post")
        form = classForm(request.POST)
        if form.is_valid():

            lecturer = LecturerProfile.objects.get(lecturer=request.user)
            subject = Class.objects.get_or_create(class_name=form.cleaned_data["class_name"],
                                                      class_description=form.cleaned_data["class_description"],
                                                      lecturer=lecturer)
            LecturerProfile.Classes.add(subject)
            form.save(commit=True)
            return index(request)
        else:
            print("")
            print(form.errors)

    else:
        print("")
        print("request method fail")
else:
    return HttpResponse("You are not allowed here")

return render(request, 'student_feedback_app/create_class.html', {'form':form})

forms.py

class classForm(forms.ModelForm):
subject = forms.CharField(max_length=40, help_text="Class Name", required=False)
class_description = forms.CharField(max_length=200, required=False, help_text="Class Description")
slug = forms.CharField(widget=forms.HiddenInput(), required=False)

class Meta:
    model = Class
    fields = ('subject', 'class_description',)

我的create_class.html

<!DOCTYPE html>
<html>

<head>
Create a new class

<h1> Create a new class</h1>
</head>

<body>
<div>
    <form id="" method="post" action="/lecturer/classes/">
        {% csrf_token %}
        {% for hidden in form.hidden_fields %}
            {{ hidden }}
        {% endfor %}
        {% for field in form.visible_fields %}
                    <br>
                    {{ field.errors }}
                    {{ field.help_text }}
                    {{ field }}
        {% endfor %}
        <br>
    <input type="submit" name="submit" value="Create Class" /> </form>

</div>
</body>

</html>

我在终端发现的错误是

  

用户是讲师GET

     

请求方法失败

     

[11 / Nov / 2018 16:27:24]“ GET / lecturer / create-class / HTTP / 1.1” 200 923

     

未找到:/lecturer/create-class/js/plugins/jqBootstrapValidation.js

     

[11 / Nov / 2018 16:27:24]“获取/lecturer/create-class/js/plugins/jqBootstrapValidation.js HTTP / 1.1” 404 4369

从错误中看来,这似乎与错误源于Bootstrap有关,尽管我没有使用它。 我什至取出了base_template.html并编写了create_class.html,以防万一来自其中的内容是使用javascript和bootstrap,但得到相同的输出。 任何帮助都非常感谢

0 个答案:

没有答案