Django URL参数和视图

时间:2019-05-29 06:45:11

标签: django python-2.7 django-templates django-views

我有一个视图,单击该视图即可接受请假并完成这两件事。 扣除申请的叶子数量。如果只有1位用户,则该代码可以正常工作,但是一旦添加了另一位用户,该代码就会发疯。

我尝试了以下方法,但是没有运气



form = Leave_Form(request.POST or None)
        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)


def accept_leave(request,id):  # accept email
    all_item = Leave.objects.get(id=id)
    employee = Employee.objects.get(id=id)
    context = {'employee': employee, 'all_item': all_item}
    leave = employee.leave_set.last()


#Annual Leave
    if leave.leave_Type == 'Annual_leave':
        employee.Annual_leave -= leave.leave_qty
        leave_status = "Accepted"
        employee.save()


#other conditions are here as well

    else:
        subject = "Leave Accepted" # email subject
        email_from = "settings.EMAIL_HOST_USER"  # email from
        to_email = ['talhamurtaza@clickmail.info']  # email to

        with open("C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/accept_email.txt", 'rb') as f:
            msgbody = f.read()
            msg = EmailMultiAlternatives(
            subject=subject, body=msgbody, from_email=email_from,to=to_email)
            html_template = get_template("...").render()
            msg.attach_alternative(html_template, "text/html")
            msg.send()
    return render(request, 'projectfiles/email.html', context)



def reject_leave(request, id):  # reject email
    all_item = Leave.objects.get(id=id)
    all_item.leave_status = "Rejected"
    all_item.save()
    context = {'all_item':all_item}
    subject = "Leave Rejected"  # email subject
    email_from = "settings.EMAIL_HOST_USER"  # email from
    to_email = ['talhamurtaza@clickmail.info']  # email to

    with open(
            "C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/reject_email.txt", 'rb') as f:
        msgbody = f.read()
        msg = EmailMultiAlternatives(
        subject=subject, body=msgbody, from_email=email_from, to=to_email)
        html_template = get_template(
            "C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/reject_email.html").render()
        msg.attach_alternative(html_template, "text/html")
        msg.send()

    return render(request, 'projectfiles/rejectemail.html',context)








但是我无法这样做,它给我URL错误和查看错误/ 例如 1. accept_leave()恰好接受2个参数(给定1个) 2. quereyset不存在 3.没有匹配的querey等

models.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from datetime import date,datetime



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)
    def __str__(self):
                return self.employee_name.username
    class Meta:
        verbose_name_plural = "Employee"

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")
    class Meta:
        verbose_name_plural = "Leave"
    def __str__(self):
        return self.leave_Type + "  by  " + str(self.employee_leaves)

views.py


def accept_leave(request, lev_id, emp_id):  # accept email
    print "=/=/=/=/=/=/=/=/=" #+ str(request.GET) + "=/=/=/=/=/=/=/=/="
    all_item = Leave.objects.get(lev_id=lev_id)
    employee = Employee.objects.get(emp_id=emp_id)
    context = {'employee': employee, 'all_item': all_item}
    leave = employee.leave_set.last()

#Annual Leave
    if leave.leave_Type == 'Annual_leave':
        employee.Annual_leave -= leave.leave_qty
        leave_status = "Accepted"
        employee.save()
    else:
        subject = "Leave Accepted" # email subject
        email_from = "settings.EMAIL_HOST_USER"  # email from
        to_email = ['talhamurtaza@clickmail.info']  # email to

        with open("...", 'rb') as f:
            msgbody = f.read()
            msg = EmailMultiAlternatives(
            subject=subject, body=msgbody, from_email=email_from,to=to_email)
            html_template = get_template("...").render()
            msg.attach_alternative(html_template, "text/html")
            msg.send()
    return render(request, 'projectfiles/email.html', context)

urls.py

from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views

urlpatterns = [
    url(r'^(?i)Home/$', views.home, name='Home-Page'),
    url(r'^(?i)request/$', views.request_leave,
        name='Leave-Page'),  # leave request
    url(r'^(?i)leaves/$', views.leave_show, name='leave_show'),
    url(r'^(?i)AcceptedLeaves/$',views.accepted_leave_show, name='Accept_show'),
    url(r'^(?i)Rejectleaves/$', views.rejected_leave_show,
        name='Reject_show'),  # user leaves
]

管理仪表板.html

<title>Admin Dashboard</title>

{% include 'projectfiles/base2.html' %}

<center>
{% block asd %}
<br><br>

<div class="container">


{% for obj in all_items%}
{% if obj.leave_status == "Pending" %}


{% if count %}

<h3>Total: <font color='#1783FF'> "{{ count }}"</font></h3><hr width="40%" noshade>

{% else %}

<br><br><br><br><br><br><br><br>
<h2><u>NO LEAVES</u></h2>

{% endif %}

</div>
<br>
<div class="container">

<h3><b>Applicant:</b> {{obj.employee_leaves}}</h3>

<b>Leave Type:</b> {{obj.leave_Type}}<br>
<small>Leave ID: {{obj.id}}</small><br>
<small>From: {{obj.from_date}}</small><br>
<small>To: {{obj.to_date}}</small><br>
<small>Applied date: {{obj.submit_date}}</small><br>
<small>Quantity: {{obj.leave_qty}}</small><br>

{% if obj.description %}
<small><b>Reason: {{obj.description}}</b></small><br>
{% else %}  <small><b><u>Not Mentioned</u></b></small><br>    {% endif %}

<a href="/acceptemail/?{{obj.id}}" + "&emp_id={{obj.employee_leaves.pk}}"> Accept</a> <b>||</b> <a href="{% url 'Reject-page' id=obj.id %}">Reject</a>

<hr width="50%">

</div>

{% else %} <h2><u>No Pending LEAVES</u></h2>

{% endif %} {% endfor %}


{% endblock asd %}
</center>

错误

[29/May/2019 12:01:30] "GET /leaves/ HTTP/1.1" 200 2154
[29/May/2019 12:01:30] "GET /static/css/styles.css HTTP/1.1" 304 0
[29/May/2019 12:01:30] "GET /static/js/login.js HTTP/1.1" 304 0
[29/May/2019 12:01:38] "GET /request/ HTTP/1.1" 200 8148
Internal Server Error: /acceptemail/
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: accept_leave() takes exactly 3 arguments (1 given)
[29/May/2019 12:01:40] "GET /acceptemail/?5 HTTP/1.1" 500 62132

错误2

Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Python27\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\views.py", line 223, in leave_show
    return render(request, 'projectfiles/adminpage.html', context)
  File "C:\Python27\lib\site-packages\django\shortcuts.py", line 30, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Python27\lib\site-packages\django\template\loader.py", line 68, in render_to_string
    return template.render(context, request)
  File "C:\Python27\lib\site-packages\django\template\backends\django.py", line 66, in render
    return self.template.render(context)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 207, in render
    return self._render(context)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 199, in _render
    return self.nodelist.render(context)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 990, in render
    bit = node.render_annotated(context)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 957, in render_annotated
    return self.render(context)
  File "C:\Python27\lib\site-packages\django\template\loader_tags.py", line 63, in render
    result = self.nodelist.render(context)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 990, in render
    bit = node.render_annotated(context)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 957, in render_annotated
    return self.render(context)
  File "C:\Python27\lib\site-packages\django\template\defaulttags.py", line 216, in render
    nodelist.append(node.render_annotated(context))
  File "C:\Python27\lib\site-packages\django\template\base.py", line 957, in render_annotated
    return self.render(context)
  File "C:\Python27\lib\site-packages\django\template\defaulttags.py", line 322, in render
    return nodelist.render(context)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 990, in render
    bit = node.render_annotated(context)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 957, in render_annotated
    return self.render(context)
  File "C:\Python27\lib\site-packages\django\template\defaulttags.py", line 458, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "C:\Python27\lib\site-packages\django\urls\base.py", line 91, in reverse
    return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 497, in _reverse_with_prefix
    raise NoReverseMatch(msg)
NoReverseMatch: Reverse for 'Accept-page' with keyword arguments '{u'id': 7}' not found. 1 pattern(s) tried: ['acceptemail/(?P<lev_id>\\d+)$']
[29/May/2019 12:05:59] "GET /leaves/ HTTP/1.1" 500 167194

我希望代码将状态更改为“已接受”,并扣除所选的请假金额并在db中为申请请假的用户更新。

0 个答案:

没有答案