English 中文(简体)
django信号,如何使用“instance”
原标题:django signals, how to use "instance"

我正试图建立一个系统,使用户能够上载齐pfile,然后利用“空洞”信号提取。

class Project:
    ....
    file_zip=FileField(upload_to= projects/%Y/%m/%d )

@receiver(post_save, sender=Project)
def unzip_and_process(sender, **kwargs):
    #project_zip = FieldFile.open(file_zip, mode= rb )
    file_path = sender.instance.file_zip.path
    with zipfile.ZipFile(file_path,  r ) as project_zip:
        project_zip.extractall(re.search( [^s]+(?=.zip) , file_path).group(0))
        project_zip.close()

在提供正确档案途径时,方法可进行罚款(在此情况下,需要提供<条码>内容.file_zip.path)。 然而,我无法以信号接手。 Django信号文件不明确,没有实例。 因此,我做了些什么?

最佳回答

实际上, Django有关信号的文件非常清楚,确实有实例。

在您的情况下,post_save 信号发出以下论点:sender (模型类别),instance (类别sender,created,raw/code>,和using。 如果您需要查阅<代码>instance,请您以身边的kwargs[e>,或更好地改变你的追随职能,接受以下论点:

@receiver(post_save, sender=Project)
def unzip_and_process(sender, instance, created, raw, using, **kwargs):
    # Now *instance* is the instance you want
    # ...
问题回答

这在连接<代码>时对我有利。 Django 信号:

这里是models.py:

class MyModel(models.Model):
    name = models.CharField(max_length=100)

www.un.org/Depts/DGACM/index_french.htm

@receiver(post_save, sender=MyModel)
def print_name(sender, instance, **kwargs):
    print  %s  % instance.name 




相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签