Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using the URLconf defined in questionbook.urls, Django tried these URL patterns, in this order
I am trying to upload file from django admin interface and make it downloadable for user so that user can download it onclick But every time i click on download button it says something like this I am using pdf file here. Using the URLconf defined in questionbook.urls, Django tried these URL patterns, in this order: admin/ posts/ [name='list'] ^static/(?P<path>.*)$ ^media/(?P<path>.*)$ The current path, posts/Ths is a post/Aditya-Kumar_1.pdf, didn't match any of these. I dont know what is the problem here so far i have done this. models.py class Post(models.Model): title = models.CharField(max_length= 120) slug = AutoSlugField(populate_from='title') document = models.FileField( upload_to=upload_location, null=True, blank=True, validators= [validate_file_extension] ) category = models.ForeignKey(Category, on_delete=models.CASCADE) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), #'var/www/static/', ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn") -
Edit fields before create using ModelSerializer
I have a pallet that have contents inside. I need to assign a specific number to the pallet, based to a foreign key value (But that is not in the code yet). With postman, when I POST with some json body; If I give some number field, then get an error that number cannot be duplicated. If I don't send number(because I'm giving it on customized create method), I get an error that number is a required field. If I remove number from PalletSerializer, it saves, but when I need to get it, there is no number to see. Which is the correct way to achieve adding data before create? Here are the serializers: class ContentSerializer(serializers.ModelSerializer): class Meta: model = models.Content fields = ('id', 'quantity', 'kilograms', 'container') class PalletSerializer(serializers.ModelSerializer): contents = ContentSerializer(many=True) class Meta: model = models.Pallet fields = ('id', 'number', 'receipt_waybill', 'client', 'contents',) def create(self, validated_data): contents_data = validated_data.pop('contents') number = 123456 pallet = models.Pallet.objects.create(number=number, **validated_data) for content_data in contents_data: specifications_data = content_data.pop('specifications') instance = models.Content.objects.create(pallet=pallet, **content_data) instance.specifications.set(specifications_data) return pallet -
Google OAuth authentication with Django getting AuthException from localhost
I was trying to test Google authentication from Django with social-auth-app-django library with Authorized domain in /etc/hosts file. All other authentications works fine like Facebook, Github, Twitter etc. One thing about logout; logging out from application will not log out from actual backend, can we log out from backend with Django? Created a project and obtained credentials from Google API console and put it in settings.py as SOCIAL_AUTH_GOOGLE_OAUTH2_KEY and SECRET. With Javascript, getting redirect_uri mismatch, Request Details redirect_uri=storagerelay://http/www.simplysmile.in?id=auth725330 response_type=permission id_token scope=email profile openid openid.realm= client_id=101069722014-u09qsn0dtnj8km7kid0883si0up9015p.apps.googleusercontent.com ss_domain=http://www.simplysmile.in fetch_basic_profile=true gsiwebsdk=2 with the link <a href="{% url 'social:begin' 'google' %}">Login with Google</a> getting AuthException. Please help to find a solution or share a tutorial to get Google authentication work with Django. -
Check if a view function was called
I'd like to test if my JS timer runs my timeout view: def testTimeLimit(self): self.client.get('/') response = self.client.get('/new',follow = True) sleep(2) #Assertion that checks if timeout view was called How could I check what view functions were called in a session in chronological order? I know this test is easy to do in selenium but is it possible with a django.test.TestCase? -
Django choices from another model's choices that are already selected
So I have one model that has a ManytoMany field which selects choices from a model. I want another model that has a ManytoMany field who's choices are only the selected choices of the first model. How would I go about making this model? -
checkbox returns empty list django templates
I'm fairly new to django.What I am trying to do is values from selected checkboxes from my django template. But it gives an empty list in views.py. I have searched for solutions but so far I have been unsuccessfull. my template: {% for x in project_list %} <tr > <td > <label> <input type="checkbox" name="checks[]" value="{{x.id}}"/> <span><a href= '{% url "projects:ProjectDetail" Pid=x.id %}' >{{x.project_name}}</a><br></span> </label> </td> </tr> {%endfor%} <a class="waves-effect waves-light btn-small" id="nxtBtn" href="{% url 'projects:ProjectDelete' %}">Delete selected projects</a> views.py def Delete_project(request,*args, **kwargs): some_var = request.POST.getlist('checks[]') print("printing project Id's") print(some_var) what I want to do is when I click on Delete selected projects I should get list of seleted checkbox values.But I'm getting an empty list when I print list in views. Thanks in advance! -
use sessions out of the views django
I made a Custom template tag using this doc like this in my Django application : myproject/ __init__.py models.py templatetags/ __init__.py myCustomTags.py views.py in the myCustomTags.py, I need to use some variables that there are in views.py so I save those variables in session , and tried to get them in myCustomTags.py, but noting worked and it does not recognized my sessions. I used this doc ,but it seems that this method wants me to use session_keys. in this method my question is that how to use the sessions without the key or somehow pass the keys from views.py to myCustomTags.py too . here is my code in this method: views.py: from importlib import import_module from django.conf import settings SessionStore = import_module(settings.SESSION_ENGINE).SessionStore from django.contrib.sessions.backends.db import SessionStore my_session = SessionStore() def user_login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') # some process to validate and etc... my_session['test_session'] = 'this_is_my_test' my_session.create() return redirect(reverse('basic_app:index')) myCustomTags.py from django import template from importlib import import_module from django.conf import settings SessionStore = import_module(settings.SESSION_ENGINE).SessionStore from django.contrib.sessions.backends.db import SessionStore my_session = SessionStore() register = template.Library() @register.simple_tag def userStatusMode(): status = my_session['test_session'] return status base.html: {% load dynamic_vars %} {% userStatusMode as user_status_thing %} <!-- and … -
Django : pre selection or tags. model relations
Django Version is 2.1.7 Hello, i have a OneToMany Relation and i ask my self if there is a possibility to make some kind of pre-selection (Tags or so?) for my Farmers? Because not every Farmer has or wants Chickens or he is specialist in Cows only. Means, right now, whenever i want to assign an individual Animal to a Farmer, i see all Farmers displayed in my Django Admin. With a growing Number of Farmers it gets confusing. So i thought to insert some Kind of Model Field in my Farmers Model... like chickens = true or not true and cows = true or not true or to introduce a new model for every species. My Goal is, to assign a set of species to a every farmer. So that the Next time i want to add a chicken django shows only Farmers that will work with Chickens on their Farmland, it makes no sense to Display all Farmers, when some Farmers know that they handel only a specific set of species. As a Newbie i would guess i have to make some new models for every Species with a ManyToMany Relation? So Farmers >< Species X, Y, Z … -
Override related manager in inherited model
Strange problem when working with Django models and related fields/managers, hopefully someone has run into this problem before. I have the following model structure defined: class CustomManager(models.Manager): use_for_related_fields = True def __init__(self, *args, **kwargs): self._param = kwargs.pop("param", True) super().__init__(*args, **kwargs) class MyModel(models.Model): id = models.AutoField(primary_key=True) class BaseRelatedModel(models.Model): id = models.AutoField(primary_key=True) objects = CustomManager() class SubRelatedModel(BaseRelatedModel): related = models.ForeignKey(MyModel, related_name="related_objs", on_delete=models.CASCADE) objects = CustomManager(param=False) As you can see, I have a BaseRelatedModel which sets its manager to be an instance of CustomManager, which sets the default _param value to True. I then subclass this model in SubRelatedModel and attempt to override the objects manager with a new instance of a CustomManager, this time setting its param value to False. The manager override does not seem to work when I attempt to access all related SubRelatedModel objects from a given MyModel instance. In [1]: m = MyModel.objects.create() In [2]: m.related_objs._param Out[2]: True I would expect the m.related_objs._param to return False, since that is the parameter of the objects manager on the SubRelatedModel. Any ideas why this isn't taking effect, or another approach I could use for this problem? Thanks! -
django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_confirm'
My urls.py file code : from django.urls import path from django.conf.urls import url from . import views from django.contrib.auth.views import PasswordResetView,PasswordResetDoneView,PasswordResetConfirmView app_name = 'user' urlpatterns = [ url('^login/$',views.user_login,name="user_login"), url('^logout/$',views.user_logout,name="user_logout"), url('^password-reset/$',PasswordResetView.as_view(template_name='user/password_reset.html'),name="password_reset"), url('^password-reset/done/$',PasswordResetDoneView.as_view(template_name='user/password_reset_done.html'),name="password_reset_done"), url('^password-reset-confirm/<uidb64>/<token>/$',PasswordResetConfirmView.as_view(template_name='user/password_reset_confirm.html'),name="password_reset_confirm"), url('^home/$',views.register,name="register"), url('^manage_address/$',views.manage_address,name="manage_address"), url('^delete_address/(?P<address_id>[0-9]+)/$',views.delete_address,name="delete_address"), url('^contact_support/$',views.contact_support,name="contact_support"), ] Error Traceback : raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. [25/Feb/2019 23:10:30] "POST /password-reset/ HTTP/1.1" 500 183309 -
Django Crispy forms input out of order
I am building some forms using django-crispy_forms, I need them to be in the some specific order (specifically the order I stablished on the fields inside forms.py). class RegistroRelatorio(forms.ModelForm): class Meta: model = RelatorioVendas fields = {"razao_social","codigo_interno","nome_fantasia","endereco","bairro","uf","telefones","cnpj","fundacao", "negocios","cidades_negocios","c1_nome","c1_whats","c1_email","c1_cargo","c1_comunicacao","c1_preferencia"} I tried to use label_order inside this class, it worked, but when I use the crispy form it stops working... I even tried to use the Layout method from the crispy library. -
django left join + group by count(*), includes zero counts
class ItemGroup(models.Model): name = models.CharField(max_length=50) class Item(models.Model): name = models.CharField(max_length=50) group = models.ForeignKey(ItemGroup, on_delete=models.CASCADE) I want to display all the item groups, and for each group show the number of items the group has, and include groups which has no items. In SQL I use left join for this purpose: SELECT item_group.name, COUNT(*) FROM item_group LEFT JOIN item ON item_group.id = item.id GROUP BY item_group.id, item_group.name So I get groups with zeros counts as well. How to do the equivalent query with django ORM? -
Structure a python project 3 tiers
In a project python, 1- i created three packages: presntation_layer, data_layer, application_layer. 2- For my unit tests, for each class inside each package i created a file of test. I just want to know if both are a good way to structure project python. -
How to correct blank Hosted Fields error in django
I am using Django to build an e-commerce app and I would like to integrate a payment gateway using Braintree. However, after integrating it using Hosted Fields, my credit card is displayed in a way that we cannot even write the card number neither the CVV code nor the expiration date. I attached a screenshot about the paymBraintree card process. Please assist Thanks process.html {% extends "base.html" %} {% block title %}Pay by credit card{% endblock %} {% block content %} <h1>Pay by credit card</h1> <form action="." id="payment" method="post"> <label for="card-number">Card Number</label> <div id="card-number" class="field"></div> <label for="cvv">CVV</label> <div id="cvv" class="field"></div> <label for="expiration-date">Expiration Date</label> <div id="expiration-date" class="field"></div> <input type="hidden" id="nonce" name="payment_method_nonce" value=""> {% csrf_token %} <input type="submit" value="Pay"> </form> <!-- Load the required client component. --> <script src="https://js.braintreegateway.com/web/3.29.0/js/client.min.js"> </script> <!-- Load Hosted Fields component. --> <script src="https://js.braintreegateway.com/web/3.29.0/js/hostedfields.min.js"></script> <script> var form = document.querySelector('#payment'); var submit = document.querySelector('input[type="submit"]'); braintree.client.create({ authorization: '{{ client_token }}' }, function (clientErr, clientInstance) { if (clientErr) { console.error(clientErr); return; } braintree.hostedFields.create({ client: clientInstance, styles: { 'input': {'font-size': '13px'}, 'input.invalid': {'color': 'red'}, 'input.valid': {'color': 'green'} }, fields: { number: {selector: '#card-number'}, cvv: {selector: '#cvv'}, expirationDate: {selector: '#expiration-date'} } }, function (hostedFieldsErr, hostedFieldsInstance) { if (hostedFieldsErr) { console.error(hostedFieldsErr); return; } submit.removeAttribute('disabled'); … -
How can I make a pdf file downloadable in django
I want to make a post which includes pdf file and that post is rendered on website. where file should has a download button to get dowload. so far i have done this. Here i can upload file from admin interface but i am not sure how to make it available to user for download. How can make it downloadable do i need to do something with urls too if yes then what should i do with them. I am new to django i have no idea about it. models.py class Post(models.Model): title = models.CharField(max_length= 120) slug = AutoSlugField(populate_from='title') document = models.FileField( upload_to = upload_location, null=True, blank=True, validators= [validate_file_extension] ) category = models.ForeignKey(Category, on_delete=models.CASCADE) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) views.py def posts_list(request): query_list = Post.objects.all() context = { "title" : "PostList", "query_list": query_list } return render(request, "base.html", context) def category_list(request): pass def posts_detail(request): pass templates/base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h1>{{title}}</h1> {% for post in query_list %} <p>{{post.title}}</p> <p>{{post.content}}</p> <p>{{post.category}}</p> <a href="{{post.document}}">Download</a> {% endfor %} <!--category list--> </body> </html> -
Duplicate Content Type in Django after copying Postgres Directory
Situation I have a django app (using postgres as the database) running in production. I am trying to measure/improve performance, and I'd like to do that by copying data from the production instance (which has by far the best data, in terms of quantity and quality) onto my local machine, and run the server locally. I copy the Postgres folder out of which the DB is running on the production machine to my local machine (using scp), and start up the DB from that now local folder, and my local django server. Functionally, I can interact with the app completely normally, without issue. However, as soon as I make a change to my models, generate a migration, and try to migrate (again, to this local version) I get errors: django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_content_type_app_label_model_<HASH>_uniq" DETAIL: Key (app_label, model)=(<APP_NAME>, <CONTENT_TYPE>) already exists. <APP_NAME> and <CONTENT_TYPE> are the specific names of the app and content type for my app. The content_type is a type that has existed in the database for a long while and not affected in my model change/migration. When I say the app "generally works fine" in the previous paragraph, part of what I mean is … -
django model foreign key AttributeError
In my Django project, I have two apps : "music" and "user". I am trying to create a table in my app "music" as a joint table between the table "MusicPiece" and the table "Member" from the other app "user". I followed what I read in other post but I got an AttributeError when I make my migrations : AttributeError: module 'user.models' has no attribute 'Member' Here are my two models.py file : -in "music" : from django.db import models from django.utils import timezone from user import models as user_models class MusicPiece(models.Model): name = models.CharField(max_length=20) class MusicPieceAuthorship(models.Model): user = models.ForeignKey(user_models.Member, on_delete=models.CASCADE) music_piece = models.ForeignKey(MusicPiece, on_delete=models.CASCADE) -in "user" : from django.db import models from django.utils import timezone from django.contrib.auth.models import User from music import models as music_models class Member(models.Model): user = models.OneToOneField(User) birth_date = models.DateField(null=True) avatar = models.ImageField() The weirdest thing is that when I import music.models.MusiquePiece in user.models.py it works perfectly. And when I import user.models.xxxx it doesn't work in any apps. Do you know where does the problem come from? -
nginx error: worker_connections are not enough daphne Django channels supervisor
I have a Django 2.1 application using Django Channels v2 running on daphne, nginx and supervisor. I have scoured through all SO forums and tried all of the correct answers (such as changing localhost to 127.0.0.1, changing proxy_pass value to myapp.com but have been unable to resolve this error. sudo less /var/log/nginx/error.log shows 2019/02/25 16:31:08 [alert] 7154#7154: *13731 768 worker_connections are not enough while connecting to upstream, client: 127.0.0.1:8000, server: myapp.com, request: "GET / HTTP/1.1", upstream: "http:/127.0.0.1:8000/", host: "www.myapp.com" I've tried increasing the worker_connections but I get a connection refused too many loop. My server block located at /etc/nginx/sites-available/myapp upstream channels-backend { server 127.0.0.1:8000; } server { listen 127.0.0.1:8000; server_name myapp.com www.myapp.com; location = /favicon.ico { access_log off; log_not_found off; } location / { try_files $uri @proxy_to_app; } location /static/ { root /home/user/myapp/src/myapp; } location /media/ { root /home/user/myapp/src/myapp; include /etc/nginx/mime.types; } location @proxy_to_app { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } my supervisor configuration file [fcgi-program:asgi] # TCP socket used by Nginx backend upstream socket=tcp://127.0.0.1:8000 # Directory where your site's project files are located directory=/home/user/myapp/src/myapp # Each process needs to have … -
Django app unable to start with cloud foundry push
I am used to push spring apps to cloud foundry. This is for the first time I am pushing django app. After uploading is complete, it shows Waiting for app to start... Start unsuccessful My app project structure is below .gitignore Procfile README.md app: __init__.py settings.py urls.py wsgi.py assets: __init__.py admin.py apps.py data_generator.py models.py tests.py urls.py views.py migrations: __init__.py tokentype: __init__.py admin.py apps.py models.py tests.py urls.py views.py migrations: __init__.py db.sqlite3 log_storage.log manage.py manifest.yml repo/assetmanagement-3.9-py3-none-any.whl repo/mindsphere_core-0.1.0-py3-none-any.whl requirements.txt runtime.txt sdk_util.py My runtime.txt contains python-3.5.x. My Procfile contains web: python manage.py migrate && python manage.py runserver. My requirements.txt has all necessary requirements including django and djangorestframework. And manifest.yaml has below content: applications: - name: pythondemoapp instances: 1 randon-route : true path: . memory: 1GB env: HOST_ENVIRONMENT: eu1-int When I run cf logs pythondemoapp --recent after the app fails to start, i get the below log, where it complains abt couple of issues: ModuleNotFoundError: No module named 'django' (but I have this in my requirements.txt) Failed to make TCP connection to port 8080: connection refused. (I am not able to understand why its Starting development server at http://127.0.0.1:8000/ i.e at localhost) AttributeError: module 'pip._internal' has no attribute 'utils' Please review the logs from this … -
my django url is giving prefernce to <something> first than the admin/and login/ etc url
my app urls.py is: from django.urls import path from . import views from django.conf.urls import (handler400, handler403, handler404, handler500) app_name = "bca" handler404 = 'my_app.views.handler404' urlpatterns = [ path("", views.index, name='index'), path("login/", views.login_request, name='login'), path("register/", views.register, name='register'), path("logout/", views.logout_request, name='logout'), path("<match>", views.match, name='match'),#this is being preferred first... ] when ever i try admin/ in url it gives a value error Value error: what should i do . I can upload more code if you want just help me. -
How to interpolate dates and values, from database, through Django Models?
I'm new in Django and I have a database with 4 tables containing values from sensors and the datetime that the measures were taken. The problem is: the sensors have a deadband and the measures are wrote just when this deadband value are overcame, so the 4 tables don't have the measures synchronized by datetime. One of my applications needs the synchronization of these measures and I want organize by date and interpolate the datas putting the previous value when the deadband are not excited, instead of a JOIN setting NULL. For example: Sensor 1: Datetime | Value1 28/02/2018 00:00:00 0 28/02/2018 00:00:30 10 28/02/2018 10:00:00 10.3 28/02/2018 10:10:00 10.6 28/02/2018 10:11:00 12 Sensor 2: Datetime | Value2 28/02/2018 00:00:00 0 28/02/2018 00:00:40 13 28/02/2018 10:00:00 9.3 28/02/2018 10:11:01 32 28/02/2018 10:11:37 11.6 Expected result: Datetime | Value1 | Value2 28/02/2018 00:00:00 0 0 28/02/2018 00:00:30 10 0 28/02/2018 00:00:40 10 13 28/02/2018 10:00:00 10.3 9.3 28/02/2018 10:10:00 10.6 9.3 28/02/2018 10:11:00 12 9.3 28/02/2018 10:11:01 12 11.6 28/02/2018 10:11:37 12 32 The databases used will be SQLite (development) and PostgreSQL (deployment). I've thought to pass a JOIN to a python object, so the values of the interpolation will be … -
django backend and angular frontend send request to backend
hello I have finished learn angular 7 basics now have combined django from the back and angular for the from I am in the start of this project now I am using rest_framework for django and I want angular to send a GET request to the backend as we know django uses 127.0.0.1:8000 and angular 127.0.0.1:4200 and when I do this function export class HomeComponent implements OnInit { users: Object; recvedData: boolean = false; hasError: boolean = false; constructor(private http: HttpClient) { } ngOnInit() { this.http.get('/api/qutes').subscribe(data => { this.users = data; console.log(data); }, error => { this.recvedData = true; this.hasError = true; console.log(error); }) } } I am trying to get data from /api/quets from the backend server but it requesting the data from the frontend server (127.0.0.1:4200/api/quets) and this URL does not exists I know I can add a service with variable domain = "127.0.0.1:8000" and to this.http.get(this.service.domain +"/api/quets") my question: there is a better way to do that? so it send all of the request to the backend server automatically? -
Unable to load django webpage
https://docs.djangoproject.com/en/2.1/intro/tutorial01/ Just trying to run the server and test connection. I've gotten this to work many times in the past and I'm not sure why I'm having trouble now. -
Middlware triggering error twice in django
I've got some middleware I created for an app that checks a few criteria against a logged in user. If it fails any of those, it kicks off errors letting the user know. The problem is that the error is showing up twice at the top of the page. The middleware looks like this: class RegistrationMiddleware(object): def __init__(self, get_response): self.get_response = get_response print("In init of middleware") def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. print("Pre-view middle") response = self.get_response(request) # Code to be executed for each request/response after # the view is called. print("Post-view middle") ...logic stuff.... if invalid_entries: for problem_reg in invalid_entries: messages.error( request, format_html( """ Please either remove or change this registration. """ ) ) print('end of view reutrning response') return response The error shows up twice on the page. My console shows something like this: Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. In init of middleware Pre-view middle this is a test of the get_user method Post-view middle end of view reutrning response [25/Feb/2019 09:48:46] "GET /registrations/ HTTP/1.1" 200 21860 [25/Feb/2019 09:48:46] "GET /static/styles.css HTTP/1.1" 200 7082 [25/Feb/2019 09:48:46] "GET /static/registrations/style.css HTTP/1.1" … -
Get absolute_url with Django signal
I would like to get the absolute url from my saved object. My model has a method named get_absolute_url and I would like to call this method with my django post_save signal. I receive a post_save signal when a new entry is added inside a specific table named Thread. This post_save signal executes my Celery task. My Thread model is : class Thread(models.Model): """ A thread with a title """ topic = models.ForeignKey('Topic') title = models.CharField(max_length=200) sticky = models.BooleanField(default=False) slug = models.SlugField() time_created = models.DateTimeField(default=timezone.now) time_last_activity = models.DateTimeField(default=timezone.now) def __init__(self, *args, **kwargs): """ Initialize 'time_last_activity' to 'time_created' """ super(Thread, self).__init__(*args, **kwargs) self.time_last_activity = self.time_created def __str__(self): """ Return the thread's title """ return self.title def get_absolute_url(self): """ Return the url of the instance's detail view """ url_kwargs = { 'topic_pk': self.topic.pk, 'topic_slug': self.topic.slug, 'thread_pk': self.pk, 'thread_slug': self.slug, } return reverse('simple-forums:thread-detail', kwargs=url_kwargs) In my model, I have a celery.py file : # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db.models.signals import post_save from django.dispatch import receiver from simple_forums.models import Thread from ..tasks import thread_notification @receiver(post_save, sender=Thread) def get_new_thread(sender, instance, **kwargs): """ Post_save method which start Celery task to notify forum subscribers that a new thread has been created """ …