Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: persisting sklearn model's using joblib
I have a django app with a view which fits a new TfidfVectorizer each time it is called. This requires doing a lot of duplicate work since the data I am fitting to does not change. To eliminate this duplicate work, I tried to persist the vectorizer to file using joblib. However, when I run the django app I receive the following error: Internal Server Error: /get_results/ Traceback (most recent call last): File "//anaconda/envs/xkcd/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "//anaconda/envs/xkcd/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "//anaconda/envs/xkcd/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/jkarimi91/Projects/xkcd_search/xkcd_project/search/views.py", line 12, in get_results results = [r['img'] for r in get_search_results(query)] File "/Users/jkarimi91/Projects/xkcd_search/xkcd_project/search/views.py", line 16, in get_search_results model = joblib.load('search/search_engine/model.p') File "//anaconda/envs/xkcd/lib/python2.7/site-packages/sklearn/externals/joblib/numpy_pickle.py", line 575, in load obj = _unpickle(fobj, filename, mmap_mode) File "//anaconda/envs/xkcd/lib/python2.7/site-packages/sklearn/externals/joblib/numpy_pickle.py", line 507, in _unpickle obj = unpickler.load() File "//anaconda/envs/xkcd/lib/python2.7/pickle.py", line 864, in load dispatch[key](self) File "//anaconda/envs/xkcd/lib/python2.7/pickle.py", line 1096, in load_global klass = self.find_class(module, name) File "//anaconda/envs/xkcd/lib/python2.7/pickle.py", line 1132, in find_class klass = getattr(mod, name) AttributeError: 'module' object has no attribute 'tokenize' The error appears to be a result of the fact thatjoblib uses pickle under the hood. As noted in the pickle documentation, … -
Save form as foreign key's object
There is 2 models with a ForeignKey Relationship, Profile model and Article model, I would like to save the connected user as profile.user when an Article object is created. Here is the error I get with the code below : 'NoneType' object has no attribute 'user' models.py : class Profile(models.Model): name = models.CharField(max_length=120) user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True) class Gig(models.Model): profile = models.ForeignKey(Profile, null=True) title = models.CharField(max_length=100, unique=True) Here is my view for where I want to save profile.user if request.method == 'POST': form = GigForm(request.POST, request.FILES) if form.is_valid(): save_it = form.save() > save_it.profile.user = request.user #here save_it.save() return redirect(reverse('own_gigs_details')) else: form = GigForm() What am I doing wrong ? -
Why can't I show a model's foreign key's username on my template?
I have 2 apps, the first one is the user's profile, the second one is user's article, I put a ForeignKey on the article to link it with the username of user's profile, but I'm having some trouble retrieving that same username. How can I do it ? Here are my models : profiles/models.py class Profile(models.Model): name = models.CharField(max_length=120) user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True) ... article/models.py from profiles.models import Profile class Article(models.Model): profile = models.ForeignKey(Profile, null=True) title = models.CharField(max_length=100, unique=True) date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de parution") ... On my views I'm just getting all article objects 'articles':Article.objects.all() So why I can't access the name or user.username of profile/models.py from article/templates/page.html ? page.html {% for article in articles %} {{ article.profile.name }} {% endfor %} -
Django Cannot Import File in Subdirectory
I'm almost certain I'm missing something obvious, but imports have plagued me for a while. I have the following app structure in a larger Django project: \reporting\ \reporting\__init__.py \reporting\<all other default django files> \reporting\utils\__init__.py \reporting\utils\base_file.py \reporting\utils\appname_reporting.py I am trying to import appname_reporting to my \reporting\views.py. I have tried import utils.appname_reporting, from utils import appname_reporting, and from .utils import appname_reporting. All of them give me an error: ImportError: No module named 'appname_reporting'. There are no other files importing appname_reporting.py. And appname_reporting.py imports base_file.py. -
How to change widgets used in admin?
Is it possible to overwrite the files django / forms / templates / django / forms / widgets /? With admin HTMLs you can override creating a directory within templates with the admin name and then create the HTML with the same Django name. With Widgets, is it possible? I'm wondering why I'm creating an application to change the look of admin, but I want to make a relatively heavy change in the widgets. If changing the HTML of widgets in this way is not correct, how can I do this? For example: In the inclusion of a user there is a widget to include authorizations to a users, they are two selects, I would like to change this HTML. -
Why won't my startup.sh run from Docker-Compose Command?
I have a startup.sh specifically for Django, but it does not seem to be running the commands when I run my docker-compose. Snippet of docker-compose: web: restart: always build: ./web expose: - "8000" links: - postgres:postgres env_file: .env environment: DEBUG: 'true' command: ./startup.sh After I build and run docker-compose, here is the directory structure inside the web container: /proj /accounts /projname /tests /fixturse /manage.py /startup.sh permissions for startup.sh -rwxr-xr-x 1 root root 376 Jan 8 21:33 startup.sh startup.sh #!/bin/bash python manage.py runserver 0.0.0.0:8000 python manage.py makemigrations accounts python manage.py migrate python manage.py check_permissions python manage.py cities --import=country --force echo "removing extra countries" python manage.py removecountries echo "importing cities" python manage.py cities --import=city python manage.py cities --import=postal_code after I run docker-compose I have to manually open a shell in the running container and run ./startup.sh manually to get it to work. Interesting side note: Although none of the commands inside .startup.sh appear to be working when the command is issued through the Docker-Compose, I am still able to hit urls which means python manage.py runserver is successfully being calledsomewhere. I doubt it is from startup.sh as no other command in this script is being ran. -
Download (user) uploaded files django
In my webapplications users can upload files (pdf's, ms-docs etc). I store the files in /media/, but I cannot seem to find a way to make the files downloadable again on the website (for other users). This is the function in views.py that handles the upload form: def upload(request): if request.method == "POST": form = UploadForm(request.POST or None, request.FILES or None) if form.is_valid(): resourceupload = form.save(commit=False) resourceupload.uploadedBy = request.user resourceupload.upload_date = timezone.now() resourceupload.save() return redirect('course', pk=resourceupload.course.pk) else: form = UploadForm() return render(request, 'main/upload.html', {'form': form}) and this is the associated template: <form method="POST" enctype="multipart/form-data" class="post-form"> {% csrf_token %} <table> <tr> <td>{{ form.title.label_tag }}</td> <td>{{ form.title }}</td> </tr> <!--<tr> <td>{{ form.major.label_tag }}</td> <td id="majorcs" >{{ form.major }}</td> </tr>--> <tr> <td>{{ form.course.label_tag }}</td> <td id="coursejs">{{ form.course }}</td> <td> <button type="button" onclick="window.document.location='{% url "addcourse" %}'"}>Add Course</button> </td> </tr> <tr> <td>{{ form.resourcetype.label_tag }}</td> <td>{{ form.resourcetype }}</td> </tr> <tr> <td>{{ form.resourcefile.label_tag }}</td> <td>{{ form.resourcefile }}</td> </tr> </table> <button type="submit" class="save btn btn-blog pull-right">SAVE</button> </form> The uploading goes fine, but I cannot seem to find a way to make the resourcefile downloadble. This is a snippet from the template where I have a list of the resources that can be downloaded: {% for res in resources%} … -
Can I pay someone to help me learn - Django, python, vagrant, postgress and maybe some Node.JS too [on hold]
I'm in a really awkward place right now, I'm locked out of my primary OS (Ubuntu) and have to do everything through Vagrant VMs. I'm learning Django and python for the first time, and also PostgreSQL. And any Node.JS or front end frameworks like angularJS and JQuery would be much appreciated too, but its the back end stuff I really need to learn fast. Especially working with Django on postgres database hosted on Heroku. Having to learn Windows after being on Ubuntu for 10 years has set me back immensely, I've been spending a good 50% of my time just figuring out how to set things up with Vagrant and find ways around the traps and limitations of Windows. I really need help getting up and running because the project I'm on now is extremely important, and time is so critical, what I do now will determine have huge impact on how the future turns out. I would DEEPLY appreciate if someone can teach me, and help me get on my feet with all this. My main experience is with PHP and MySQL, I know a good bit of bash scripting and a little bit of Perl, but everything in … -
Extending wagtail Streamfields in an inherited class
I have a abstract class that have ha StreamField in it. I also have a class CustomPage that inherits from BasePage. I want CustomPage to add a new StructBlock to content. How do i do that? class BasePage(Page): content = StreamField([ ('ad', ...), ('text', ...), ('img', ...), ]) content_panels = Page.content_panels + [ StreamFieldPanel('content'), ] class Meta: abstract = True class CustomPage(BasePage): # add ('custom_block', ...) to content streamfield. -
Can I use crispy forms without bootstrap?
I want to use crispy forms with django. I've created a responsive website without using bootstrap. Is it possible to implement crispy forms without bootstrap? If not, what are the best alternatives to it? -
Does not authenticate user django-social-auth?
User clicked to link /login/steam. After that all works propetly (django.contrib.auth user instance and social_auth user instance create fine, custom pipeline works. But after when i try to use request.user in my view after login with steam i have error 'AnonymousUser' object is not iterable My settings.py file SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.social_user', # custom pipeline 'markers.pipeline.add_steam_data_marker', # 'social.pipeline.user.get_username', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details', ) My custom pipeline.py in app def add_steam_data_marker(strategy, details, backend, uid, *args, **kwargs): if backend.name == 'steam': try: Model.objects.get(steam_user_id=uid) return redirect('/home/') except ObjectDoesNotExist: Model.objects.create( ........, ) return redirect('/model/add/') -
Download local file link in html django template
Basically I have a django template from which I show data about a document and I want a link to download the file. I tried something like this but it is not working: <div class="metadata-container"> <div class="metadata-title"> <div>Version</div> <div>Author</div> <div>File</div> </div> <div class="metadata-content"> <div>{{ document.version }}</div> <div>{{ document.author }}</div> <a href=document.file download><div>{{ document.file }}</div> </div> </div> The filename in format '/documents/2017/filename.txt' is in document.file variable or however it's called. How can I use it in the ? or how can I make it work? -
Exception handling for missing parameters of a view passed on as json data
Lately, I found out the elementary truth related to exception handling - our server should rarely (preferably, never) through 5XX error. Having said that, let's consider a REST view with some parameters, and a respective URL. urlpatterns = [ url(r'^some_view/', some_view), ] @api_view(['POST']) def some_view(request): # ... param1 = request.data['param1'] In this code, I have to manually handle the exception where the developer calls some_view without assigning value to param1, otherwise - if I don't handle this case explicitly - they will get 500 error (MultipleKeyValueError) which is bad. And we have a dilemma: - Handling it will cause irritating and repetitive try-except blocks, especially when we have multiple params - Not handling will lead to 500 error The solution is to rewrite the view this way: urlpatterns = [ url(r'^some_view/(?P<param1>\w+/', some_view), ] @api_view(['POST']) def some_view(request, param1): # ... Here Django will throw 400 exception - as opposed to 500 - saying that url is not found. But on the other hand, the first option (where I use request.data['param1']) gives the pleasant benefit that I can call the REST resource not only from an outside app, but also from my web app submitting params by serializing HTML form. So here … -
django form value quoted in funny characters u'
I have used django-crispy-forms app to create it. One input in the form is multiple checkboxes which people can click. I am having a form validation problem because the value coming from post request is preceded and appended by some funny character set. Below is the log. [(u'rich_kids', u'rich_kids'), (u'richadults', u'richadults'), (u'pooradults', u'pooradults')] trying to use POST data richadults Campaign_Target_AudienceSelect a valid choice. [u'richadults'] is not one of the available choices.campaign_target_audienceThis field is required. form validation fails Actually I need the value to be richadults as shown just before error line but it is coming out to be like [u'richadults'] as shown in log. Please advise on how to correct it. -
how to use $resource, where to start
I am trying to understand $resource, but dont know where to start. I am trying to save data into db using REST API. This is my form: <ion-view title="Add New Device" ng-controller="addDevice"> <ion-content> <form name="addDeviceForm" ng-init="setFormScope(this)" data-ng-submit="deviceSubmit()"> <div class="list" style="background:#ffffff;"> <div class="item item-divider"> Device Info </div> <label class="item item-input item-stacked-label"> <span class="input-label">Name</span> <input type="text" placeholder="Name" ng-model="newDevice.name"> </label> <label class="item item-input item-stacked-label"> <span class="input-label">Icon</span> <input type="text" placeholder="Icon" ng-model="newDevice.icon"> <select ng-model="newDevice.icon" ng-options="ionicon.name for ionicon in ionicons"></select> </label> <div class="item item-divider"> Location </div> <label class="item item-input item-select"> <div class="input-label"> Select a Location </div> <select ng-model="newDevice.locationSelect" ng-options="o.id as o.name for o in locations"></select> </label> <div class="item item-divider"> Select Action </div> <label class="item item-input item-select"> <div class="input-label"> Action </div> <select ng-model="newDevice.actionSelect" ng-options="o.id as o.name for o in actions"></select> </label> <div class="item item-divider"> Featured </div> <li class="item item-toggle"> Featured <label class="toggle toggle-balanced"> <input type="checkbox" checked ng-model="newDevice.featured"> <div class="track"> <div class="handle"></div> </div> </label> </li> </div> <div class="padding"> <button class="button button-balanced" ng-click=""> Add Device </button> </div> </form> </ion-content> Then this is my angular code, but for now if I add data, they will only be added in cache, if I refres they will be flushed, so I want to make permanent changes in DB, adding data. .controller('addDevice', function … -
Django + gunicorn + nginx 400 bad request
I am getting 400 bad request error by accessing domain name (ip is fine) in django + gunicorn + nginx configuration. I forgot to change ip address in dns settings. After I did it, I found that 400 error is still there. I waited for few days for DNS provider to update a thing, then I checked what host is owned by domain and is changed but 400 error still appears when trying to access its by domain name. The only thing I found in other questions, that may be wrong is ALLLOWED_HOSTS which was correct. But then I discovered, as far as it's Digital Ocean pre-configured project, they made their own implementation in the very bottom of settings.py . But I don't quite get it? How can I allow my domain name? Or will it work as well the old way? import os import netifaces def ip_addresses(): ip_list = [] for interface in netifaces.interfaces(): addrs = netifaces.ifaddresses(interface) for x in (netifaces.AF_INET, netifaces.AF_INET6): if x in addrs: ip_list.append(addrs[x][0]['addr']) return ip_list ALLOWED_HOSTS = ip_addresses() -
Django signal calls another instead of finish
I'm adding PayPal payment to my Django project. I use Django-paypal app with custom form. Everything seems to work correctly, signal is recieved but the reciever doesn't finish correctly. Execution suddenly jumps to dispatcher.py Signal.send() method (I can see it in PyCharm debug mode). To clearly explain what is happening I have to add couple of screenshots from debugger so the post is longer than usual. When debuuger is on this line: item_number = f.get['item_number{}'.format(i + 1)] it doesn't continue to the line below but jumps to dispatcher.py. This is the reciever in models.py: def recieve_payment(sender, **kwargs): ipn_obj = sender f = parse_url_params_naked(ipn_obj.query) if ipn_obj.payment_status == ST_PP_COMPLETED: if ipn_obj.receiver_email != settings.PAYPAL_RECEIVER_EMAIL: # Not a valid payment return # Undertake some action depending upon `ipn_obj`. if ipn_obj.custom == "Upgrade all users!": for i in ipn_obj.num_cart_items: item_number = f.get['item_number{}'.format(i + 1)] # IT JUMPS FROM THIS LINE amount = decimal.Decimal(f.args['mc_gross_{}'.format(i + 1)]) Payment.objects.create(invoice=Invoice.objects.get(identificator=item_number),total_price=amount) print amount print 'COMPLETED' else: print 'BAD' # ... valid_ipn_received.connect(recieve_payment) THE FIRST THING - I PAY ORDER THROUGH PAYPAL When I pay the order, it stops in this breakpoint and state: Now I'm going line by line in debugger: When the debugger is here (on first or second line): … -
Django execution test order changes the output of inner function call
This is driving me crazy. I'm trying to write some test for a template tag I wrote but it seems that the order of the test methods in the TestCase class changes the output of the function I'm calling inside them. This is my code (with only the minimum tests that get me the error). build_context() is an imported recursive function that traverse the urlconf inclusion of the project and produce the context for my custom tag. I have put self.assertTrue(False, str(context)) as a quick way to check the content of my variable: class TestContext(TestCase): def test_1_context_structure(self): context = build_context(ALL_NAMES) self.assertTrue(False, str(context)) # ... actual asserts... def test_7_wildcard_outer_namespace_context(self): context = build_context('app2:' + ALL_NAMES) self.assertTrue(False, str(context)) # ... actual asserts... The output is: ====================================================================== FAIL: test_1_context_structure (test_context.TestContext) ---------------------------------------------------------------------- ... AssertionError: False is not true : {'object_name': 'Url', 'patterns': OrderedDict([('app1:app1_view3', '/app1/view3'), ('app1_view2', '/app1/view2'), ('app2:app2_view1', '/app2/view1'), ('app2:app2_view2', '/app2/view2'), ('app2:app2_view3', '/app2/view3'), ('app2:app3:app3_view1', '/app2/app3/view1'), ('app2:app3:app3_view2', '/app2/app3/view2'), ('app2:app3:app3_view3', '/app2/app3/view3')])} ====================================================================== FAIL: test_7_wildcard_outer_namespace_context (test_context.TestContext) ---------------------------------------------------------------------- ... AssertionError: False is not true : {'object_name': 'Url', 'patterns': OrderedDict([('app1:app1_view3', '/app1/view3'), ('app1_view2', '/app1/view2'), ('app2:app2_view1', '/app2/view1'), ('app2:app2_view2', '/app2/view2'), ('app2:app2_view3', '/app2/view3'), ('app2:app3:app3_view1', '/app2/app3/view1'), ('app2:app3:app3_view2', '/app2/app3/view2'), ('app2:app3:app3_view3', '/app2/app3/view3')])} here, the output of test_1 is correct, while the output of test_7 is not. BUT If … -
How to create a progressbar in Django
I need to know how can we create progress-bar in Django . In my case, I have to wait some more time during a request-response process.So I need to represent the process completion status using a progress-bar. How it be possible ? -
Receive data from android in python
Currently , I am new to both python and python framework django. I want to receive some data to my web app. Although that data needs to be saved in database but it requires some processing aswell. (That is why i think Django restframework is out of question or may be overhead). I simply dont get what happens where due to serializer and stuff. In PHP , we simply would have get data by $_GET['data']. But can you help me get this data in django. What will be in urls.py , setting.py and views.py. Thanks. I can add more info here if required . -
Using ManyToManyFields() with Django
I'm building a social network where user are supposed to be able to follow each other. So I define a class user with a field: ManyToMany to stock the users that follow this user. This is what I have done in my model.py: followings = models.ManyToManyField('self', blank=True) This is my view.py: @login_required def follow_test(request): name = request.POST.get('name', '') user_followed = Dater.objects.get(username=name) current_user = Dater.objects.get(id=request.user.id) print current_user.followings # display my_app.Dater.None current_user.followings.add(user_followed) print current_user.followings # display my_app.Dater.None I retrieve correctly my users (current (The one who follow someone) and the followed one) but I can't add the followed user in the set followings of the current user. Can you see something I don't do properly in my view? -
how do i create archive month from the current year
i want to create archive months from 10 months before currentdate to current date ie dynamic so tha i dont't have to update html page again and again. i am using custom filter to update my date,generic MonthArchiveView and bootstrap blog template. this is the code snipet i wanted to implement in django template but due lot of syntax restrictions ,I was'nt able to implement it. from datetime import date d = date.today() for i in range(10): if(d.month-1==1): d=date(d.year-1,12,1) else: d=date(d.year,d.month-1,1) print(d) In index.html h4>Archives</h4 ol class="list-unstyled" {% with ''|center:10 as range %} {% for i in range %} {{d|get_date}} <li><a href="{% url 'blog:month_archive' d.year d.month %}">{{d.month }} {{d.year }}</a></li> {% endfor %}`enter code here` {% endwith %} </ol </div In Blog_Tag.py(Custom Filter) from django import template from datetime import date register = template.Library() @register.filter(name='get_date') def get_date(d): if d.month == 1: d= date(d.year - 1, 12, 1) else: d = date(d.year, d.month - 1, 1) return d In views.py def index(request): d=date.today() return render(request, 'blogger/index.html',{'d':d}) url pattern url(r'^(?P[0-9]{4})/(?P[- \w]+)/$',ArticleMonthArchiveView.as_view(),name="month_archive"), what I am getting is on my blog page Archives Dec. 1, 2016 1 2017 Dec. 1, 2016 1 2017 Dec. 1, 2016 1 2017 Dec. 1, 2016 1 2017 Dec. … -
Django / Cassandra: can not createsuperuser
I am running Debian server with Django and Cassandra. I am not able to create the admin user via command: python manage.py createsuperuser Running the command causes an error: cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 1:260 no viable alternative at input '.' (...auth_user.date_joined FROM auth_user WHERE [auth_user]....)"> The synchronization works fine - the keyspace and tables were created according to model. Version information Debian GNU/Linux 8.6 (jessie) Python 2.7.9 Django 1.10.5 Cassandra 3.0.9 Django: settings.py # Application definition INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django_cassandra_engine', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django_cassandra_engine', 'NAME': 'mydb', 'TEST_NAME': 'test_db', 'HOST': 'xx.xx.xx.xx', 'OPTIONS': { 'replication': { 'strategy_class': 'SimpleStrategy', 'replication_factor': 1 } } } } Full traceback Not checking migrations as it is not possible to access/create the django_migrations table. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute return super(Command, self).execute(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 96, in handle default_username … -
How To execute only If all the statements in try doesn't fail?
try : doSomething1() doSomething2() doSomething3() except Exception as e : doSomething4() } I know that in the above code If doSomething1() fails doSomething2() & doSomething3() won't execute and it would jump to doSomething4(). But I want something where if either on of doSomething1() or doSomething2() or doSomething2() fails the whole try doesn't gets executed and jumps to doSomething4() Actually I'm working with a database and in try I create two rows but sometimes second row fails and first one doesn't, But I don't want the 1st row to be saved when the second one fails. I want both of them to execute or fail together. How? -
How to make django post_save signal run only during creation
I'm using django-notifications in my project and I want to notify a particular user whenever a model is created using the signal, but the post_save also runs when a model is being updated how do I prevent this and only make the post_save method run when a model is created. models.py class Card(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=100) description = models.TextField(blank=True) list = models.ForeignKey(List, related_name='cards') story_points = models.IntegerField(null=True, blank=True) business_value = models.IntegerField(null=True, blank=True) def __str__(self): return "Card: {}".format(self.title) def my_handler(sender, instance, **kwargs): if instance.pk is None: notify.send(instance.user, recipient=User.objects.get(pk=1), target=instance, verb='created') post_save.connect(my_handler, sender=Card) I tried using if instance.pk is None, but when I add this condition it doesn't run at all.