0

I have a model that takes a Boolean update from the admin. If the admin clicks it, the end user can or cannot access the a view. The problem is that the view is accessible through the home page which has a base file and it requires the id of the user to check against. I get this error NoReverseMatch at /home/ I am unable to understand how can I pass the context value to the base file. I don't want to create another view for as it's a base file.

I tried context_processors but it gives me this error at the home.view int() argument must be a string or a number, not builtin_function_or_method

I have two functions in context_processors, each has it's own characteristics.

Here is the code

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>

errors

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'

enter image description here

error 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)

UPDATED

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.

I expect, when the user is allowed by the admin from the back end then the user is able to access the request page and apply, otherwise the view redirects the user to a different page.

Talha Murtaza
  • 324
  • 1
  • 2
  • 17
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/194164/discussion-on-question-by-talha-murtaza-django-context-value-for-home-page). – Samuel Liew May 30 '19 at 10:27

3 Answers3

1

From error

int() argument must be a string or a number, not builtin_function_or_method

it's obvious that context processor does not like a function or method to be returned.

so don't do

return {'emp_base_context': emp_base_context}

return a proper value instead like

return {'emp_base_context': emp_data}

Also I could not understand why you've declared emp_data and lev_data when you're not using it. So, I feel your context processors should look like.

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}
xxbinxx
  • 1,527
  • 11
  • 18
1

The error is in emp_data = Employee.objects.get(id=id)

in the function

def emp_base_context(request):
    emp_data = Employee.objects.get(id=id)
    return {
        'emp_base_context': emp_data}

where is the id coming from? Since you didn't give any id here, it's taking the python in-built id function. You might watch to fetching the id form request.

harshil9968
  • 3,254
  • 1
  • 16
  • 26
0

From the docs:

A context processor has a very simple interface: It’s a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.

So when you do: emp_data = Employee.objects.get(id=id) Django is raising the exception.

>>> 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>

If you're trying to retrieve the user logged in:

def emp_base_context(request):
    emp_data = Employee.objects.get(id=request.user.id)

    return {
        'emp_base_context': emp_base_context} 
Juan Diego Godoy Robles
  • 14,447
  • 2
  • 38
  • 52
  • Yes, it working but I want the Employee id to be pass rather than the request.user.id. Because the admin user has id of 1 and the requesting user has id of 2 in the User. but in Employee the id is of user is 1 and that causes an error. – Talha Murtaza May 30 '19 at 08:51