Last active
June 28, 2018 05:09
-
-
Save morenopc/5663509 to your computer and use it in GitHub Desktop.
Funcionários models
Sobrescrever formulário admin para adicionar dois objetos User e Funcionario
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FuncionarioForm(forms.ModelForm): | |
""" Sobrescreve formulário de funcionários """ | |
class Meta: | |
model = Funcionario | |
exclude = ('usuario', ) | |
def __init__(self, *args, **kwargs): | |
super(FuncionarioForm, self).__init__(*args, **kwargs) | |
# Editar funcionário: valores iniciais | |
if hasattr(self, 'instance') and hasattr(self.instance, 'usuario'): | |
self.fields['nome'].initial = self.instance.usuario.first_name | |
self.fields['sobrenome'].initial = self.instance.usuario.last_name | |
self.fields['email'].initial = self.instance.usuario.email | |
# Opcional | |
self.fields['usuario'].required = False | |
self.fields['usuario'].widget.attrs['disabled'] = 'disabled' | |
self.fields['senha'].required = False | |
self.fields['senha'].widget.attrs['disabled'] = 'disabled' | |
usuario = forms.RegexField(label=_("Username"), max_length=30, | |
regex=r'^[\w.@+-]+$', | |
help_text=_(u"Máximo de 30 letras. Permitidas letras, números e " | |
u"@/./+/-/_ somente."), | |
error_messages={ | |
'invalid': _(u"Permitido somente letras, números e " | |
u"@/./+/-/_ .")}) | |
senha = forms.CharField(max_length=30, widget=forms.PasswordInput) | |
nome = forms.CharField(max_length=30) | |
sobrenome = forms.CharField(max_length=30) | |
email = forms.EmailField(required=False, | |
widget=forms.TextInput(attrs={'class': 'vTextField'})) | |
cpf = BRCPFField(label='CPF') | |
def clean(self): | |
if self.cleaned_data.get('funcao') == 'motorista': | |
if (not self.cleaned_data.get('cnh') or | |
not self.cleaned_data.get('cnh_validade')): | |
raise forms.ValidationError( | |
u'Dados da CNH não podem estar vazios.') | |
return self.cleaned_data | |
def clean_usuario(self): | |
if not hasattr(self.instance, 'usuario'): | |
if User.objects.filter( | |
username=self.cleaned_data.get('usuario')).exists(): | |
raise forms.ValidationError( | |
u'Nome de usuário já está cadastrado.') | |
return self.cleaned_data.get('usuario') | |
def clean_cpf(self): | |
if hasattr(self.instance, 'cpf') and self.cleaned_data.get('cpf'): | |
try: | |
func = Funcionario.objects.get( | |
cpf=self.cleaned_data.get('cpf')) | |
if hasattr(self.instance, 'id') and self.instance.id: | |
if self.instance.id == func.id: | |
raise Funcionario.DoesNotExist | |
raise forms.ValidationError( | |
u'CPF pertence ao funcionário {}'.format( | |
func.usuario.get_full_name())) | |
except Funcionario.DoesNotExist: | |
return self.cleaned_data.get('cpf') | |
return self.cleaned_data.get('cpf') | |
def save(self, *args, **kwargs): | |
# Novo funcionário | |
if not hasattr(self.instance, 'usuario'): | |
user = User.objects.create_user( | |
username=self.cleaned_data.get('usuario'), | |
password=self.cleaned_data.get('senha')) | |
user.is_active = True | |
# Editar funcionário | |
else: | |
user = self.instance.usuario | |
user.email = self.cleaned_data.get('email') | |
user.first_name = unicode(self.cleaned_data.get('nome')) | |
user.last_name = unicode(self.cleaned_data.get('sobrenome')) | |
# Remove dos outros grupos | |
for group in user.groups.all(): | |
group.user_set.remove(user) | |
# Adiciona ao grupo | |
grupo, created = Group.objects.get_or_create( | |
name__iexact=self.cleaned_data.get('funcao')) | |
grupo.user_set.add(user) | |
user.is_staff = True | |
self.instance.usuario = user | |
user.save() | |
return super(FuncionarioForm, self).save(*args, **kwargs) | |
class FuncionarioAdmin(admin.ModelAdmin): | |
form = FuncionarioForm | |
list_display = ['usuario', 'usuario__nome', 'funcao', 'cpf', 'rg', | |
'usuario__email', 'obs', 'cnh', 'cnh_validade__data'] | |
list_display_links = ['usuario__nome'] | |
ordering = ['funcao', 'usuario__first_name'] | |
fieldsets = ( | |
(None, { | |
'fields': ( | |
('usuario', 'senha'), | |
('nome', 'sobrenome'), | |
'email', | |
'rg', 'cpf', 'funcao', 'obs') | |
}), | |
('Motorista', { | |
'classes': ('grp-collapse',), # grp-closed | |
'fields': ('cnh', 'cnh_validade') | |
}) | |
) | |
search_fields = ['usuario__first_name', 'usuario__last_name', | |
'usuario__email', 'funcao', 'cpf', 'rg'] | |
list_filter = ['funcao'] | |
def usuario__nome(self, obj): | |
return obj.usuario.get_full_name() | |
usuario__nome.short_description = u'Nome' | |
def usuario__email(self, obj): | |
return obj.usuario.email | |
usuario__email.short_description = u'Email' | |
def cnh_validade__data(self, obj): | |
if obj.cnh_validade: | |
return datetime.strftime(obj.cnh_validade, '%d/%m/%Y') | |
return '' | |
cnh_validade__data.short_description = u'validade' | |
def get_readonly_fields(self, request, obj=None): | |
""" Somente leitura ao editar """ | |
if obj: | |
return ['usuario', 'usuario__password'] | |
return [] | |
admin.site.register(Funcionario, FuncionarioAdmin) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Funcionario(models.Model): | |
""" Funcionários da empresa """ | |
class Meta: | |
verbose_name = _(u'Funcionário') | |
GERENTE = 'gerente' | |
SUPERVISOR = 'supervisor' | |
OPERACIONAL = 'operacional' | |
MOTORISTA = 'motorista' | |
PORTADOR = 'portador' | |
FUNCAO = ( | |
(GERENTE, 'Gerente'), | |
(SUPERVISOR, 'Supervisor'), | |
(OPERACIONAL, 'Operacional'), | |
(MOTORISTA, 'Motorista'), | |
(PORTADOR, 'Portador'), | |
) | |
usuario = models.OneToOneField(User, unique=True) | |
rg = models.CharField(_('identidade'), max_length=16) | |
cpf = models.CharField(_('CPF'), max_length=16, unique=True) | |
funcao = models.CharField(_(u'função'), choices=FUNCAO, max_length=16, | |
default=MOTORISTA) | |
cnh = models.CharField(_('CNH'), max_length=16, null=True, blank=True) | |
cnh_validade = models.DateField(_('CNH Validade'), null=True, blank=True) | |
obs = models.TextField(_(u'observação'), null=True, blank=True) | |
@staticmethod | |
def autocomplete_search_fields(): | |
return ("id__iexact", "dia__account",) | |
def __unicode__(self): | |
return u'{}'.format(self.usuario.get_full_name()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment