简体   繁体   中英

How to set fields/model to readonly if one attribute is set to true in Django?

So, I got three classes:

class User(...):
    #... other fields
    name = models.CharField()

class Equipment(...):
    #... other fields 
    inUse = models.Boolean(default=False)

class Ticket(...):
    #... Other fields
    user = models.ForeignKey(...)
    equipment = models.ForeignKey(...)
    ended = models.Boolean(default=False)

Now, when I create a new Ticket , the equipment "inUse" attribute changes to True, so I cannot give the same Equipment to more than one User . The thing is that when I set the Ticket to "ended" I'll still be able to change it to not "ended". I want not to be able to change that once I set the "ended" attribute of the Ticket to True.

PS: I'm overriding the method save to make changes in the Equipment when setting up a new Ticket or changing it to "ended".

admin.py

from django.contrib import admin

from .models import Equipamento, TipoEquipamento, Funcionario, Setor, Ticket

# Register your models here.
class EquipamentoAdmin(admin.ModelAdmin):
    list_display = ['codigo', 'categoria', 'descricao', 'ativo', 'emUso']
    search_fields = ['codigo', 'descricao']

class FuncionarioAdmin(admin.ModelAdmin):
    list_display = ['nome', 'setor', 'email']
    search_fields = ['codigo', 'nome']
    

class TicketAdmin(admin.ModelAdmin):
    list_display = ['id', 'get_user_name', 'get_equipment_name', 'dataDevolucao', 'finalizado']
    autocomplete_fields = ['usuario', 'equipamento']
    
    def get_user_name(self, obj):
        return obj.usuario.nome
    
    def get_equipment_name(self, obj):
        return obj.equipamento.descricao

    get_user_name.short_description = 'Funcionario'
    get_equipment_name.short_description = 'Equipamento'

dumb question, after a few minutes I realized I could set a field like "can Change" in the model so that when I change Status the field will be set to false, and I will not be able to change that model anymore. Daaah, thanks anyways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM