Set as default User logged in on the model | Django + Python3

0

I'm trying to learn Django, and with that I'm trying to create a simple ticket system.

I've made a lot of progress in my studies, but now I'm packing on the following problem.

How to do by default when saving a ticket, does Django save the currently logged in user?

Follow my codes from the file models.py

from django.contrib.auth.models import User
from django.db import models
from datetime import datetime

class Projeto(models.Model):
    """
        Classe que gere os Projetos
        Permite que se cadastre N usuários por Projeto
        Retorna:
            NOME_DO_PROJETO | SITE_DO_PROJETO
    """
    nome = models.CharField(max_length=100)
    site = models.CharField(max_length=200)
    informacoes = models.TextField(blank=True)
    usuarios = models.ManyToManyField(User, related_name='projetos')

    def __str__(self):
        return self.nome + " | " + self.site

class Ticket(models.Model):
    """
        Classe que gere os Tickets no sistema.
        Retorna:
            DATA HORA | TITULO DO CHAMADO
    """
    TIPOS_TICKET = (
        ('BUG', 'Bug'),
        ('URGENTE', 'Urgente'),
        ('FINANCEIRO', 'Financeiro'),
        ('MELHORIA', 'Melhoria')
    )
    STATUS_TICKET = (
        ('ABERTO', 'Aberto'),
        ('AGUARDANDO_CLIENTE', 'Aguardando Cliente'),
        ('EM_ANALISE', 'Em Análise'),
        ('FINALIZADO', 'Finalizado'),
        ('CANCELADO', 'Cancelado'),
    )
    titulo = models.CharField(max_length=200)
    conteudo = models.TextField()
    tipo = models.CharField(max_length=30, choices=TIPOS_TICKET, default='BUG')
    status = models.CharField(max_length=30, choices=STATUS_TICKET, default='ABERTO')
    projeto = models.ForeignKey(
        Projeto,
        on_delete=models.CASCADE,
        limit_choices_to={'usuarios':1}
    )
    usuario = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        null=True
    )
    data_abertura = models.DateTimeField('Data Abertura', auto_now_add=True)
    data_fechamento = models.DateTimeField('Data Fechamento', blank=True, null=True)

    def __str__(self):
        return str(datetime.strftime(self.data_abertura, "%d/%m/%y %H:%M") + " | " + self.titulo)

    def save(self, *args, **kwargs):
        self.usuario = User
        super(Ticket, self).save(*args, **kwargs)

class TicketMsg(models.Model):
    """
        Mensagens dos tickets
        Retorna:
            texto da mensagem
    """
    texto = models.TextField()
    ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE)
    data_resposta = models.DateTimeField('Data Resposta')

    def __str__(self):
        return str(self.texto)

And my file admin.py

from django.contrib import admin
from django.contrib.auth.models import User
from .models import Ticket, TicketMsg, Projeto

# Register your models here.
class ProjetoAdmin(admin.ModelAdmin):
    model = Projeto
    filter_horizontal = ('usuarios',)

class TicketAdmin(admin.ModelAdmin):
    model = Ticket
    exclude = ('status', 'data_fechamento', 'data_abertura', 'usuario')
    list_display = ('titulo', 'tipo', 'status', 'projeto', 'data_abertura')
    list_filter = ('projeto', 'tipo', 'status')

    def get_ordering(self, request):
        return ['data_abertura']

admin.site.register(Projeto, ProjetoAdmin)
admin.site.register(Ticket, TicketAdmin)
admin.site.register(TicketMsg)

This is the result of the listing so far, using Django's ADMIN

Theideaisthatwhenthepersonentersaticket,thesystemwillidentifywhichuserdidit.

I'vebeenabletogetthesystemtofilterwhichprojectsauserhastherighttoopenticketfor.

NowthesystemhastosavetheloggedinuserIDsothatIcanidentifywhoopenedtheticket.

Followformimage:

All help is welcome! Thanks guys!

    
asked by anonymous 23.02.2017 / 15:12

1 answer

0

There is a method called .save_model in ModelAdmin that has the purpose of making pre and post save operations.

class TicketAdmin(admin.ModelAdmin):
...

def save_model(self, request, obj, form, change):
    obj.user = request.user
    super(ArticleAdmin, self).save_model(request, obj, form, change)

More detailed documentation ModelAdmin.save_model .

    
24.02.2017 / 12:45