Django:'TypeError:'HttpResponseForbidden'对象不可调用

Posted

技术标签:

【中文标题】Django:\'TypeError:\'HttpResponseForbidden\'对象不可调用【英文标题】:Django: 'TypeError: 'HttpResponseForbidden' object is not callableDjango:'TypeError:'HttpResponseForbidden'对象不可调用 【发布时间】:2021-10-29 19:18:44 【问题描述】:

正在建立一个工作门户。我遇到了标题上的错误。我已经尝试了所有建议的解决方案。没有人能解决我的问题。请协助。过去 48 小时内,该错误一直把我当作人质。如果尝试登录、管理、注册或访问任何页面,我会得到

'TypeError: 'HttpResponseForbidden' 对象不可调用

这是模型、视图和模板:

model_1

#models
from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE
from PIL import Image


class Profile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pic')

    def __str__(self):
        return f'self.user.username Profile'

    def save(self):
        super().save()     
        img = Image.open(self.image.path)
        if img.height > 300 and img.width > 300:
            output_size=(300,300)
            img.thumbnail(output_size)
            img.save(self.image.path)




Views_1

from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth import authenticate
from django.http import request, HttpResponse
from django.contrib import messages
from .forms import *
from .models import *
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required

# Create your views here.
def register(request):
    if request.method == 'POST':
        form = CompRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            return redirect('Login')
    else:
        form = CompRegisterForm()
    return render(request, 'Users/register.html', 'form': form)


@login_required
def profile(request):
    if request.method == 'POST':
        u_form = CompUpdateForm(request.POST, instance=request.user)
        p_form = ProfilePicForm(request.POST,
                                request.FILES,
                                instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, f'Your account has been updated!')
            return redirect('Profile_Page')

    else:
        u_form = CompUpdateForm(instance=request.user)
        p_form = ProfilePicForm(instance=request.user.profile)

    context = 
        'u_form': u_form,
        'p_form': p_form
    

    return render(request, 'Users/profile.html', context)


模板

% extends "../Job/base.html"%
% load crispy_forms_tags %
% block content%
% load bootstrap %
<div class="container">
  <form method ="POST", enctype="multipart/form-data">
    %csrf_token%
    <fieldset>
      <legend class="border-bottom mb-4">Login</legend> 
      form|bootstrap
    </fieldset>
    <div class="form-group">
      <button class="btn btn-outline-info" type="Submit">Login </button>
    </div>
  </form>
  <div class="border-top pt-3"> 
    <small class= "text-muted">
    Need an account ? <a class= 'ml-2' href="% url 'Register' %"> Sign up </a>
    </small>
    <small>
      Forgot Password ? <a class = 'ml-2' href="% url 'password_reset'%">Reset Password</a>
    </small>
  
  </div>
</div>
% endblock content %

网址

from typing import Pattern
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls.static import static
from Users import views as user_views


urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('Job.urls')),
    path('register/', user_views.register, name="Register"),
    path('login/', auth_views.LoginView.as_view(template_name='Users/login.html'), name='Login'),
    path('Logout/', auth_views.LogoutView.as_view(template_name='Users/index.html'), name='Logout'),
    path('profile/', user_views.Profile, name="Profile_Page"),
    path('Password-reset/', auth_views.PasswordResetView.as_view(
        template_name='Users/password_reset.html'), name='password_reset'),
    path('Password-reset/done/', auth_views.PasswordResetDoneView.as_view(
        template_name='Users/password_reset_done.html'), name='password_reset_done'),
    path('Password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(
        template_name='Users/password_reset_confirm.html'), name='password_reset_confirm'),
]


if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

错误

Traceback (most recent call last):
  File "/home/tito/wira_Proj/wira_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
TypeError: 'HttpResponseForbidden' object is not callable
[31/Aug/2021 06:59:12] "GET /profile/ HTTP/1.1" 500 58968
Internal Server Error: /favicon.ico
Traceback (most recent call last):
  File "/home/tito/wira_Proj/wira_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
TypeError: 'HttpResponseForbidden' object is not callable


我们将非常感谢您的帮助

【问题讨论】:

请edit 并将full错误回溯添加到您的问题中。 显示您的urls.py,您是否有任何自定义中间件? 我已添加 URLS 。自定义中间件,我用的是Django预包版 错字:在path('profile/', user_views.Profile, name="Profile_Page")user_views.Profile 指的是模型,您的视图被命名为profile,因此它应该是user_views.profile。另见Should wildcard import be avoided? 感谢指正。不幸的是,它没有用。 【参考方案1】:

最后,我得到了解决方案: 检查您的 settings.py 文件中的以下内容并删除/删除它们

CSRF_COOKIE_DOMAIN:设置 CSRF cookie 时要使用的域。这对于轻松允许跨子域请求从正常的跨站点请求伪造保护中排除非常有用。它应该设置为诸如“.example.com”之类的字符串,以允许来自一个子域上的表单的 POST 请求被另一个子域提供的视图接受。 CSRF_COOKIE_SECURE:如果您设置为 true,则 cookie 将被标记为“安全”,这意味着浏览器可以确保 cookie 仅通过 HTTPS 连接发送。记住您正在使用 localhost django.views.csrf.csrf_failure 阅读更多来自django Crosssite Forgery

【讨论】:

【参考方案2】:

在你看来试试这个

def profile(request):
    if request.method == 'POST':
        u_form = CompUpdateForm(request.POST, instance=request.user)
        p_form = ProfilePicForm(request.POST,
                                request.FILES,
                                instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, f'Your account has been updated!')
            return redirect('Profile_Page')

    else:
        u_form = CompUpdateForm()
        p_form = ProfilePicForm()

    context = 
        'u_form': u_form,
        'p_form': p_form
    

    return render(request, 'Users/profile.html', context)

【讨论】:

以上是关于Django:'TypeError:'HttpResponseForbidden'对象不可调用的主要内容,如果未能解决你的问题,请参考以下文章

django:TypeError:'tuple'对象不可调用

Django TypeError - TypeError: issubclass() arg 1 必须是一个类

Django:“TypeError:[] 不是 JSON 可序列化的”为啥?

Django 预览,TypeError:'str' 对象不可调用

Django异常中间件:TypeError:object()不带参数

Django ConnectionAbortedError + TypeError + AttributeError