如何编写代码,以便在使用 django 的模型中只选择一个单选按钮。?

#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):


    employee_ID = models.CharField(max_length = 20)


    name = models.CharField(max_length = 50)


    user = models.ForeignKey(User, on_delete = models.CASCADE, null =True)


    department = models.CharField(max_length = 50)


    designation = models.CharField(max_length = 50)


    type_of_leave = models.CharField(max_length = 15, choices = CHOICES)


    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(('accept'), default= False)


    rejected = models.BooleanField(('reject'), default = False)


    reason_reject = models.CharField(('reason for rejection'),max_length=50) // this didn't help me.


    def __str__(self):

        return self.name

这是一个请假申请表,其中accepted, rejected应仅选择两个字段 ( ) 中的一个,如果未选择字段拒绝字段,则reason_reject不应在/admin面板中显示。


#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

用户填写表格并提交。因此,现在管理员必须接受或拒绝它。reason_reject仅当管理员选择rejected字段后,该字段才应显示给管理员。这一切都应该只发生在管理端。


#admin.py

from django.contrib import admin

from . import models


通过运行上面的代码,我得到 KeyError at /admin/lrequests/leave/15/change/和


"Key 'id' not found in 'LeaveForm'. Choices are: accepted, department, designation, employee_ID, from_date, name, reason, reason_reject, rejected, reporting_manager, to_date, type_of_leave, user."


慕后森
浏览 229回答 2
2回答

慕姐8265434

整个前提是有缺陷的。您不能在模型定义中执行这种逻辑,因为那时没有实例,因此没有要比较的值。即使可以,它仍然没有意义,因为模型定义定义了模型具有的数据库列;您不能在数据库中具有不同实例且具有不同列的实例。模型定义适用于整个模型。您需要reason_reject在类定义中。您可能想要做的是根据模型中的值更改表单。您可以通过覆盖get_fields方法在管理员中执行此操作。class LeaveAdmin(admin.ModelAdmin):    ...    def get_fields(self, request, obj=None):        fields = [....list of fields for the form...]        if obj and obj.rejected:            fields.append('reason_reject')        return fields注意,您可能要考虑您是否真的需要单独的接受/拒绝字段。对于应用程序的状态最好有一个字段:接受或拒绝。您可以将它们表示为单个单选按钮或下拉菜单。STATUS_CHOICES = (    (1, 'Accepted'),    (0, 'Rejected'),)status = models.IntegerField(choices=STATUS_CHOICES, blank=True, null=True)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python