models.py
from django.db import models
from django.contrib.auth.models import User
CHOICES = (('1','Earned Leave'),('2','Casual Leave'),('3','Sick Leave'),('4','Paid Leave'))
class Leave(models.Model):
name = models.CharField(max_length = 50)
user = models.ForeignKey(User, on_delete = models.CASCADE, null =True)
employee_ID = models.CharField(max_length = 20)
department = models.CharField(max_length = 50)
designation = models.CharField(max_length = 50)
type_of_leave = models.CharField(max_length = 15, choices = CHOICES, default = None)
from_date = models.DateField(help_text = 'mm/dd/yy')
to_date = models.DateField(help_text = 'mm/dd/yy')
reporting_manager = models.CharField(max_length = 50, default = None, help_text = '0001_manager, 0002_manager')
reason = models.CharField(max_length= 180)
accepted = models.BooleanField(('approval status'), default= False)
def __str__(self):
return self.name
我希望用户在提交表单后,如果其状态为“是工作人员”,则只能访问“ type_leave_field”。
forms.py
from django import forms
from lrequests import models
class LeaveRequestForm(forms.ModelForm):
class Meta:
fields = ("name", "employee_ID", "department", "designation", "type_of_leave", "from_date", "to_date", "reporting_manager", "reason")
model = models.Leave
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import LeaveRequestForm
from .models import Leave
def leaveRequest(request):
form_class = LeaveRequestForm
if request.method == "POST":
form = LeaveRequestForm(request.POST)
if form.is_valid():
leave = form.save(commit = False)
leave.user = request.user
form.save()
return HttpResponse("Sucessfully submitted")
else:
form = LeaveRequestForm()
return render(request, "request_form.html", {'form' : form_class})
我尝试使用django-guardian和django-objectpermissions,但是我没有看到使用它们的确切方法。我什至为此创建了一个用户权限,但是由于管理员视图和模板不是用户编写的代码,因此我无法给出定义。
base:这是一个请假管理系统项目,用户即使提交表格也可以编辑其请假类型,谢谢。
如何在html页面中显示特定字段。
在我的models.py中,“接受”字段是一个布尔字段,在用户提交表单后,我想显示该字段的状态,无论它在html页面中是True还是False。我无法从数据库中检索该字段。
答案 0 :(得分:0)
您可以做的是通过使除用户应能够更新的字段以外的所有其他字段均为只读,来覆盖ModelAdmin readonly_fields方法。
def get_readonly_fields(self, request, obj=None):
# the logged in user can be accessed through the request object
if obj and request.user.is_staff:
readonly_fields = [f.name for f in self.opts.fields]
readonly_fields.remove('type_leave_field')
return readonly_fields
关于列表理解:
self.opts
使您可以访问元类中指定的模型(或者也可以使用@admin.register()
)。
self.opts.fields
是一个由该模型中的字段对象组成的元组。每个对象都是带有字段元数据的字典。通过访问每个字段对象的.name(键),我们可以获得以字符串表示的字段名称。