Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django .latest() values
I'm using django for my project. I have a model(table) in which the data is filled by running a process. Each process has threesteps , so all the seven steps are seven rows in table. Below is the sample table: RunId Process ID 403 step1 1 403 step2 2 403 step3 3 404 step1 4 404 step2 5 404 step3 7 Each process has a RunId which is unique to each process. In the front-end, I have a table which shows the process which are run currently now and the current step in which the process is. To get the current step, I used the following django code: RunIds = [403,404] model.objects.filter(RunId__in = RunIds).latest() which gives the last row of each process (that is step 3 in above table). But when I wanted to see the values of the queryset, I ran the following command: model.objects.filter(RunId__in = RunIds).latest().values() Django showed an error saying values() is not an attribute of latest(), I have searched on Google , but wasn't able to find the solution. -
Add method to ModelViewset Endpoint without having to call the method name in the URL [DJANGO]
I have two separate endpoints that "accepts" and "declines" each applicant on the system respectively. Endpoint #1: ...api/v1/applicants/{ID}/accept Endpoint #2: ...api/v1/applicants/{ID}/decline Now, I'm refactoring and trying to combine the Endpoints into one, such that the following URL can be used to accept and decline an applicant, while maintaining : ...api/v1/applicants/{ID}/ The purpose of doing this is to conform the endpoints to REST methodologies. WHAT I TRIED: I tried creating a hidden method [starting with underscore - eg: _someFunction() using a PUT request method]. This didn't work. I know I could also do it through the serializers.py file but don't know how as I haven't seen an example online. Here is the accept class. The decline is similar with minor changes: @action(detail=True, methods=['put']) def accept(self, request, pk): data = request.data if request.user.user_type == "2": if Applicant.objects.filter(id=pk).exists(): applicant = Applicant.objects.get(id=pk) if applicant.status == '1': applicant.status = '2' applicant.save() # Hash the ID of the particular applicant so it can be used for verification # make this a function during refactoring hashids = Hashids(salt=HASH_SALT, min_length=16) hashid = hashids.encode(applicant.id) # send email with the link to the applicant # make this a function too SENDER="xxx@example.com" SUBJECT="Congratulations, you've been accepted!" MESSAGE = """ Hello {}, … -
Django post data from Javascript function
I'm trying to send a string to a post view via checkbox being checked and unchecked. The part I am having trouble with is on the post view being able to get read the data. I have the name being generated during the templating of the HTML to tell me the id of the item. Then the javascript is supposed to pass the name of the checkbox to the post view and then just print out the post value. Error The error I'm getting is that it returned a "None" so I'm thinking I'm not getting the name right. In the data field of the javascript, I also tried "data:{data:$header}" and I got the same result. Javascript $("input[type='checkbox']").change(function() { // console.log($header = $(this)[0].name) $header = $(this)[0].name $.post({ url: "", data: $header, headers: { 'X-CSRFToken': csrftoken } }) }); Django view.py class CurrentCodeView(LoginRequiredMixin,DetailView): template_name = 'codes/currentCodes.html' def get(self, request, *args, **kwargs): //doing alot of stuff def post(self,request,*args, **kwargs): print(request.POST.get('data')) -
Why does my own login view with my own User model in Django doesn't work?
I have created my own user model in Django: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_active = models.BooleanField(_('active'), default=False) token_num = models.IntegerField(_('token count'), default=0) money_num = models.IntegerField(_('money count'), default=0) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = _('user') verbose_name_plural = _('users') So then i decided to do my own login view. Here it is: def login(request): if request.method == "POST": form = LoginForm(request.POST) email = request.POST.get('email') password = request.POST.get('password') user = authenticate(username=email, password=password) if user is not None and user.is_active: login(request, user) return HttpResponseRedirect("/main/") else: form = LoginForm() return render(request, 'registration/login.html', {'form': form}) Here is my LoginForm: class LoginForm(forms.Form): user_email = forms.EmailField(max_length=255) password = forms.CharField(max_length=255) class Meta: model = User fields = ('email', 'password') And my login.html: {% extends 'base.html' %} {% block title %}Login{% endblock %} {% block content %} <h2>Login</h2> <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="display: none">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color:red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Login</button> </form> {% endblock %} And here is my urls.py: urlpatterns = [ … -
Django ORM Exclusive ORs
I have an issue with my Django ORM query. This query: Ticket.objects.filter( Q(change_personal_data__personal_data__number=number, change_personal_data__is_active=True) ) produces the following query: SELECT "tickets_ticket"."id" FROM "tickets_ticket" INNER JOIN "tickets_changepersonaldata" ON ("tickets_ticket"."id" = "tickets_changepersonaldata"."ticket_id") INNER JOIN "tickets_personal" ON ("tickets_changepersonaldata"."personal_data_id" = "tickets_personal"."id") WHERE ("tickets_personal"."number" = 'xxxxxxxx' AND "tickets_changepersonaldata"."is_active" = True); and this one: Ticket.objects.filter(Q(Q(personal_data__number=number) & ~Q(change_personal_data__is_active=True))) produces this: SELECT "tickets_ticket"."id" FROM "tickets_ticket" INNER JOIN "tickets_personal" ON ("tickets_ticket"."personal_data_id" = "tickets_personal"."id") WHERE ("tickets_personal"."number" = 'xxxxxxxx' AND NOT ("tickets_ticket"."id" IN (SELECT U1."ticket_id" AS Col1 FROM "tickets_changepersonaldata" U1 WHERE U1."is_active" = True))); but when I combine them (with OR condition) within 1 queryset Ticket.objects.filter( Q( Q(change_personal_data__personal_data__number=number, change_personal_data__is_active=True) | Q( Q(personal_data__number=number) & ~Q(change_personal_data__is_active=True) ) ) ) I get: SELECT "tickets_ticket"."id" FROM "tickets_ticket" LEFT OUTER JOIN "tickets_changepersonaldata" ON ("tickets_ticket"."id" = "tickets_changepersonaldata"."ticket_id") LEFT OUTER JOIN "tickets_personal" ON ("tickets_changepersonaldata"."personal_data_id" = "tickets_personal"."id") LEFT OUTER JOIN "tickets_personal" T4 ON ("tickets_ticket"."personal_data_id" = T4."id") WHERE ("tickets_personal"."number" = 'xxxxxxxx' AND "tickets_changepersonaldata"."is_active" = True) OR (T4."number" = 'xxxxxxxx' AND NOT ("tickets_ticket"."id" IN (SELECT U1."ticket_id" AS Col1 FROM "tickets_changepersonaldata" U1 WHERE (U1."is_active" = True AND U1."id" = ("tickets_changepersonaldata"."id"))))); but I need to have this SQL: SELECT "tickets_ticket"."id" FROM "tickets_ticket" LEFT OUTER JOIN "tickets_changepersonaldata" ON ("tickets_ticket"."id" = "tickets_changepersonaldata"."ticket_id") LEFT OUTER JOIN "tickets_personal" ON ("tickets_changepersonaldata"."personal_data_id" = "tickets_personal"."id") LEFT OUTER JOIN "tickets_personal" T4 … -
How to plot a matplotlib graph(interactive graph) into django template?
I know this question has been asked several times but I just can't find the best solution. I have an arduino code for taking readings and plotting them through matplotlib. These reading are the volume of water passing through a sensor at a given time. I DO NOT wan't to just display an image on html but the whole interactive graph. Following is my python code for plotting the graph import serial import numpy as np import matplotlib.pyplot as plt from drawnow import * ser = serial.Serial('COM3', baudrate = 9600) f=[] v = [] plt.ion() count=0 def makeFig(): ax1 = plt.subplot(211) plt.ylim(0,50) plt.title('Flowrate') plt.grid(True) plt.ylabel('Flow') plt.plot(f, 'ro-', label='litre/min') plt.legend(loc='upper left') ax2 = plt.subplot(212, sharex=ax1) plt.ylim(0,10000) plt.grid(True) plt.ylabel('volume') plt.plot(v, 'ro-', label='mL') plt.legend(loc='upper left') while True: arduinoData = ser.readline().decode('ascii') dataArray = arduinoData.split(',') flow = float (dataArray[0] ) volume = float ( dataArray[1]) f.append(flow) v.append(volume) drawnow(makeFig) plt.pause(.000001) count=count+1 if(count>60): f.pop(0) v.pop(0) My views.py is something like this: def footprint(request): v = vol() volume = v return render(request, 'main/footprint.html', {'volume': volume}) Please suggest some method to get this graph on HTML as easily as possible. -
configuring google cloud datastore in django project
I don't know how to configure google cloud datastore with Django app. I went through a tutorial that sets database backends to dummy as follows DATABASES = { 'default': { 'ENGINE': 'django.db.backends.dummy', } } But in this way my database is not properly configured. I don't understand the logic behind dummy. My admin panel is not accessed either. So my question is how to properly configure cloud datastore with django app. Complete configuration will be appreciated. Thanks. -
Python Django delete multiple records using a check box and a delete button
Looking for some guidance on how to delete multiple rows (a table is produced using a listview - postgreSQL) using a check box and a delete button. -
which part of api documentation you should share
I'm a starting to learn website development. trying to learn by working with freelancers. So I start with to freelancers one for the backend and the other for the frontend. Just finish with the documentation for the api in the backend side. the frontend developer asking me for that documentation to be shared with him. unfortunately am confused. where can I find the documentation for the api. and which part of it that I need to share it with a frontend developer? -
django python search result issue
I am creating a search feature. where the user will input name and city. results should appear like: name available in that city should show up. view.py def search(request): if request.method == 'GET': srch = request.GET['srh'] srch1 = request.GET['srh1'] if srch: match = demo.objects.filter(Q(name__icontains=srch)) if srch1 in match: match2 = demo.objects.filter(Q(city__icontains=srch1)) if match2: return render(request, 'listing-search.html', {'sr':match2}) else: print('no result found') else: return HttpResponseRedirect('') return render(request, 'listing-search.html') Template <form action="search/" method="get"> <div class="input-group input-group-1"> <span class="input-group-addon" id="basic-addon1">Find</span> <input type="text" name= "srh" class="form-control" placeholder="Business Name Type Karo" aria-describedby="basic-addon1" list="find"> </div> <div class="input-group input-group-2"> <span class="input-group-addon" id="basic-addon2">Location</span> <input type="text" name="srh1" class="form-control" placeholder="Ex: Shahabad" aria-describedby="basic-addon2" list="suggest-location"> </div> <button class="btn btn-default" type="submit"><i class="fa fa-search" style="font-size: 25px"></i></button> <div class="fix"></div> </form> Models.py class demo(models.Model): name = models.CharField(max_length=100) city = models.CharField(max_length=100, null=True,) def __str__(self): return self.name -
Django - Authenticate against existing DB
Apologies if this is simple or my terminology is off, this is my first django project. I haven't been able to find a similar solution for this online. I have an existing application, with a postgres DB where I authenticate my users. I have wrote an application in Django to interact with some tables and display info to the user. I would like to use Django to login and track User sessions against this DB. so I can use the features like {% if user.is_authenticated %} but I don't want to use the migrate command so I don't want to change the existing DB. I can access the table where the account info is as I created a model for it. I see you can use remote user logon param but I cant find any sample or guide on how to use it and am completely lost. Right now I create a login form in the views page. Then get the username and password that is entered, but I don't know what to do next. Also would need to hash the password. Is there a libray in djano that will do that for the app. Any pointers or online guides … -
How to filter Django annotations on reverse foreign key fields
I am trying to get a count of all related models with a particular field value. Here is some code... models.py: class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): BAD = "BAD" MEH = "MEH" GOOD = "GOOD" GREAT = "GREAT" REVIEW_CHOICES = ( (BAD, BAD.title()), (MEH, MEH.title()), (GOOD, GOOD.title()), (GREAT, GREAT.title()), ) title = models.CharField(max_length=100) review = models.CharField(max_length=100, choices=REVIEW_CHOICES) author = models.ForeignKey(Author, related_name="books") Suppose I want to list the number of each type of reviews for each author. I have tried: Authors.object.annotate(n_good_books=Count("books")).filter(books__review="GOOD").values("name", "n_good_books") I have also tried: Authors.object.annotate(n_good_books=Count("books", filter=Q(books_review="GOOD"))).values("name", "n_good_books") But neither of these works. Any suggestions? -
i can not upload img to DRF api using Angular 6
i'm new to DRF ,i build a simple api depends on the official documentation evrything works good but when i want to upload img file the request.data is empty request.data = ----> <QueryDict: {}> so if any one can help angular .serviece.ts const httpOptions_multipart = { headers: new HttpHeaders({ 'Content-Type': 'multipart/form-data', 'Authorization': 'Token 28----------------------8d01ab33e1df' }) }; UploadImage(img):Observable<Image> { console.log(img); return this.http.put<Image>(this.profileUrl, img, httpOptions_multipart) } Angular .component.ts fileToUpload: File = null; handleFileInput(files: FileList) { this.fileToUpload = files.item(0); console.log('get item '); var reader = new FileReader(); reader.onload = (event:any){ this.imgUrl = event.target.result; } reader.readAsDataURL(this.fileToUpload) } uploadFileToActivity(){ this.productservice.UploadImage(this.fileToUpload).subscribe(data =>{ console.log(data); }, error => { console.log(error); }); } django rest framework model.py class Profile(models.Model): name = models.CharField(max_length=200) bio = models.TextField(blank=True) pic = models.ImageField(upload_to='pics', blank=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) views.py class ProfileViewSet(viewsets.ModelViewSet): serializer_class = ProfileSerializer queryset = Profile.objects.all() @decorators.action( detail=True, methods=['PUT'], serializer_class=ProfilePicSerializer, parser_classes=(MultiPartParser,) ) def pic(self, request, pk): print ('request.data = ----> ',request.data) obj = self.get_object() print(obj) serializer = self.serializer_class(obj, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return response.Response(serializer.data) return response.Response(serializer.errors, status.HTTP_400_BAD_REQUEST) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['name', 'bio', 'pic'] read_only_fields = ['pic'] class ProfilePicSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['pic'] settings.py REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'DEFAULT_RENDERER_CLASSES': … -
Django: need help in designing relationships between models
I have an app which allows to associate to each client multiple boards, boards where I can upload files relevant for the client to make decisions about how the website page in question will look. So the relationships I need to model are: one client, multiple boards; one board, one client; one board, multiple files; Let's concentrate on the first two models.py class Board(models.Model): title = models.CharField(max_length=120, verbose_name="Titolo") description = models.TextField() files = models.FileField( null=True, blank=True, upload_to = 'clients_download_area', verbose_name = 'Client Reserved File') date = models.DateTimeField(auto_now_add=True, verbose_name = 'Data di pubblicazione') def __str__(self): return str(self.title) class Client(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=120) boards = models.ManyToManyField(Board, blank=True) def __str__(self): return str(self.name) Ok, relationship #1 is done. But what if I need to know which client is associated to a board (relationship #2)? If I set a new field to Board Class class Board(models.Model): [...] client = models.ForeignKey(Client, blank = True) of course, when I makemigrations Django complains because it does not know what Client is, since I define it in the next model. How can I design this DB? Thank you in advance for any help you could provide -
How model inheritance works in django model
class OdishGovtJobs(models.Model): start_date = models.CharField(max_length=60) last_date = models.CharField(max_length=60) post_name = models.CharField(max_length=255) education = models.CharField(max_length=255) more_info = models.CharField(max_length=255) requirement_board = models.CharField(max_length=255) type = models.IntegerField() def __str__(self): return "Odisha Govt Jobs" class AndamanNicoborGovtJobs(OdishGovtJobs): pass def __str__(self): return "Andaman Nicobor Govt Jobs" I wants all the fields in second model fields of first and second model will be same.. It is throwing these error while m doing this.. thanks,, -
Relative font URLs in CSS cause 403s on S3
I am using presigned URLs with boto3 in order to 'protect' (or at least limit access) to content stored on S3 (I pass a relative path to a Django view, and then generate a absolute presigned URL to the storage location on S3, then pass this as a redirect to the client which then retrieves the expected file): import boto3 class ContentStreamView(LoginRequiredMixin, RedirectView): def get_redirect_url(self, **kwargs): ... relevant code below s3_client = boto3.client('s3', aws_access_key_id=self.storage_details.access_key, aws_secret_access_key=self.storage_details.secret_key, config=Config(signature_version=self.storage_details.signature_version)) # Key will equal the filepath to the content required. return s3_client.generate_presigned_url( ClientMethod='get_object', ExpiresIn=60, Params={ 'Bucket': self.storage_details.bucket_name, 'Key': kwargs['filepath'] } ) ... passes the URL back to the client in the get method of the CBV def get(self, request, *args, **kwargs): ... url = self.get_redirect_url(filepath=path) return HttpResponsePermanentRedirect(url) I have my CORS on S3 bucket set up like the following at the moment: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>HEAD</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> I have CORS setup with Django to allow all: CORS_ORIGIN_ALLOW_ALL = True As an example when the browser tries to access https://myapp.com/streamer/some_folder/css/some_css_file.css then the browser is redirected to (and gets the file as expected) to the presigned S3 url: https://examplebucket.s3.amazonaws.com/some_folder/css/some_css_file.css?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=credentials%2Faws4_request&X-Amz-Date=20180924T145056Z&X-Amz-Expires=60&X-Amz-SignedHeaders=host&X-Amz-Signature=signature. This works great, BUT, the relative URLs within the css … -
How to detect if obj is being added or edited inside ModelForm.clean?
I want to validate user submitted data differently whether the user is adding a new object or changing an existing one. There isn't an attribute of the model other than the id that I could check on the db if the object already exist (if it exist on the db, it's being added). In other methods, like save_model, a add parameter is passed, so you can check it, but in modelform.clean there is no such parameter. How to do that verification inside modelform.clean? MyModelForm(forms.ModelForm): def clean(self): if add : validation_A() else: validantion_B() -
How to override url patterns of Django's contrib?
I'm currently writing an app in Django and I'm using the default django.contrib.auth for the users. I'm currently doing the internationalization. I already generated the locale files and it's working well with my custom urls, but it's not working for the auth urls (e.g., login, password_reset, reset/done/). Is it possible to override those? Here are my files: settings.py LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] urls.py re_path(_(r'^users/'), include('django.contrib.auth.urls')), django.po #: users/urls.py:10 msgid "^login/$" msgstr "^iniciar_sesion/$" -
Url Django testing
urls.py of my web application is as follows urlpatterns = [ path('u/<int:unit_id>/', views.unit_view, name='unit_view'), path('u/<int:unit_id>/edit/', views.unit_edit, name='unit_edit'), ] I triedn to write tests for urls are as following from django.urls import reverse, resolve from django.test import TestCase class TestUrls(TestCase): def test_unit_view_url(self): path = reverse('unit_view', kwargs={'unit_id': 1}) self.assertEqual('unit_view', resolve(path).views.unit_view) def test_unit_edit_url(self): path = reverse('unit_edit', kwargs={'unit_id': 1}) assert resolve(path).views.unit_edit == 'unit_edit' Getting error as ERROR: test_unit_view_url (decentmark.tests.test_urls.TestUrls) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Prabhanjan\Documents\GitHub\decentmark\decentmark\tests\test_urls.py", line 8, in test_unit_view_url path = reverse('unit_view', kwargs={'unit_id': 1}) File "C:\Users\Prabhanjan\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\base.py", line 90, in r everse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "C:\Users\Prabhanjan\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 622 , in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'unit_view' not found. 'unit_view' is not a valid view function or pa ttern name. -
Django manager - overriding objects manager of auth.models Group
I'm new to django managers. I'm using python 2.7.15rc and Django 1.8. Normally when I use Group.objects.all() django returns me all groups. I want these groups to be filtered... so I just created a manager for auth.models Group: class DefaultGroupManager(models.Manager): test_ids = [1,2,3,4,5,6,7] def get_queryset(self): return super(DefaultGroupManager, self).get_queryset().exclude(pk__in=test_id) I want this manager to be as default, so when I use Group.objects.all() it will be filtered, BUT I don't know how to override default manager without touching django internal code. I have a big project so i just want to change: Group.objects.all() -> not filtered to Group.objects.all() -> filtered with my manager without changing word "objects" Group.new_nanager.all(), or class name NewGroupClass.objects.all(). Is this even possible? I will appreciate any help. (I'm new to coding) -
AJAX - Displaying current status of the connection to users
I will need to pull data from many datasources - this is a time-consuming process. If user sends the form the program pulls data from 7 tables ( using ajax ) I would like to provide an information what is actually going on ,for example "Pulling data from table1" , "Pulling data from table2" and so on. but have no idea how to do this - Is there a good standard for this kind of task ? I am using python/django as a backend Thanks in advance -
DRF serializing MPTT tree
I am trying to serializer a tree model using this answer. Model class Task(MPTTModel): parent = TreeForeignKey('self', related_name='children') Serializers class TaskChildrenSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ('id', 'name',) def get_fields(self): fields = super(TaskChildrenSerializer, self).get_fields() fields['related_tasks'] = TaskChildrenSerializer(many=True) return fields class TaskBaseSerializer(serializers.ModelSerializer): related_tasks = TaskChildrenSerializer(many=True, read_only=True) class Meta: model = Task fields = ('id', 'is_active', 'related_tasks', 'duration') But with that it shows nested elements as I want, but next it duplicates all children nodes and runs recursively for each of them (as on the picture id 4 and 5 are duplicated). Is there a way to remove that duplication? Or may be any other ways to solve this problem? -
Django sorting without duplicates
Model structure in screenshot. I want structure in template as in the sreen. screen in view i get object: def get_context_data(self, *args, **kwargs): context = super(ArticleDetailView, self).get_context_data(*args, **kwargs) context['article'] = self.get_object() If in template i use cycle for->i have structure like this: type1: news 1; type1: news 2;type 2: news 3. -
Django - JS : How to display the first PDF page as cover
I would like to improve my script in order to set PDF cover page for each object when user sets the mouve over the object on the template. Actual process: Up to now, I can upload .pdf and .epub file formats according to an object with some additionnals fields : title, language ... The PDF is stored into media directory in my project. In the main page, I display all objects like this : As you can see in the end of each publication, there is a glyphicon which let, up to now, to display inside another tab the object PDF file. Expected idea: I would like to know if there is a way to place the mouse over the glyphicon and display a window with the PDF file. The better thing will be to display only the first PDF page in order to define a cover page for each object. I don't know if my request is possible. But if yes, I would like to know which ways I could study to make that. Other possibility, create a new field - pick up the uploaded PDF file and create a function which let to cut the PDF, keep the … -
How to run a script before and after a Python expression is executed in Django shell?
I want to make Django's management command shell to run a script before and after every Python expression is executed. For example: (Think of I'm using command python3 manage.py shell --ipython to get into shell.) In [1]: from api.models import Student In [2]: new_student = Student.objects.create(name="John Doe", number=123) In [3]: new_student.number Out[3]: 123 In [4]: new_student.name Out[4]: "John Doe" I want to send the expressions and outputs of them to a Slack channel.To do that, I need to run a Python script before and after every expression which takes expressions or outputs to log to my Slack channel. For the example above, the script would log expressions, for example "new_student.number", and their outputs -if exist, of course-, for exapmle "123", to the Slack channel. I've tried using django-extensions module, used its shell_plus command with pre and post signals. But it was only calling the signals before and after running the plus_shell. Therefore, what I want to do was running those signal handlers before and after every command/expression. Is there a way to achieve this using a configuration, a module or even writing a custom management command?