我正在尝试更新表中的几行。与this question相同。几天以来,我修改了项目代码,并试图解决该问题,但是它对我不起作用。首先,我以表格形式显示html页面中的所有现有行。如果是POST请求,则尝试保存到db中。我这里有2个错误。 1.如果我使用return render_to_response('module.html',{'modules' : modules})
,它会按照我的意愿在html页面中显示数据,但是当单击“保存”按钮时,它会在POST请求中显示以下错误:
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
如果我使用return render(request, 'module.html',{'modules' : modules})
,它甚至不显示数据,只是在GET请求中给出以下错误:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/module/nav-tab/new
Django Version: 2.1.3
Python Version: 3.7.1
Installed Applications:
['MyApp',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
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 "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
34.response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
126.response = self.process_exception_by_middleware(e, request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
124.response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapped_view
142.response = view_func(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapped_view
142.response = view_func(request, *args, **kwargs)
File "/Users/cem/Documents/Projects/Python/Web/FirstApp/MyApp/views.py" in addmodule
157.return render(request,template_name, args)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/shortcuts.py" in render
36.content = loader.render_to_string(template_name, context, request, using=using)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/template/loader.py" in render_to_string
62.return template.render(context, request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/template/backends/django.py" in render
61.return self.template.render(context)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/template/base.py" in render
169.with context.bind_template(self):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/contextlib.py" in __enter__
112.return next(self.gen)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/template/context.py" in bind_template
246.updates.update(processor(self.request))
Exception Type: TypeError at /module/nav-tab/new
Exception Value: 'module' object is not callable
您能帮我发现我的代码有问题吗?
models.py
class ModuleNames(models.Model):
ModuleName = models.CharField(max_length = 50)
ModuleDesc = models.CharField(max_length = 256)
ModuleSort = models.SmallIntegerField()
isActive = models.BooleanField()
ModuleType = models.ForeignKey(ModuleTypes, on_delete=models.CASCADE, null = True)
slug = models.SlugField(('ModuleName'), max_length=50, blank=True)
class Meta:
app_label = 'zz'
def __unicode__(self):
return self.status
views.py
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.serializers.json import Serializer
from django.http import HttpResponse
from urllib.parse import urlparse
from django.urls import resolve
from django.http import Http404, HttpResponseRedirect
from django.db import connection
from myapp.models import TableDefinition
from myapp.models import ColumnDefinition
from myapp.models import ModuleNames
from myapp.models import ModuleTypes
from collections import namedtuple
from django.db.models import F
import json
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
@cache_page(60 * 15)
@csrf_protect
def addmodule(request,moduletype):
modules=''
if request.method == 'POST':
data = request.POST.dict()
data.pop('csrfmiddlewaretoken', None)
for i in data.items():
obj = ModuleNames.objects.get(id=i[0].split("_")[1])
print(obj)
obj.save()
listmodules = ModuleTypes.objects.get(ModuleType=moduletype)
modules = ModuleNames.objects.all()
print(modules)
return render(request, 'module.html',{'modules' : modules})
template.html
<table class="table table-striped table-hover table-sm">
<thead>
<tr>
<th width="35px">Id</th>
<th width="50px">Module Name</th>
<th width="50px">Module Desc</th>
<th width="50px">Module Sort</th>
<th width="50px">Is Active?</th>
<th width="50px">Module Type</th>
</tr>
</thead>
<tbody>
<form action="" method="post" accept-charset="utf-8">
{% csrf_token %}
<input type='hidden' name='csrfmiddlewaretoken' value='randomchars'/>
{% for module in modules %}
<tr>
<td>
<label for="module_id">{{ module.id }} </label>
</td>
<td>
<input id="{{ module.id }}" type="text" name="moduleName_{{ module.ModuleName }}" value="{{ module.ModuleName }}">
</td>
<td>
<input id="{{ module.id }}" type="text" name="moduleDesc_{{ module.ModuleDesc }}" value="{{ module.ModuleDesc }}">
</td>
<td>
<input id="{{ module.id }}" type="text" name="moduleSort_{{ module.ModuleSort }}" value="{{ module.ModuleSort }}">
</td>
<td>
<input id="{{ module.id }}" type="text" name="moduleIsActive_{{ module.isActive }}" value="{{ module.isActive }}">
</td>
<td>
<input id="{{ module.id }}" type="text" name="moduleTypeId_{{ module.ModuleType_id }}" value="{{ module.ModuleType_id }}">
</td>
</tr>
{% endfor %}
<tr>
<td>
<!--<input id="module_id" type="text" name="module_id" value="">-->
</td>
<td>
<input id="module_name" type="text" name="module_name" value="">
</td>
<td>
<input id="module_desc" type="text" name="module_desc" value="">
</td>
<td>
<input id="module_sort" type="text" name="module_sort" value="">
</td>
<td>
<input id="module_isactive" type="text" name="module_isactive" value="">
</td>
<td>
<input id="module_typeid" type="text" name="module_typeid" value="">
</td>
</tr>
<tr>
<td colspan="6">
<input type="submit" value="Save">
</td>
</tr>
</form>
</tbody>
</table>