【问题标题】:TypeError: FormListView() missing 1 required positional argument: 'request'类型错误:FormListView() 缺少 1 个必需的位置参数:“请求”
【发布时间】:2020-08-08 17:00:42
【问题描述】:

我是 django 的新手,我有一个问题。 启动服务器时出现如下错误:

File "/home/user/Portfolio/web_project/web_page/urls.py", line 5, in <module>
    path('',            FormListView(),     name = 'home'),
TypeError: FormListView() missing 1 required positional argument: 'request'

我知道我没有正确编写请求,但现在我不明白到底是什么问题。

urls.py:

from django.urls import path
from .views      import FormListView

urlpatterns = [
    path('',            FormListView(),     name = 'home'),
    path('success/',    Success(),          name = 'success')
]

views.py:

from django.core.mail       import send_mail, BadHeaderError
from django.shortcuts       import render, redirect
from django.http            import HttpResponse, HttpResponseRedirect
from .models                import Form
from django.views.generic   import TemplateView

def FormListView(request):
    if request.method == 'GET':
        form = FormListView()
    else:
        form = FormListView(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            surname = form.cleaned_data['surname']
            email = form.cleaned_data['email']
            try:
                send_mail(name, surname, email, ['kirill_popov_000@mail.ru'])
            except BadHeaderError:
                return HttpResponse('Invalid')
            return redirect('success')
    return render(request, "index.html", {'form': form})

def Success(request):
    return HttpResponse('Success!')

【问题讨论】:

    标签: python python-3.x django django-views


    【解决方案1】:

    你不应该调用这个函数,而是传递一个对视图的引用,所以没有括号(()):

    urlpatterns = [
        path('',            FormListView,     name = 'home'),
        path('success/',    Success,          name = 'success')
    ]
    

    注意:函数通常用 snake_case 编写,而不是 PerlCase,因此它是 建议将您的函数重命名为 form_list_view,而不是 FormListView

    【讨论】:

    • 哦,我花了三个小时寻找这个问题......非常感谢!
    猜你喜欢
    • 2020-05-13
    • 2018-05-31
    • 1970-01-01
    • 2021-08-12
    • 2018-01-24
    • 2020-05-07
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多