0

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.

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Thank you, this solved the problem. but overriding the save() function in the model class seems like a better solution. Thank you again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.