Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to use file upload without forms.py - 'InMemoryUploadedFile' object is not callable
So I'm trying to make a form with some data and an upload field. Django docs doesn't provide any good tutorial of doing this without forms.py. I don't want to use that. I tried to adapt their tutorial with forms.py (https://docs.djangoproject.com/en/2.2/topics/http/file-uploads/) with my project but I'm getting an error. "InMemoryUploadedFile' object is not callable" I've tried searching it on google but I didn't find this error. I obviously miss something, because when I used to do file uploads with Node I had to do more things, like setting file storage ect. I just don't know how to handle this in django. So what am I missing and why do I get this error? views.py def incarcarecv(req): context = { 'title': "title" } if req.method == 'POST': nume = req.POST['nume'] prenume = req.POST['prenume'] telefon = req.POST['telefon'] email = req.POST['email'] CV = req.FILES['CV'] cvUpload = CV(solicitant = req.user, nume=nume, prenume=prenume, telefon=telefon, emailContact=email, CV=CV) return render(req, "../templates/pagini/incarcare-cv.html", context) models.py class CV(models.Model): solicitant = models.ForeignKey(User, on_delete=models.CASCADE) dataUploadCV = models.DateField(auto_now_add=True) nume = models.CharField(max_length=12) prenume = models.CharField(max_length=12) telefon = models.CharField(max_length=12) emailContact = models.EmailField(max_length=40) CV = models.FileField(upload_to='documents/%d/%m/%Y') rezolvata = models.BooleanField(default=False) def __str__(self): return self.solicitant html {% extends 'base.html' %} {% load static %} {% block content %} … -
Django not routing Heroku Websokect to dyno
I am trying to enable Channels V2 for a Django app deployed in Heroku. The WSGI web dyno works perfectly but the second web dyno for ASGI channels never get the requests so when trying to create a websocket connection I get a 404 response. Here is the Procfile file: web: gunicorn app_xxx.wsgi --log-file - web2: daphne app_xxx.routing:application --port $PORT --bind 0.0.0.0 -v2 I have also tried with Uvicorn like: web: gunicorn app_xxx.wsgi --log-file - web2: gunicorn app_xxx.asgi:application -b 0.0.0.0:$PORT -w 1 -k uvicorn.workers.UvicornWorker Seems like everything is in place, just need to find a way to EXPOSE the wss endpoint -
Django sessions in hazelcast and shared cache
I have a setup with two instances of one service on django, and they store theirs cache in a hazelcast cluster by memcached client. (https://imgur.com/K8CMQeX) The sessions also stored in hazelcast. In this case, if hazelcast stores all data in one map (as written in docs), all sessions should be replicated between these instances. I tested it with an admin login and it is not. If I logged in on the first instance I also should log in on another instance. Sessions are stored in hazelcast correctly, cause if hazelcast goes down, Django produces an exception about session creation failure. Whats wrong? Hazelcast: 3.12, django: 2.0.12, python-memcached: 1.59. # settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': 'hazelcast-ip:5701' } } SESSION_ENGINE = 'django.contrib.sessions.backends.cache' hazelcast.xml <network> <memcache-protocol enabled="true"/> <tcp-ip enabled="true"> <interface>hazelcast-external-ip</interface> </tcp-ip> <network> The goal of this replication is to send requests from gateway to replicated instance if first instance goes down, sessions should be saved too. -
HTML Button gets executed before pressed
0 I have a html template which contains a button when u press the button it executes a function in views.py which i will list: from django.shortcuts import render from django.http import HttpResponse import requests from bs4 import BeautifulSoup def button(request): return render(request, 'home.html') def output(request): def trade_spider(max_pages): dat = '' page = 1 while(page <= max_pages): search = 'Ipad' url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=' + search + '&_sacat=0&_pgn=' + str(page) src = requests.get(url) text = src.text soup = BeautifulSoup(text, features="html.parser") for link in soup.findAll('a', {'class': 's-item__link'}): href = link.get('href') title = link.string if(title == None): title = "Sorry the title was unavailable however you can check the price." price = get_item_price(href) dat += href + '\n' + title + '\n' + price page+=1 return dat def get_item_price(item_url): src = requests.get(item_url) text = src.text soup = BeautifulSoup(text, features="html.parser") for item_price in soup.findAll('span', {'class': 'notranslate'}): price = item_price.string return price data = trade_spider(1) return render(request, 'home.html',{'data': data}) home.html: <!DOCTYPE html> <html> <head> <title> Python button script </title> </head> <body> <button>Execute Script</button> <hr> {% if data %} {{data | safe}} {% endif %} </body> </html> Everything works fine however when i run the page it diplays the button AND the output which i dont … -
Django: 'ImproperlyConfigured at' after form POST using CreateView
I want to add data to my database from form (which is CreateView). Unfortunately after posting I got 'ImproperlyConfigured at/persons/new/' I was trying to edit my urls.py, but I think I missed something. My views.py class PersonListView(ListView): model = Person template_name = 'app/home.html' context_object_name = 'users' class PersonCreateView(CreateView): model = Person fields = ['name','surname'] My urls.py in project *imports* urlpatterns = [ path('admin/',admin.site.urls), path('persons/', include('app.urls')), ] My urls.py in app *imports* urlpatterns = [ path('',PersonListView.as_view(),name='persons), path('new/',PersonCreateView.as_view(),name='person-create), ] After submit my form, data are added to database but I got error like above. -
NameError at /gmailAuthenticate/ NameError: name 'xsrfutil' is not defined
I want the visitor of this website to get authenticated via Gmail API. Getting the following error on the line 24 in views.py (at the line FLOW.params['state']): NameError at /gmailAuthenticate/ name 'xsrfutil' is not defined Views.py file: from django.shortcuts import render from .models import CredentialsModel import httplib2 import requests from oauth2client.client import flow_from_clientsecrets from gfglogin import settings from django.http import HttpResponseRedirect from oauth2client.contrib.django_util.storage import DjangoORMStorage from oauth2client.contrib.django_util.models import CredentialsField # Create your views here. FLOW = flow_from_clientsecrets( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, scope='https://www.googleapis.com/auth/gmail.readonly', redirect_uri='http://127.0.0.1:8000/oauth2callback', prompt='consent') def gmail_authenticate(request): storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build('gmail', 'v1', http = http) print('access_token = ', credential.access_token) status = True return render(request, 'index.html', {'status': status}) Urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^gmailAuthenticate/', views.gmail_authenticate, name ='gmail_authenticate'), url(r'^oauth2callback/', views.auth_return), url(r'^$', views.home, name ='home'), ] -
Django Admin- Dynamic child ModelChoiceField queryset on parent ModelChoiceField
this question have been asked many times. i went through many of them. still couldn't find what i am looking for. I am trying to load child ModelChoiceField data on parent ModelChoiceField selection in Django-Admin only My code is as follows: class AddressForm(forms.ModelForm): name = forms.CharField(max_length=150) city = forms.ModelChoiceField(queryset=City.objects.all(), required=False) class Meta: model = Address fields = ['name', 'country', 'city'] def __init__(self, *args, **kwargs): if 'instance' in kwargs: address = kwargs['instance'] self.base_fields['name'].initial = address.name country = self.get_country(*args, **kwargs) self.base_fields['city'].queryset = country.cities if country else City.objects.none() super().__init__(*args, **kwargs) but it's not working on onChange event. any help would be appreciated. -
Django: AttributeError: 'str' object has no attribute 'username'
I am new to django and making a project. i have a Attribute error and i am not using the default django model. Here is my views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout as dlogout from .models import User from .forms import * def ajaxsignup(request): ajax = AjaxSignUp(request.POST) context = {'ajax_output': ajax.output() } return render(request, 'ajax.html', context) def ajaxlogin(request): ajax = AjaxLogin(request.POST) logged_in_user, output = ajax.validate() if logged_in_user != None: login(request, logged_in_user) context = {'ajax_output': output} return render(request, 'ajax.html', context) def signup(request): context = {} return render(request, 'sign-up.html', context) def ajaxsavephoto(request): ajax= AjaxSavePhoto(request.POST, request.user) context = {'ajax_output': ajax.output()} return render (request, 'ajax.html', context) def ajaxphotofeed(request): ajax= AjaxPhotoFeed(request.GET, request.user) context = {'ajax_output': ajax.output()} return render (request, 'ajax.html', context) def ajaxprofilefeed(request): ajax= AjaxPhotoFeed(request.GET, request.user) context = {'ajax_output': ajax.output()} return render (request, 'ajax.html', context) def profile(request,username): if User.objects.filter(username=username).exists(): u = User.objects.filter(username=username) if u.profilepic=="": u.profilepic = "static/assets/img/default.png" context= {"ProfilePic": u.profilepic, "whosprofile": username, "logged_in_as": request.user.username} if request.user.is_authenticated: return render(request,'logged-in-profile.html', context) return render(request, 'profile.html', context) else: return redirect(index) def index(request): context = {} if request.user.is_authenticated: u= User.objects.filter(username=request.user.username) # if u.profilepic=="": # u.profilepic = "static/assets/img/default.png" # context = {'user': request.user, 'profilepic': u.profilepic} # return render (request, 'login.html', context) return render(request, 'logged-in-index.html', context) … -
How can I use Cytoscape (javascript library) within Django?
I have a front-end developed that utilizes a javascript library called Cytoscape (graph networking), and I'm trying to develop the backend using SQLite and Django (planning to store the JSON files of the Cytoscape maps). The problem I'm running into, however, is that when I add the template HTML files (with their CSS and Javascript components), only the HTML is read and Cytoscape isn't used at all. I figure this is due to incompatibility with Python and Cytoscape. Is there any easy fix to this? -
Every request being sent by Firefox triggers ConnectionResetError
For some reason Firefox, and only Firefox is causing this problem. Django server is still functional and I'm able to navigate, but stack trace keeps appearing on terminal. Steps to reproduce problem: Start django app (python3 manage.py runserver), Open client/browser(firefox) and go to localhost:8000, Start making requests / clicking URLs / anything that sends a request to Django Terminal stack trace: Exception happened during processing of request from ('127.0.0.1', 55364) Exception happened during processing of request from ('127.0.0.1', 55366) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/Users/orion/Desktop/Claymore/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/Users/orion/Desktop/Claymore/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer ---------------------------------------- Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/Users/orion/Desktop/Claymore/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/Users/orion/Desktop/Claymore/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer … -
How to solve problem with resizing image?
I have image page - / image_hash /? query_params The page contains an image. If there are no GET parameters, then it comes from the unchanged backend. Three GET parameters may be present: width - field for changing the image width width - width height - height size - maximum size in bytes They can be present both individually and together. If a parameter is available, it is necessary to produce or degrade the image quality. Do not change the original image. Use caching to not generate a new image when re-requesting. I understand the first two points how to do, but the last one cannot be processed without changing the image. I would be very grateful for the help -
Django error with module while running tests
When i run python manage.py tests i get an error saying that some test module is not found. I am using PyCharm, Django 2.1.4 and W10 on Ubuntu. The error: ====================================================================== ERROR: projectname.projectname (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: projectname.projectname Traceback (most recent call last): File "/usr/lib/python3.6/unittest/loader.py", line 462, in _find_test_path package = self._get_module_from_name(name) File "/usr/lib/python3.6/unittest/loader.py", line 369, in _get_module_from_name __import__(name) ModuleNotFoundError: No module named 'projectname.projectname' What I've tried python manage.py runserver and it runs just fine. Add projectname to INSTALLED_APPS Create and app called tests My project structure Django │ ├── requirements.txt │ └── projectname │ ├── __init__.py │ ├── manage.py │ └── projectname │ ├── apps │ │ ├── accounts │ │ │ ├── admin.py │ │ │ ├── apps.py │ │ │ ├── __init__.py │ │ │ ├── migrations │ │ │ │ ├── __init__.py │ │ │ ├── models │ │ │ │ ├── __init__.py │ │ │ │ ├── profiles.py │ │ │ │ └── users.py │ │ │ ├── serializers │ │ │ │ └── __init__.py │ │ │ ├── tests.py │ │ │ ├── urls.py │ │ │ └── views │ │ │ └── __init__.py │ │ ├── __init__.py │ ├── … -
How to generate word document from html in Django?
Now I use easy_pdf for create pdf documents from html templates. Are there any library for make doc/docx files in the same way? -
AttributeError at /admin/ 'WSGIRequest' object has no attribute 'user'
This is the error is get and i am not able to get the admin login screen. AttributeError at /admin/ 'WSGIRequest' object has no attribute 'user' Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 2.1.2 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'user' Exception Location: C:\Users\Neptune\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\sites.py in has_permission, line 186 Python Executable: C:\Users\Neptune\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.3 Python Path: ['C:\Users\Neptune\Desktop\MyMusic', 'C:\Users\Neptune\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\Neptune\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\Neptune\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\Neptune\AppData\Local\Programs\Python\Python37-32', 'C:\Users\Neptune\AppData\Local\Programs\Python\Python37-32\lib\site-packages', 'C:\Users\Neptune\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.9.1-py3.7.egg'] Server time: Tue, 4 Jun 2019 17:37:30 +0000 -
How to disable view if not form submitted with Django generic FormView
Lets say that I have a generic class based FormView and after form submit I want the user to get to a new view. But that view should only be able to be displayed after form submit and not when the user tries to type in for example: /order-success This is some example view that I have: class Order(FormView): template_name = 'order.html' form_class = OrderForm success_url = # something here to do? def form_valid(self, form): self.obj.save() return super().form_valid(self.obj) So, what do I need here. Do I need to do this by with some middleware? Or is there some token thing I need to do. Or add something to the session storage to read from? What could be a good approach to this? -
django notification, if not user is the owner of post equals user is the one who comment
I'm using django notification hq, https://github.com/django-notifications/django-notifications. currently the user gets a notification to his post when there's a comment. but he also gets a notification when he writes the comment to his post. I don't want the owner of the post to get a notification if the comment is made by the owner. here's my try class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def save(self, *args, **kwargs): if not self.author == self.post.author: notify.send(self.author, recipient=self.post.author, action_object=self.post, target=self, verb="commented on") super(Comment, self).save(*args, **kwargs) my second problem is when the user sees the notification it still appears, it should be turned into 0 notification from 1 notification if user sees it. I read the documentation here https://github.com/django-notifications/django-notifications but still no idea.. -
How do you install Django 2x on pip when python 2x is your default version of python but you use python 3x on Bash
I need to install Django 2.2.2 on my MacBook pro (latest generation), and I am a user of python 3x. However, my default version of python is python 2x and I cannot pip install Django version 2x when I am using python 2x. Could anyone explain how to change the default version of python on MacBook I have looked at many other questions on this site and none have worked. All help is appreciated thank you :) -
Remove duplicates across django query sets
I have the following django queries: AUSTF = TSF.objects.filter(FKToTld__FKToUser=request.user).values('FKToTld__dNm').distinct() AUSTU = TSU.objects.filter(FKToTld__FKToUser=request.user).values('FKToTld__dNm').distinct() AUSTJS = JSP.objects.filter(FKToTld__FKToUser=request.user).values('FKToTld__dNm').distinct() This produces output that has the same values returned like: 123.456.789 website.com 123.456.789 website.com I want to take all three objects, and remove any duplicates before outputting in my template. The distinct() method does this for single object, but not for all objects. I thought appending these three objects to a tuple might work, but that hasnt worked out. Can someone help? Thanks -
Getting values of dropdown django. (Also how to work with ranges when filtering)
I'm having problems trying to filter ranges and working with dropdowns.I will really appreciate any help with the two. Its dealing with age range. Models.py : class Part_Time_DM(models.Model): Name=models.CharField(max_length=30, unique=True, default="name") Date_of_birth=models.DateField(default=date.today) Age=models.IntegerField() Views.py: def home(request): qs = Part_Time_DM.objects.all() location_query= request.GET.get('location') age_query= request.GET.get('age') if location_query != "" and location_query != None: qs = qs.filter(Location__icontains=location_query ) return render(request, 'home.html', {"qs": qs}) Template: <form class="form-wrap" method="GET" action="."> <select name="age" class="form-control"> <option value="18 - 21">18 - 21</option> <option value="22 - 25">22 - 25</option> <option value="26 - 30">26 - 30</option> <option value="31 - 35">31 - 35</option> <option value="36 and above">36 and above</option> </select> <br> <button type="submit" class="btn btn-primary">Search</button> </form> -
Django throws ValueError: save() prohibited to prevent data loss due to unsaved related object save method
I am trying to create some objects of model ABC in from save method of XYZ model, when a XYZ models object is created. See the below code for reference : Class XYZ(models.Model): name = models.CharField(max_length=150) #Other Feilds def save(self, *args, **kwargs): self.match_tick = self.match_date.timestamp() contest_obj_1 = ContestDetail( contest_of_ABC=self, contest_name="₹1000 Winnnings", filled_status = False, ) contest_obj_1.save() super(MatchDetail, self).save(*args, **kwargs) Class ABC(models.Model): contest_of_ABC = models.ForeignKey(XYZ) contest_name = models.CharField(max_length=100) filled_status = models.BooleanField(default=False) And here are the error lines : File "./center/models.py", line 47, in save contest_obj_1.save() File "./center/models.py", line 203, in save super(ContestDetail, self).save(*args, **kwargs) File "/home/FightBack/.virtualenvs/ENV/lib/python3.5/site-packages/django/db/models/base.py", line 762, in save "unsaved related object '%s'." % field.name ValueError: save() prohibited to prevent data loss due to unsaved related object 'contest_of_ABC'. -
How to send POST subheaders in json in python (django) to server
Im trying to send info this to server about several days and get confused... had tried to solve problem with urllib3 but got an error. without "json.dumps" i got an django error. without "items" cant get response. def create_quote(request, order_id='2845', currency='EUR', total_amount='1'): text = order_id + str(total_amount) + currency post_data = { 'api_hash': API_HASH, 'hash': hashlib.sha256(text.encode('utf-8')).hexdigest(), 'order_id': order_id, 'currency': currency, 'amount': total_amount, 'items': json.dumps({ 'sku': '450', 'name': 'Test Item', 'amount': '1', 'type': 'item_type', 'qty': '10', 'price': '15', 'id': '5619', 'url': 'http://example.com/products/item/example-item-name-5619' }), 'customer_ip_address': '***', 'url_failure': '', 'url_ok': '', } http = urllib3.PoolManager() url = 'http://checkout.test.pay.g2a.com/index/createQuote' response = http.request('POST', url, post_data) return HttpResponse(response.data) How can i rightly sent json data with django/python? -
Testing a Django Form with a CSV upload
I have a form that the user upload's a CSV into for data processing. I'm currently trying to test the form.is_valid() method. However I am following the Django documentation, and the form is still returning an error that the field requires a value. Any ideas? The Documentation The documentation show the following example - >>> c = Client() >>> with open('wishlist.doc') as fp: ... c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp}) The Test class TestImportCSVForm(TestCase): def test_form_valid(self): with open('fake.csv', 'r', newline='') as csvfile: form_data = { 'csv_file': csvfile, } form = ImportCSVForm(data=form_data) self.assertTrue(form.is_valid()) The Form class ImportCSVForm(forms.Form): """ Form for uploading CSVs """ csv_file = forms.FileField( label=_("CSV File"), help_text=_("Upload a CSV")) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( 'csv_file', HTML("""<hr>"""), ButtonHolder( Submit('submit', 'Submit', css_class='btn btn-primary') ) ) The error when I run the test (Pdb) form.errors {'csv_file': ['This field is required.']} -
The current path, photos/, didn't match any of these
I'm trying to get an app running in django but I encounter this error: The current path, photos/, didn't match any of these, even though I could not figure which part of the code is problematic. Here is my code: views.py: from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("<h>This is the main page</h>") urls.py: from django.contrib import admin from django.urls import path from photoapp import views urlpatterns = [ path('', views.index, name='index'), ] main urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('photos/', include('photoapp.urls')), ] -
Period base class of django-schedulers is not giving deleted events and it's occurrences for a period
I want to get the occurrences of the deleted event I have used django-scheduler to create event and occurrences I have used events=Event.objects.filter(deleted=true) It gives the queryset of deleted events then I use period class to get the events b/w start and end parameters invited_events=period(events, start=from_date,end=to_date) It gives me empty period class Then I use Invited_events.get_occurrence() So I want to ask can we use period class to get deleted events ,and then get all persisted and non-persisted occurrences from it -
simple comment code won't collaborate with notification app
my code for comment works fine but as soon as I add notification feature it doesn't work, while notification kinda works. I'm using django-notification-hq 3rd party app. from here: https://github.com/django-notifications/django-notifications here's my code class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) message = models.TextField() ordered = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-id'] def get_edit_url(self): return reverse('comment_edit', args=[self.post.pk, self.pk]) def get_delete_url(self): return reverse('comment_delete', args=[self.post.pk, self.pk]) def save(self, *args, **kwargs): notify.send(self.author, recipient=self.post.author, action_object=self.post, target=self, verb="commented on") views.py @login_required def comment_new(request, post_pk): post = get_object_or_404(Post, pk=post_pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = request.user comment.save() return redirect(comment.post) else: form = CommentForm() return render(request, 'community/comment_form.html', { 'form':form, }) urls.py path('post/<int:post_pk>/comment/new',views.comment_new, name='comment_new'), I added this single line, def save(self, *args, **kwargs): notify.send(self.author, recipient=self.post.author, action_object=self.post, target=self, verb="commented on")