创建

时间:2016-06-03 18:22:28

标签: python django django-models django-views

我无法弄清楚我的模型是如何被保存两次的。该模型称为Job。如果客户创建订单,则会创建Job实例。创建后,会有一个信号,警告管理员已创建或编辑了新的Job对象。

@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)

编辑:我发现了导致问题的原因,这是一个信号(问题的最底层)。但是,我确实需要这个信号,所以我仍然无法弄清楚如何使这项工作......

问题是AdminUser创建Job后收到了两封电子邮件。一封电子邮件是订单已创建,第二封电子邮件告知订单已被编辑。

我怀疑这是因为我重写了saveinit方法,创建类似signal的内容,Job属性 - {{1} }改变了。 我在此处找到了相关建议SO QUESTION这是因为在创建approved之后,管理员必须批准它 - 只需更改Job Bool approved对象属性的值Job

我正在附加view,其中Job已创建,模型Job

查看:

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)

JOB:

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

投放信号:

@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()

1 个答案:

答案 0 :(得分:0)

按照docs

连接接收器时添加dispatch_uuid
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")