Ajax 500 Internal Server但在刷新后和Django模型中被删除

时间:2018-02-22 03:42:29

标签: ajax django datatables

我正在使用Django和Datatables,我正在为ListView做类似批量删除功能。

单击“删除”按钮时,会显示POST 500 (Internal Server Error)。但是当我刷新页面时,它会被成功删除。

'action': function() {
    // count check used for checking selected items.
    var count = table.rows({
        selected: true
    }).count();

    if (count > 0) {
        swal({
            title: "Are you sure you want to delete these items?",
            text: "There is NO undo!",
            type: "warning",
            showCancelButton: true,
            // confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            closeOnConfirm: true,
        }, function(isConfirm) {
            if (isConfirm) {
                var data = table.rows({
                    selected: true
                }).data();

                var list = [];

                for (var i = 0; i < data.length; i++) {
                    // alert(data[i][2]);
                    list.push(data[i][2]);
                }

                var sData = list.join();

                // alert(sData)
                document.getElementById('delete_items_list').value = sData;

                $.ajaxSetup({
                    beforeSend: function(xhr, settings) {
                        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                            xhr.setRequestHeader("X-CSRFToken", csrftoken);
                        }
                    }
                });
                $.ajax({
                    type: 'POST',
                    url: window.location.href,
                    data: {
                        'ids': sData
                    },
                    success: function() {
                        // Update page
                        window.location.reload();
                        swal("Deleted!", "The selected item/s were successfully deleted.", "success");
                    },
                    error: function() {
                        // Display message or something else
                        // swal("Error deleting!", "Please try again.", "error");
                    }
                });
            } else {
                return false;
            }
        });
    } else {
        swal("Error!", "You didn't select any items.", "error");
        return false;
    }
},

这是我在part(基于类的通用ListView)中的views.py:

class PartListView(LoginRequiredMixin, ListView):

    model = Part

    def post(self, request, *args, **kwargs):
        ids = self.request.POST.get('ids')
        ids = ids.split(",")
        # try:
            # Check ids are valid numbers
            # ids = map(int, ids)
        # except ValueError as e:
        #     return JsonResponse(status=400)
        # delete items
        self.model.objects.filter(id__in=ids).delete()
        return reverse('part')
        # return JsonResponse({"status": "ok"}, status=204)



    def get_context_data(self, **kwargs):
        context = super(PartListView, self).get_context_data(**kwargs)
        context['now'] = timezone.now()
        context['activate'] = 'part'
        return context

我还希望在页面重新加载后显示swal("Deleted!", "The selected item/s were successfully deleted.", "success"); sweetalert ,但它不起作用。这可能是因为500内部服务器错误而无法显示的原因。

我该如何解决这个问题?提前谢谢!

这就是用户界面的样子。 enter image description here

回溯:

AttributeError at /part/
'str' object has no attribute 'get'

Request Method: POST
Request URL: http://127.0.0.1:8000/part/
Django Version: 2.0.2
Python Executable: C:\Ken\deltainventory\myvenv\Scripts\python.exe
Python Version: 3.6.3
Python Path: ['C:\\Ken\\deltainventory', 'C:\\Ken\\deltainventory\\myvenv\\Scripts\\python36.zip', 'C:\\Python36\\DLLs', 'C:\\Python36\\lib', 'C:\\Python36', 'C:\\Ken\\deltainventory\\myvenv', 'C:\\Ken\\deltainventory\\myvenv\\lib\\site-packages']
Server time: Thu, 22 Feb 2018 11:56:09 +0800
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'inventory',
 'widget_tweaks',
 'sweetify']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Traceback:

File "C:\Ken\deltainventory\myvenv\lib\site-packages\django\core\handlers\exception.py" in inner
  35.             response = get_response(request)

File "C:\Ken\deltainventory\myvenv\lib\site-packages\django\utils\deprecation.py" in __call__
  97.             response = self.process_response(request, response)

File "C:\Ken\deltainventory\myvenv\lib\site-packages\django\middleware\clickjacking.py" in process_response
  26.         if response.get('X-Frame-Options') is not None:

Exception Type: AttributeError at /part/
Exception Value: 'str' object has no attribute 'get'
Request information:
USER: admin

GET: No GET data

POST:
ids = '71'

FILES: No FILES data

COOKIES:
sessionid = 'i9h2ts33s15n5ufcvuzanut5a01f54z7'
_ga = 'GA1.1.1743870208.1519265216'
_gid = 'GA1.1.1997363703.1519265216'
_gat = '1'

META:
ALLUSERSPROFILE = 'C:\\ProgramData'
ANSICON = '73x32766 (73x21)'
ANSICON_DEF = '7'
APPDATA = 'C:\\Users\\Administrator\\AppData\\Roaming'
COMMONPROGRAMFILES = 'C:\\Program Files\\Common Files'
COMMONPROGRAMFILES(X86) = 'C:\\Program Files (x86)\\Common Files'
COMMONPROGRAMW6432 = 'C:\\Program Files\\Common Files'
COMPUTERNAME = 'IT06062016-PC'
COMSPEC = 'C:\\Windows\\system32\\cmd.exe'
CONEMUANSI = 'ON'
CONEMUANSILOG = ''
CONEMUARGS = ''
CONEMUARGS2 = ''
CONEMUBACKHWND = '0x000202B8'
CONEMUBASEDIR = 'E:\\kendjango jan 29\\ConEmu Portable 171226\\ConEmu'
CONEMUBASEDIRSHORT = 'E:\\kendjango jan 29\\ConEmu Portable 171226\\ConEmu'
CONEMUBUILD = '171226'
CONEMUCFGDIR = 'E:\\kendjango jan 29\\ConEmu Portable 171226'
CONEMUCONFIG = ''
CONEMUDIR = 'E:\\kendjango jan 29\\ConEmu Portable 171226'
CONEMUDRAWHWND = '0x000202B6'
CONEMUDRIVE = 'E:'
CONEMUHOOKS = 'Enabled'
CONEMUHWND = '0x000202A0'
CONEMUISADMIN = 'ADMIN'
CONEMUPALETTE = '<Current color scheme>'
CONEMUPID = '4412'
CONEMUPROMPT0 = '$E[m$E[32m$E]9;8;"USERNAME"$E\\@$E]9;8;"COMPUTERNAME"$E\\$S'
CONEMUPROMPT1 = '$E[m$E[32m$E]9;8;"USERNAME"$E\\@$E]9;8;"COMPUTERNAME"$E\\$S$E[92m$P$E[90m'
CONEMUPROMPT2 = '$_$E[90m$$'
CONEMUPROMPT3 = '$E[m$S$E]9;12$E\\'
CONEMUSERVERPID = '2452'
CONEMUTASK = '{Shells::cmd}'
CONEMUWORKDIR = 'C:\\Users\\Administrator'
CONEMUWORKDRIVE = 'C:'
CONTENT_LENGTH = '6'
CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=UTF-8'
CSRF_COOKIE = '5iKoTML7QZIkPSxkhBURue1sujhVwOvc0mvC4dngtR712KJ1HTokzSzDhG7z5zVG'
DJANGO_SETTINGS_MODULE = 'deltainventory.settings'
FP_NO_HOST_CHECK = 'NO'
GATEWAY_INTERFACE = 'CGI/1.1'
HOMEDRIVE = 'C:'
HOMEPATH = '\\Users\\Administrator'
HTTP_ACCEPT = '*/*'
HTTP_ACCEPT_ENCODING = 'gzip, deflate, br'
HTTP_ACCEPT_LANGUAGE = 'en-US,en;q=0.9'
HTTP_CONNECTION = 'keep-alive'
HTTP_COOKIE = 'sessionid=i9h2ts33s15n5ufcvuzanut5a01f54z7; _ga=GA1.1.1743870208.1519265216; _gid=GA1.1.1997363703.1519265216; _gat=1'
HTTP_HOST = '127.0.0.1:8000'
HTTP_ORIGIN = 'http://127.0.0.1:8000'
HTTP_REFERER = 'http://127.0.0.1:8000/part/'
HTTP_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36'
HTTP_X_CSRFTOKEN = 'IsFQFHqDnOMyFtsEaNxHIlGOLmy5uHRgDwq4Q82M0GbfSlElA51aNZeZyJoJ3shK'
HTTP_X_REQUESTED_WITH = 'XMLHttpRequest'
LOCALAPPDATA = 'C:\\Users\\Administrator\\AppData\\Local'
LOGONSERVER = '\\\\IT06062016-PC'
NUMBER_OF_PROCESSORS = '4'
OS = 'Windows_NT'
PATH = 'C:\\Ken\\deltainventory\\myvenv\\Scripts;E:\\kendjango jan 29\\ConEmu Portable 171226\\ConEmu\\Scripts;E:\\kendjango jan 29\\ConEmu Portable 171226;E:\\kendjango jan 29\\ConEmu Portable 171226\\ConEmu;C:\\Python36\\Scripts\\;C:\\Python36\\;C:\\Program Files (x86)\\NVIDIA Corporation\\PhysX\\Common;C:\\ProgramData\\Oracle\\Java\\javapath;C:\\Program Files\\Broadcom\\Broadcom 802.11 Network Adapter\\Driver;;C:\\Program Files (x86)\\Intel\\iCLS Client\\;C:\\Program Files\\Intel\\iCLS Client\\;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files (x86)\\Intel\\OpenCL SDK\\2.0\\bin\\x86;C:\\Program Files (x86)\\Intel\\OpenCL SDK\\2.0\\bin\\x64;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\IPT;C:\\Program Files (x86)\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files (x86)\\Intel\\Intel(R) Management Engine Components\\IPT;C:\\Program Files\\WIDCOMM\\Bluetooth Software\\;C:\\Program Files\\WIDCOMM\\Bluetooth Software\\syswow64'
PATHEXT = '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW'
PATH_INFO = '/part/'
PROCESSOR_ARCHITECTURE = 'AMD64'
PROCESSOR_IDENTIFIER = 'Intel64 Family 6 Model 58 Stepping 9, GenuineIntel'
PROCESSOR_LEVEL = '6'
PROCESSOR_REVISION = '3a09'
PROGRAMDATA = 'C:\\ProgramData'
PROGRAMFILES = 'C:\\Program Files'
PROGRAMFILES(X86) = 'C:\\Program Files (x86)'
PROGRAMW6432 = 'C:\\Program Files'
PROMPT = '(myvenv) $E[m$E[32m$E]9;8;"USERNAME"$E\\@$E]9;8;"COMPUTERNAME"$E\\$S$E[92m$P$E[90m$_$E[90m$$$E[m$S$E]9;12$E\\'
PSMODULEPATH = 'C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules\\'
PUBLIC = 'C:\\Users\\Public'
QUERY_STRING = ''
REMOTE_ADDR = '127.0.0.1'
REMOTE_HOST = ''
REQUEST_METHOD = 'POST'
RUN_MAIN = 'true'
SCRIPT_NAME = ''
SERVER_NAME = 'IT06062016-PC'
SERVER_PORT = '8000'
SERVER_PROTOCOL = 'HTTP/1.1'
SERVER_SOFTWARE = 'WSGIServer/0.2'
SESSIONNAME = 'Console'
SYSTEMDRIVE = 'C:'
SYSTEMROOT = 'C:\\Windows'
TEMP = 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp'
TMP = 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp'
USERDOMAIN = 'IT06062016-PC'
USERNAME = 'Administrator'
USERPROFILE = 'C:\\Users\\Administrator'
VIRTUAL_ENV = 'C:\\Ken\\deltainventory\\myvenv'
WINDIR = 'C:\\Windows'
WINDOWS_TRACING_FLAGS = '3'
WINDOWS_TRACING_LOGFILE = 'C:\\BVTBin\\Tests\\installpackage\\csilogfile.log'
_OLD_VIRTUAL_PATH = 'E:\\kendjango jan 29\\ConEmu Portable 171226\\ConEmu\\Scripts;E:\\kendjango jan 29\\ConEmu Portable 171226;E:\\kendjango jan 29\\ConEmu Portable 171226\\ConEmu;C:\\Python36\\Scripts\\;C:\\Python36\\;C:\\Program Files (x86)\\NVIDIA Corporation\\PhysX\\Common;C:\\ProgramData\\Oracle\\Java\\javapath;C:\\Program Files\\Broadcom\\Broadcom 802.11 Network Adapter\\Driver;;C:\\Program Files (x86)\\Intel\\iCLS Client\\;C:\\Program Files\\Intel\\iCLS Client\\;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files (x86)\\Intel\\OpenCL SDK\\2.0\\bin\\x86;C:\\Program Files (x86)\\Intel\\OpenCL SDK\\2.0\\bin\\x64;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\IPT;C:\\Program Files (x86)\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files (x86)\\Intel\\Intel(R) Management Engine Components\\IPT;C:\\Program Files\\WIDCOMM\\Bluetooth Software\\;C:\\Program Files\\WIDCOMM\\Bluetooth Software\\syswow64'
_OLD_VIRTUAL_PROMPT = '$E[m$E[32m$E]9;8;"USERNAME"$E\\@$E]9;8;"COMPUTERNAME"$E\\$S$E[92m$P$E[90m$_$E[90m$$$E[m$S$E]9;12$E\\'
wsgi.errors = <_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>
wsgi.file_wrapper = ''
wsgi.input = <_io.BufferedReader name=948>
wsgi.multiprocess = False
wsgi.multithread = True
wsgi.run_once = False
wsgi.url_scheme = 'http'
wsgi.version = '(1, 0)'

Settings:
Using settings module deltainventory.settings
ABSOLUTE_URL_OVERRIDES = {}
ADMINS = []
ALLOWED_HOSTS = []
APPEND_SLASH = True
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend']
AUTH_PASSWORD_VALIDATORS = '********************'
AUTH_USER_MODEL = 'auth.User'
BASE_DIR = 'C:\\Ken\\deltainventory'
CACHES = {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}
CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_KEY_PREFIX = '********************'
CACHE_MIDDLEWARE_SECONDS = 600
CSRF_COOKIE_AGE = 31449600
CSRF_COOKIE_DOMAIN = None
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_NAME = 'csrftoken'
CSRF_COOKIE_PATH = '/'
CSRF_COOKIE_SECURE = False
CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure'
CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN'
CSRF_TRUSTED_ORIGINS = []
CSRF_USE_SESSIONS = True
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'C:\\Ken\\deltainventory\\db.sqlite3', 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': None, 'USER': '', 'PASSWORD': '********************', 'HOST': '', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'NAME': None, 'MIRROR': None}}}
DATABASE_ROUTERS = []
DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440
DATA_UPLOAD_MAX_NUMBER_FIELDS = 1000
DATETIME_FORMAT = 'N j, Y, P'
DATETIME_INPUT_FORMATS = ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M:%S.%f', '%m/%d/%Y %H:%M', '%m/%d/%Y', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M:%S.%f', '%m/%d/%y %H:%M', '%m/%d/%y']
DATE_FORMAT = 'N j, Y'
DATE_INPUT_FORMATS = ['%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%b %d %Y', '%b %d, %Y', '%d %b %Y', '%d %b, %Y', '%B %d %Y', '%B %d, %Y', '%d %B %Y', '%d %B, %Y']
DEBUG = True
DEBUG_PROPAGATE_EXCEPTIONS = False
DECIMAL_SEPARATOR = '.'
DEFAULT_CHARSET = 'utf-8'
DEFAULT_CONTENT_TYPE = 'text/html'
DEFAULT_EXCEPTION_REPORTER_FILTER = 'django.views.debug.SafeExceptionReporterFilter'
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
DEFAULT_FROM_EMAIL = 'webmaster@localhost'
DEFAULT_INDEX_TABLESPACE = ''
DEFAULT_TABLESPACE = ''
DISALLOWED_USER_AGENTS = []
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_HOST_PASSWORD = '********************'
EMAIL_HOST_USER = ''
EMAIL_PORT = 25
EMAIL_SSL_CERTFILE = None
EMAIL_SSL_KEYFILE = '********************'
EMAIL_SUBJECT_PREFIX = '[Django] '
EMAIL_TIMEOUT = None
EMAIL_USE_LOCALTIME = False
EMAIL_USE_SSL = False
EMAIL_USE_TLS = False
FILE_CHARSET = 'utf-8'
FILE_UPLOAD_DIRECTORY_PERMISSIONS = None
FILE_UPLOAD_HANDLERS = ['django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler']
FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440
FILE_UPLOAD_PERMISSIONS = None
FILE_UPLOAD_TEMP_DIR = None
FIRST_DAY_OF_WEEK = 0
FIXTURE_DIRS = []
FORCE_SCRIPT_NAME = None
FORMAT_MODULE_PATH = None
FORM_RENDERER = 'django.forms.renderers.DjangoTemplates'
IGNORABLE_404_URLS = []
INSTALLED_APPS = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'inventory', 'widget_tweaks', 'sweetify']
INTERNAL_IPS = []
LANGUAGES = [('af', 'Afrikaans'), ('ar', 'Arabic'), ('ast', 'Asturian'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('be', 'Belarusian'), ('bn', 'Bengali'), ('br', 'Breton'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('dsb', 'Lower Sorbian'), ('el', 'Greek'), ('en', 'English'), ('en-au', 'Australian English'), ('en-gb', 'British English'), ('eo', 'Esperanto'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-co', 'Colombian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('es-ve', 'Venezuelan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy', 'Frisian'), ('ga', 'Irish'), ('gd', 'Scottish Gaelic'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hsb', 'Upper Sorbian'), ('hu', 'Hungarian'), ('ia', 'Interlingua'), ('id', 'Indonesian'), ('io', 'Ido'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('kab', 'Kabyle'), ('kk', 'Kazakh'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('lb', 'Luxembourgish'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('mr', 'Marathi'), ('my', 'Burmese'), ('nb', 'Norwegian Bokmål'), ('ne', 'Nepali'), ('nl', 'Dutch'), ('nn', 'Norwegian Nynorsk'), ('os', 'Ossetic'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('sw', 'Swahili'), ('ta', 'Tamil'), ('te', 'Telugu'), ('th', 'Thai'), ('tr', 'Turkish'), ('tt', 'Tatar'), ('udm', 'Udmurt'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('vi', 'Vietnamese'), ('zh-hans', 'Simplified Chinese'), ('zh-hant', 'Traditional Chinese')]
LANGUAGES_BIDI = ['he', 'ar', 'fa', 'ur']
LANGUAGE_CODE = 'en-us'
LANGUAGE_COOKIE_AGE = None
LANGUAGE_COOKIE_DOMAIN = None
LANGUAGE_COOKIE_NAME = 'django_language'
LANGUAGE_COOKIE_PATH = '/'
LOCALE_PATHS = []
LOGGING = {}
LOGGING_CONFIG = 'logging.config.dictConfig'
LOGIN_REDIRECT_URL = '/'
LOGIN_URL = '/login/'
LOGOUT_REDIRECT_URL = None
MANAGERS = []
MEDIA_ROOT = ''
MEDIA_URL = ''
MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
MIDDLEWARE = ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware']
MIGRATION_MODULES = {}
MONTH_DAY_FORMAT = 'F j'
NUMBER_GROUPING = 0
PASSWORD_HASHERS = '********************'
PASSWORD_RESET_TIMEOUT_DAYS = '********************'
PREPEND_WWW = False
ROOT_URLCONF = 'deltainventory.urls'
SECRET_KEY = '********************'
SECURE_BROWSER_XSS_FILTER = False
SECURE_CONTENT_TYPE_NOSNIFF = False
SECURE_HSTS_INCLUDE_SUBDOMAINS = False
SECURE_HSTS_PRELOAD = False
SECURE_HSTS_SECONDS = 0
SECURE_PROXY_SSL_HEADER = None
SECURE_REDIRECT_EXEMPT = []
SECURE_SSL_HOST = None
SECURE_SSL_REDIRECT = False
SERVER_EMAIL = 'root@localhost'
SESSION_CACHE_ALIAS = 'default'
SESSION_COOKIE_AGE = 1209600
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_NAME = 'sessionid'
SESSION_COOKIE_PATH = '/'
SESSION_COOKIE_SECURE = False
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_FILE_PATH = None
SESSION_SAVE_EVERY_REQUEST = False
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
SETTINGS_MODULE = 'deltainventory.settings'
SHORT_DATETIME_FORMAT = 'm/d/Y P'
SHORT_DATE_FORMAT = 'm/d/Y'
SIGNING_BACKEND = 'django.core.signing.TimestampSigner'
SILENCED_SYSTEM_CHECKS = []
STATICFILES_DIRS = ['C:\\Ken\\deltainventory\\static']
STATICFILES_FINDERS = ['django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder']
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
STATIC_ROOT = None
STATIC_URL = '/static/'
TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['C:\\Ken\\deltainventory\\templates'], 'APP_DIRS': True, 'OPTIONS': {'context_processors': ['django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages']}}]
TEMPLATE_DIR = 'C:\\Ken\\deltainventory\\templates'
TEST_NON_SERIALIZED_APPS = []
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
THOUSAND_SEPARATOR = ','
TIME_FORMAT = 'P'
TIME_INPUT_FORMATS = ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
TIME_ZONE = 'Asia/Manila'
USE_ETAGS = False
USE_I18N = True
USE_L10N = True
USE_THOUSAND_SEPARATOR = False
USE_TZ = True
USE_X_FORWARDED_HOST = False
USE_X_FORWARDED_PORT = False
WSGI_APPLICATION = 'deltainventory.wsgi.application'
X_FRAME_OPTIONS = 'SAMEORIGIN'
YEAR_MONTH_FORMAT = 'F Y'


You're seeing this error because you have DEBUG = True in your
Django settings file. Change that to False, and Django will
display a standard page generated by the handler for this status code.

3 个答案:

答案 0 :(得分:1)

使用ajax post方法在发布帖子时发送csrf令牌,如下所示。您可以在ajax设置方法中设置csrf令牌,如下所示。

在发布请求时使用csrf令牌,这将阻止500服务器错误

// CSRF code
    function getCookie(name) {
        var cookieValue = null;
        var i = 0;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (i; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    // Use csrf token while doing post request, this will prevent 500 Server Error
    $.ajaxSetup({
        crossDomain: false, // obviates need for sameOrigin test
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    }); 


});

答案 1 :(得分:1)

reverse函数以字符串格式返回一个您从post方法返回的url。它应该是一个响应对象。中间件尝试使用X-Frame-Options从响应对象获取get,但您的响应类型为str

因此返回响应对象而不是字符串。

答案 2 :(得分:0)

你得到内部错误,因为你应该返回Response实例(HttpResponse,HttpRedirectResponse,JsonResponse等)而不是字符串!

简单解决方案返回JsonResponse并删除reverse

稍微难点,但我认为更好的解决方案,覆盖get_template_names方法

def get_template_names(self):
    if self.request.is_ajax():
        return ['app/_items_table.html', ]
    return ['app/items_list.html', ]

_items_table加入items_list。并像这样更改post响应:

return super(PartListView, self).get(request, *args, **kwargs)

现在,在AJAX响应中,您应该替换页面上的完整表格,它可以帮助您摆脱页面重新加载。