python - modelos - formularios personalizados django
El modelo Django se guarda dos veces después de crear (1)
No puedo entender cómo se guarda mi modelo dos veces. El modelo se llama Job
. Si el cliente crea una orden, se crea la instancia de Job
. Después de la creación, hay una señal, que alerta al administrador que el nuevo objeto Job
ha sido creado o editado.
@receiver(post_save,sender=Job)
def alert_admin(sender,instance,created,**kwargs):
if created:
email.AdminNotifications.new_order(instance)
else:
email.AdminNotifications.edited_order(instance)
EDITAR: He descubierto qué causa el problema, es una señal (muy abajo de la pregunta). Pero, sí necesito esta señal así que todavía no puedo entender cómo hacer que esto funcione ...
El problema es que el Admin
recibe dos correos electrónicos después de que el User
crea un Job
. Un correo electrónico indica que se ha creado el pedido y el segundo correo electrónico indica que se ha editado el pedido.
Sospecho que se debe a que reescribí el método save
e init
para crear algo así como signal
cuando se modifica el atributo Job
- approved
. Encuentro ese consejo aquí. PREGUNTA Es porque después de crear un Job
, el administrador tiene que aprobarlo, simplemente cambie el valor de Bool
del atributo approved
del objeto de Job
.
Adjunto view
, donde se crea el Job
y el modelo de Job
.
VER:
def create_order(request):
LanguageLevelFormSet = formset_factory(LanguageLevelForm, extra=5, max_num=5)
language_level_formset = LanguageLevelFormSet(request.POST or None)
job_creation_form = JobCreationForm(request.POST or None, request.FILES or None)
context = {''job_creation_form'': job_creation_form,
''formset'': language_level_formset}
if request.method == ''POST'':
if job_creation_form.is_valid() and language_level_formset.is_valid():
cleaned_data_job_creation_form = job_creation_form.cleaned_data
cleaned_data_language_level_formset = language_level_formset.cleaned_data
for language_level_form in [d for d in cleaned_data_language_level_formset if d]:
language = language_level_form[''language'']
level = language_level_form[''level'']
Job.objects.create(
customer=request.user,
text_to_translate=cleaned_data_job_creation_form[''text_to_translate''],
file=cleaned_data_job_creation_form[''file''],
short_description=cleaned_data_job_creation_form[''short_description''],
notes=cleaned_data_job_creation_form[''notes''],
language_from=cleaned_data_job_creation_form[''language_from''],
language_to=language,
level=level,
)
return HttpResponseRedirect(''/order-success'')
else:
return render(request, ''auth/jobs/create-job.html'', context=context)
return render(request, ''auth/jobs/create-job.html'', context=context)
TRABAJO:
class Job(models.Model):
customer = models.ForeignKey(User, related_name=''orders'', help_text=_("Customer"), on_delete=models.CASCADE)
translator = models.ForeignKey(User, related_name=''jobs'', null=True, blank=True, help_text=_(u"Translator"))
price = models.FloatField(null=True, blank=True, help_text=_(u"Price"))
language_from = models.ForeignKey(Language, related_name=''jobs_from'', null=True)
language_to = models.ForeignKey(Language, related_name=''jobs_to'', null=True)
short_description = models.CharField(max_length=40, blank=False,
help_text=_(u"Very short description of this order"))
notes = models.TextField(help_text=_("Notes"))
text_to_translate = models.TextField(verbose_name=''Text to translate'', blank=True, null=True,
help_text=u"Text, ktorý chcete preložiť (ak neprikladáte súbor).")
file = models.FileField(null=True, blank=True, help_text=u"Upload file")
level = models.ForeignKey(Level, null=False, default=None)
delivery_date = models.DateField(null=True, blank=True, help_text=_(''Deadline''))
PROGRESS_CHOICES = (
(''translator_not_assigned_yet'', ''Translator not assigned yet''),
(''in_translation_process'', ''In translation process''),
(''translated'', ''Translated''),
(''complete'', ''Complete'')
)
progress = models.CharField(choices=PROGRESS_CHOICES, max_length=40, default=''translator_not_assigned_yet'')
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=False)
is_done = models.BooleanField(default=False)
approved = models.BooleanField(default=False)
__original_approved = None
def __init__(self, *args, **kwargs):
super(Job, self).__init__(*args, **kwargs)
self.__original_approved = self.approved
def save(self, force_insert=False, force_update=False, *args, **kwargs):
if self.approved != self.__original_approved and self.approved == True:
send_job_alert(self)
else:
pass
super(Job, self).save(force_insert, force_update, *args, **kwargs)
self.__original_approved = self.approved
@staticmethod
def get_approved_pending_jobs():
approved_pending_jobs = Job.objects.filter(approved=True, delivery__status=''pending'')
return approved_pending_jobs
@staticmethod
def get_open_jobs_for_user(user):
results = set()
candidate_jobs = Job.objects.filter(language_from__in=user.userprofile.languages_verified,
language_to__in=user.userprofile.languages_verified,
delivery__status=''pending'',
).exclude(customer=user)
for job in candidate_jobs:
if job.level.name <= user.userprofile.language_levels.get(language=job.language_to).level.name:
results.add(job)
return list(results)
@property
def has_translator(self):
return self.translator_id is not None
Señal de entrega:
@receiver(post_save,sender=Job)
def create_delivery(sender,instance,created,**kwargs):
if created:
delivery,created_delivery = Delivery.objects.get_or_create(job=instance)
instance.delivery = delivery
delivery.save()
instance.save()
agregue dispatch_uuid
mientras conecta el receptor según los documentos
def create_delivery(sender, instance, created, **kwargs):
if created:
delivery,created_delivery = Delivery.objects.get_or_create(job=instance)
instance.delivery = delivery
delivery.save()
instance.save()
post_save.connect(create_delivery, sender=Job, dispatch_uid="my_unique_identifier")