Объект типа Queue не сериализуем в формате JSON
Я создаю API отдыха для приложения службы поддержки и сталкиваюсь с проблемой при преобразовании формы в сериализатор. Уже существует django-application django-helpdesk, и я создаю REST API поверх него. Я новичок в структуре отдыха django, и документация недостаточно ясна. Я прошу предложить мне способ сделать это или возможно обходное решение.
Код для форм:
class AbstractTicketForm(forms.Form):
"""
Contain all the common code and fields between "TicketForm" and
"PublicTicketForm". This Form is not intended to be used directly.
"""
queue = forms.ChoiceField(
widget=forms.Select(attrs={'class': 'form-control'}),
label=_('Queue'),
required=True,
choices=()
)
title = forms.CharField(
max_length=100,
required=True,
widget=forms.TextInput(attrs={'class': 'form-control'}),
label=_('Summary of the problem'),
)
body = forms.CharField(
widget=forms.Textarea(attrs={'class': 'form-control'}),
label=_('Description of your issue'),
required=True,
help_text=_('Please be as descriptive as possible and include all details'),
)
priority = forms.ChoiceField(
widget=forms.Select(attrs={'class': 'form-control'}),
choices=Ticket.PRIORITY_CHOICES,
required=True,
initial='3',
label=_('Priority'),
help_text=_("Please select a priority carefully. If unsure, leave it as '3'."),
)
due_date = forms.DateTimeField(
widget=forms.TextInput(attrs={'class': 'form-control'}),
required=False,
label=_('Due on'),
)
def _create_ticket(self):
queue = Queue.objects.get(id=int(self.cleaned_data['queue']))
ticket = Ticket(title=self.cleaned_data['title'],
submitter_email=self.cleaned_data['submitter_email'],
created=timezone.now(),
status=Ticket.OPEN_STATUS,
queue=queue,
description=self.cleaned_data['body'],
priority=self.cleaned_data['priority'],
due_date=self.cleaned_data['due_date'],
)
return ticket, queue
def _create_follow_up(self, ticket, title, user=None):
followup = FollowUp(ticket=ticket,
title=title,
date=timezone.now(),
public=True,
comment=self.cleaned_data['body'],
)
if user:
followup.user = user
return followup
@staticmethod
def _send_messages(ticket, queue, followup, files, user=None):
context = safe_template_context(ticket)
context['comment'] = followup.comment
messages_sent_to = []
if ticket.submitter_email:
send_templated_mail(
'newticket_submitter',
context,
recipients=ticket.submitter_email,
sender=queue.from_address,
fail_silently=True,
files=files,
)
messages_sent_to.append(ticket.submitter_email)
if ticket.assigned_to and \
ticket.assigned_to != user and \
ticket.assigned_to.usersettings_helpdesk.settings.get('email_on_ticket_assign', False) and \
ticket.assigned_to.email and \
ticket.assigned_to.email not in messages_sent_to:
send_templated_mail(
'assigned_owner',
context,
recipients=ticket.assigned_to.email,
sender=queue.from_address,
fail_silently=True,
files=files,
)
messages_sent_to.append(ticket.assigned_to.email)
if queue.new_ticket_cc and queue.new_ticket_cc not in messages_sent_to:
send_templated_mail(
'newticket_cc',
context,
recipients=queue.new_ticket_cc,
sender=queue.from_address,
fail_silently=True,
files=files,
)
messages_sent_to.append(queue.new_ticket_cc)
if queue.updated_ticket_cc and \
queue.updated_ticket_cc != queue.new_ticket_cc and \
queue.updated_ticket_cc not in messages_sent_to:
send_templated_mail(
'newticket_cc',
context,
recipients=queue.updated_ticket_cc,
sender=queue.from_address,
fail_silently=True,
files=files,
)
class PublicTicketForm(AbstractTicketForm):
"""
Ticket Form creation for all users (public-facing).
"""
submitter_email = forms.EmailField(
widget=forms.TextInput(attrs={'class': 'form-control'}),
required=True,
label=_('Your E-Mail Address'),
help_text=_('We will e-mail you when your ticket is updated.'),
)
def __init__(self, *args, **kwargs):
"""
Add any (non-staff) custom fields that are defined to the form
"""
super(PublicTicketForm, self).__init__(*args, **kwargs)
if hasattr(settings, 'HELPDESK_PUBLIC_TICKET_QUEUE'):
self.fields['queue'].widget = forms.HiddenInput()
if hasattr(settings, 'HELPDESK_PUBLIC_TICKET_PRIORITY'):
self.fields['priority'].widget = forms.HiddenInput()
if hasattr(settings, 'HELPDESK_PUBLIC_TICKET_DUE_DATE'):
self.fields['due_date'].widget = forms.HiddenInput()
# self._add_form_custom_fields(False)
def save(self, user):
"""
Writes and returns a Ticket() object
"""
ticket, queue = self._create_ticket()
if queue.default_owner and not ticket.assigned_to:
ticket.assigned_to = queue.default_owner
ticket.save()
# self._create_custom_fields(ticket)
followup = self._create_follow_up(
ticket, title=_('Ticket Opened Via Web'), user=user)
followup.save()
# files = self._attach_files_to_follow_up(followup)
self._send_messages(ticket=ticket,
queue=queue,
followup=followup,
files=files)
return ticket
'''
I am trying to recreate the same logic using a serialzer, I tried using drf_braces formserializer but that didn't work, my code for serializer is:
'''
class AbstractTicketSerializer(serializers.Serializer):
queue = serializers.ChoiceField(
required=True,
choices=(),
)
title = serializers.CharField(
max_length=100,
required=True,
)
description = serializers.CharField(
required=True,
)
priority = serializers.ChoiceField(
choices=Ticket.PRIORITY_CHOICES,
required=True,
initial='3',
)
due_date = serializers.DateTimeField(
required=False,
)
attachment = serializers.FileField(
required=False,
)
def _create_ticket(self):
queue = Queue.objects.get(id=int(self.validated_data['queue']))
queue = QueueSerializer(queue)
ticket = Ticket(title=self.validated_data['title'],
submitter_email=self.cleaned_data['submitter_email'],
created=timezone.now(),
status=Ticket.OPEN_STATUS,
queue=queue,
description=self.validated_data['description'],
priority=self.validated_data['priority'],
due_date=self.validated_data['due_date'],
)
return ticket, queue
def _create_follow_up(self, ticket, title, user=None):
followup = FollowUp(ticket=ticket,
title=title,
date=timezone.now(),
public=True,
comment=self.validated_data['description'],
)
if user:
followup.user = user
return followup
class PublicTicketSerializer(AbstractTicketSerializer):
queue = QueueSerializer()
queue = serializers.ChoiceField(
required=True,
choices = [('', '--------')] + [(q.id, q.title) for q in Queue.objects.filter(allow_public_submission=True)],
)
submitter_email = serializers.EmailField(required=False,)
def __init__(self, *args, **kwargs):
super(PublicTicketSerializer, self).__init__(*args, **kwargs)
def save(self, user):
"""
Writes and returns a Ticket() object
"""
ticket, queue = self._create_ticket()
if queue.default_owner and not ticket.assigned_to:
ticket.assigned_to = queue.default_owner
ticket.save()
followup = self._create_follow_up(
ticket, title=_('Ticket Opened Via Web'), user=user)
followup.save()
# files = self._attach_files_to_follow_up(followup)
# self._send_messages(ticket=ticket,
# queue=queue,
# followup=followup,
# files=files)
return ticket
'''
I am getting the error 'TypeError at /api/user/dashboard/
Object of type Queue is not JSON serializable'