Reputation: 359
I'm learning about Django, and challenged myself to create an small Ticket System as study case.
Got some things done, but now i'm with a little problem.
How to when i save an "Ticket", Django get current logged in user and set as default on "usuario" field from my Ticket model?
This is my models.py
file:
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 admin.py
file:
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 my ticket list from Django Admin.
The idea, is to use default Django user system to identify who is trying to open an ticket.
I made with success the system filter what projects each user can open tickets to, but now i can't set as default value who is the current user who are typing the new Ticket.
This is my form actually.
All help is welcome! Thank you guys!
Upvotes: 0
Views: 1880
Reputation: 1010
The currently loggedin user is attached on the request object as part of Djangos Request-Response-Lifecycle. You can not access the request in methods of the model (like you wanted to do in the save() method).
However, you can override the save_model() method of the admin form, where the request is available:
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']
def save_model(self, request, obj, form, change):
obj.usuario = request.user
super(TicketAdmin, self).save_model(request, obj, form, change)
There is no need to override the save() method on your model then.
More info about the ModelAdmin on the official Django documentation: https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model
Upvotes: 2