我有一个需要管理员更新布尔值的模型。如果管理员单击它,则最终用户可以或不能访问该视图。问题在于该视图可通过具有基本文件的主页进行访问,并且需要用户ID进行检查。 我在/ home / 处收到此错误 NoReverseMatch 我无法理解如何将上下文值传递给基本文件。我不想为其创建另一个视图,因为它是基本文件。
我尝试使用context_processors,但是它在home.view上给了我这个错误 int()参数必须是字符串或数字,而不是buildin_function_or_method
我在context_processors中有两个函数,每个函数都有其自己的特征。
这是代码
settings.py
TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
'projectfiles.context_processors.emp_base_context',
'projectfiles.context_processors.lev_base_context',
],},},]
models.py
class Employee(models.Model):
allowed = models.BooleanField(default=True)
employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
employee_designation = models.CharField(max_length = 5)
employee_department = models.CharField(max_length = 5)
Annual_leave = models.PositiveSmallIntegerField(default=5)
Sick_leave = models.PositiveSmallIntegerField(default=5)
Casual_leave = models.PositiveSmallIntegerField(default=5)
Half_pay = models.PositiveSmallIntegerField(default=5)
Emergency_leave = models.PositiveSmallIntegerField(default=5)
class Leave(models.Model):
employee_leaves = models.ForeignKey(Employee, on_delete=models.CASCADE)
leave_Type = models.CharField(max_length=25)
leave_qty = models.PositiveSmallIntegerField(default=0)
description = models.CharField(max_length=75, blank=True, null=True)
submit_date = models.DateTimeField(auto_now_add=True)
from_date = models.DateField(auto_now=False, auto_now_add=False)
to_date = models.DateField(auto_now=False, auto_now_add=False)
leave_status = models.CharField(max_length=10, default="Pending")
context_processors.py
from .models import Employee, Leave
def emp_base_context(request):
emp_data = Employee.objects.get(id=id)
return {
'emp_base_context': emp_base_context}
urls.py
urlpatterns = [
url(r'^(?i)Home/$', views.home, name='Home-Page'),
url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
name='Leave-Page'), # leave request
views.py
def request_leave(request, emp_id): # Requesting leave
employee = Employee.objects.get(id=emp_id)
if employee.allowed == True:
form = Leave_Form(request.POST)
if form.is_valid():
abc = form.save(commit=False)
abc.employee_leaves = request.user.employee
abc.save()
form = Leave_Form
context = {'employee': employee, 'form': form}
return render(request, 'projectfiles/reqleave.html', context)
else:
return render(request, "projectfiles/banned.html")
base.html
<nav id="mynav" class="navbar navbar-expand-sm bg-dark">
class="glyphicon glyphicon-folder-close"></span> Leave Management System</a>
</h4>
</div>
<div class="panel-collapse collapse panel-scroll" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne"><span
class="glyphicon glyphicon-folder-close"></span> Home</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
<table class="table">
<tbody>
<tr>
<td>
The request page **<a href="{% url "Leave-Page" {{emp_base_context.id}} %}"><span class="glyphicon glyphicon-pencil text-primary"></span> Request Leave</a>**
</td>
</tr>
<tr>
<td>
<a href={% url "notifications-Page" %}><span class="glyphicon glyphicon-pencil text-primary"></span> Notifications</a>
</td>
</tr>
<td>
<a href={% url "About-Page" %}><span class="glyphicon glyphicon-file text-info"></span> About</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseThree"><span
class="glyphicon glyphicon-user"></span> {{user.username}}</a>
</h4>
</div>
<div id="collapseThree" class="panel-collapse collapse ">
<div class="panel-body">
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo"><span
class="glyphicon glyphicon-th"></span>Remaining Leaves</a>
</h4>
</div>
<div id="collapseTwo" class="panel-collapse collapse ">
<div class="panel-body">
<table class="table">
<tbody>
<tr>
<td>
Annual<span class="label label-success"><font color='red'><br><small>Remaining leaves</small></font></span>
</td>
</tr>
<tr>
<td>
Emergency<span class="label label-success"><font color='red'><br><small>Remaining leaves</small></font></span>
</td>
</tr>
<tr>
<td>
Sick<span class="label label-success"><font color='red'><br><small>Remaining leaves</small></font></span>
</td>
</tr>
<tr>
<td>
Casual<span class="label label-success"><font color='red'><br><small>Remaining leaves</small></font></span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="push"></div>
错误
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/home/
Django Version: 1.11.20
Python Version: 2.7.16
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'projectfiles',
'crispy_forms']
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:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\views.py" in home
25. return render(request, "projectfiles/HomePage.html")
File "C:\Python27\lib\site-packages\django\shortcuts.py" in render
30. content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Python27\lib\site-packages\django\template\loader.py" in render_to_string
68. return template.render(context, request)
File "C:\Python27\lib\site-packages\django\template\backends\django.py" in render
66. return self.template.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
205. with context.bind_template(self):
File "C:\Python27\lib\contextlib.py" in __enter__
17. return self.gen.next()
File "C:\Python27\lib\site-packages\django\template\context.py" in bind_template
263. updates.update(processor(self.request))
File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\context_processors.py" in emp_base_context
7. emp_data = Employee.objects.get(id=id)
File "C:\Python27\lib\site-packages\django\db\models\manager.py" in manager_method
85. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in get
371. clone = self.filter(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in filter
787. return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
805. clone.query.add_q(Q(*args, **kwargs))
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_q
1250. clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in _add_q
1276. allow_joins=allow_joins, split_subq=split_subq,
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_filter
1210. condition = self.build_lookup(lookups, col, value)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_lookup
1104. return final_lookup(lhs, rhs)
File "C:\Python27\lib\site-packages\django\db\models\lookups.py" in __init__
24. self.rhs = self.get_prep_lookup()
File "C:\Python27\lib\site-packages\django\db\models\lookups.py" in get_prep_lookup
74. return self.lhs.output_field.get_prep_value(self.rhs)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
966. return int(value)
Exception Type: TypeError at /home/
Exception Value: int() argument must be a string or a number, not 'builtin_function_or_method'
错误2.0
Request Method: GET
Request URL: http://127.0.0.1:8000/home/
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
Exception Type: TypeError at /home/
Exception Value: home() takes exactly 2 arguments (1 given)
已更新
url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
name='Leave-Page'),
<a href="{% url "Leave-Page" request.user.id %}"><span class="glyphicon glyphicon-pencil text-primary"></span> Request Leave</>
def request_leave(request, emp_id): # Requesting leave
employee = Employee.objects.get(employee_name=emp_id)
if employee.allowed == True:
form = Leave_Form(request.POST)
if form.is_valid():
abc = form.save(commit=False)
abc.employee_leaves = request.user.employee
abc.save()
form = Leave_Form
context = {'employee': employee, 'form': form}
# context = {'form': form}
return render(request, 'projectfiles/reqleave.html', context)
else:
return render(request, "projectfiles/banned.html")
using context_processor was passing the id to the entire view, I just needed to use it for request and by comparing the user id with the employee name worked for me.
我希望,如果管理员从后端允许用户访问,则用户可以访问请求页面并申请,否则视图会将用户重定向到其他页面。
答案 0 :(得分:1)
由于错误
int()参数必须是字符串或数字,而不是buildin_function_or_method
很明显,上下文处理器不喜欢返回函数或方法。
所以不要
return {'emp_base_context': emp_base_context}
返回适当的值,而不是
return {'emp_base_context': emp_data}
我也无法理解为什么不使用时声明了emp_data
和lev_data
。因此,我觉得您的上下文处理器应该看起来像。
from .models import Employee, Leave
def emp_base_context(request):
emp_data = Employee.objects.get(id=id)
return {
'emp_base_context': emp_data}
def lev_base_context(request):
lev_data = Leave.objects.get(id=id)
return {
'lev_base_context': lev_data}
答案 1 :(得分:1)
错误在emp_data = Employee.objects.get(id=id)
功能
def emp_base_context(request):
emp_data = Employee.objects.get(id=id)
return {
'emp_base_context': emp_data}
id
来自哪里?由于您在此处未提供任何ID,因此将使用python in-built id function。您可能会注意获取id
表单请求。
答案 2 :(得分:0)
来自docs:
上下文处理器的界面非常简单:它是Python 该函数采用一个参数,一个 HttpRequest对象,并返回 添加到模板上下文的字典。每个上下文 处理器必须返回字典。
因此,当您执行以下操作时:emp_data = Employee.objects.get(id=id)
Django引发了异常。
>>> Test.objects.get(id=id)
Traceback (most recent call last):
TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method'
>>> id
<built-in function id>
如果您要检索登录的用户:
def emp_base_context(request):
emp_data = Employee.objects.get(id=request.user.id)
return {
'emp_base_context': emp_base_context}