简体   繁体   中英

How to run python script in a django class-based view?

My Django app models.py has the following class:

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

I am using class-based views so my views.py file has the following class:

from django.views import generic
from django.views.generic.edit import CreateView

class ProjectCreate(CreateView):
    model = Project
    fields = ['name']

The HTTP form works perfectly and creates a new element in the database, but I need to call a function from an external python file upon the creation of a new instance of the class Project , the code I'm trying to run is:

import script
script.foo(self.object.name)

I'm trying to run the function foo inside the class ProjectCreate but I'm clueless, I tried using get and dispatch methods but it didn't work, I have read the documentation of CreateView but I couldn't find my answer.

Should I use function-based views? or is there a solution for class-based views?

Thank you very much.

You probably want to do this inside the model save method, rather than in the view, so it will be called whenever a new instance is created:

class Project(models.Model):
    ...
    def save(self, *args, **kwargs):
        if not self.pk:
            script.foo(self)
        return super(Project, self).save(*args, **kwargs)

If you're sure you only want to do it from that one view, then you could override the view's form_valid method instead:

class ProjectCreate(CreateView):
    def form_valid(self, form):
        response = super(ProjectCreate, self).form_valid(form)
        script.foo(self.object)
        return response

If you want to run your function only inside the view class you can simply override a form_valid method:

class ProjectCreate(CreateView):
    model = Author
    fields = ['name']

    def form_valid(self, form):
        result = super().form_valid(form)
        script.foo(self.object.name)
        return result

If you want to run the function after an every instance creation you can use signals or override model methods .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM