Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST Framework - Set request in serializer test for ApiClient
I already read: Django REST Framework - Set request in serializer test?. And it doesn't work for me! Because I'm using APIClient and not RequestFactory like him. I built a web app where the back-end is implemented using the Django REST Framework. Now I'm writing unit tests and I have come across a problem in testing my serializer methods. Here is one example of a serializer method I'm struggling with: def get_can_edit(self, obj): request = self.context['request'] user = User.objects.get(username=request.user) return user == obj.admin When trying to call this from the test, first I declare an instance of the serializer: But now I need self.serializer to have the correct request when get_can_edit does self.context.get('request'). I've created a fake request with the correct information using APIClient: self.client = APIClient() self.client.force_authenticate(user) conference = a_fake_conference res = self.client.get('conference:conference-detail'. args=[conference.id]) serializer = ConferenceSerializer(conference, context={WHAT_IS_REQUEST?}) # I'm using a dict as context but the request gave me an error: context={'request': { 'user': user }} sert.assertEqual(res.data, serializer.data) Now I am stuck because I am unsure how to add request1 to serializer such that request = self.context['request'] will return Thanks. -
Django: dbbackup displays pg_dump: error: too many command-line arguments
I've installed the django-dbbackup package and from what the Documentation tells, i need to run python manage.py dbbackup but it generated error pg_dump: error: too many command-line arguments from what i have seen in the logs dbbackup.db.exceptions.CommandConnectorError: Error running: pg_dump database_name --host=127.0.0.1 --port=5432 --username=postgres --no-password --clean From what i have known, the correct command for pg_dump is to include the database name in the last part but the dbbackup include the database name first. Anyone know the fix for the Django-dbbackup? -
Display image from ImageField by means of form BUT with Upload button
I've been looking for a solution for a while. I saw this solution to show the image instead of just the link to the image: Display image from ImageField by means of form But now I need to add a button so they can upload a new picture. Any solution to this? Thanks in advance! -
Flask SQLite database query not returning results properly,
Hi am really new to flask, sqlalchemy and using databases, I am trying to query from a relational SQLite database which contains 4 different tables. My query is as follows: presults=[] presults= [(q[0],q1) for q in db_session.query(Phosphosite, Substrate).filter(Substrate.SUB_ORGANISM.ilike('human')).filter(Substrate.KIN_ACC_ID.ilike(srch_strg)).join(Phosphosite, Substrate.SUB_ACC_ID == Phosphosite.SUBSTRATE_ACC_ID).all()] and the presults list is being passed to the html using Django {{}} into a table: <table class="table" cellspacing="0"> <thead> <th>{{presults}}</th> <tr> <th>Gene</th> <th>Protein</th> <th>Modified Residue</th> <th>Phosphorylation site AA sequence</th> <th>Domain</th> <th>Neighbouring Sequence</th> </tr> </thead> <tbody> {% for x in presults %} <tr> <td>{{x.Substrate_SUB_GENE}} <td>{{x.Substrate_SUBSTRATE}}</td> <td>{{x.Substrate_SUB_MOD_RSD}}</td> <td>{{x.Substrate_SITE_AA}}</td> <td>{{x.Substrate_DOMAIN}}</td> <td>{{x.Phosphosite_Neighboring_Seq}}</td> </tr> {% endfor %} however my table seems to have received the results as multiple empty rows have been produced however nothing is being printed. below is my table and the result of the tuple{{presults}} in the html enter image description here a -
How does @cache_page enable server side caching?
https://docs.djangoproject.com/en/3.0/topics/cache/ says "The cache system requires a small amount of setup. " It seems I have to setup something to make server side caching work. I didn't do any settings, I solely put @cache_page on my method in view.py. I run the server and request the page, only the first request executes the print statement. I think the caching is kicking in. So what caching backend is it using? -
Frontend receives 403 error when logged in if Django admin is also logged in
I'm trying to understand if I can be logged in as a user in both the django admin and frontend at same time in development mode. For some reason both won't work. If I log out of admin I can request data and do some crud operations in the frontend. If I'm logged in the admin and logged in the frontend all crud like operations receive a 403 error. I'm using django/backend nuxt/fronend and docker. What do I need to do in order to have both logged in and working on data? -
how to find montly total amount
so i have this model two models class Pv(models.Model): IA_System_Code = models.AutoField(primary_key = True) IA_code = models.CharField(max_length = 150) Date_recieved = models.DateField() Pv_reference = models.CharField(unique = True, max_length = 120) Payee = models.CharField(max_length=500) Description = models.CharField(max_length = 500) class Meta(): ordering = ["-IA_System_Code"] def __str__(self): return self.Description class staff(models.Model): staff_id = models.CharField(max_length = 150) name = models.CharField(max_length = 300) rank = models.CharField(max_length = 300) amount = models.DecimalField(max_digits=19, decimal_places=2) Pv_reference = models.ForeignKey('Pv',on_delete=models.CASCADE) date_created = models.DateField() def __str__(self): return self.name so pv model has a one to many relation with staff. it means many staff can benefit from one pv. and we can have a staff benefiting from diffent pv's. so the staff model can have a single staff repeating like 10 times in a month because by benefiting from different pv's . now my question is how do i get the monthly total amount of each staff -
Django-Scheduler: jQuery and Bootstrap files not loading
I’ve been having issues with loading jQuery and Bootstrap tiles through the django-scheduler. In console I get: Failed to load resource: the server responded with a status of 404 (Not Found) jquery.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) jquery-ui.min.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) bootstrap.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) all.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) bootstrap.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) all.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) If anyone has an updated tutorial for Django-Scheduler and would like to share a way to load the full calendar stuff without using things like bower, that’d be great. -
adding the user to a many to many field upon creating a model
good day, I am trying to create a viewset whereby when a showcase is created, the user gets added as one of the administrators in the many to many fields, but my code doesn't seem to work. below is what I have tried, which doesn't work. models.py class Showcase(models.Model): title = models.CharField(max_length=50) description = models.TextField(null=True) skill_type = models.ForeignKey(Skill, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="Showcases") content = models.TextField(null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) voters = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="upvotes") slug = models.SlugField(max_length=255, unique=True) administrator = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="administrators", blank=True) def __str__(self): return self.title views.py class showcaseCreateViewSet(generics.CreateAPIView): queryset = Showcase.objects.all() serializer_class = ShowcaseSerializer permission_classes = [IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save(user=self.request.user, administrator=self.request.user) -
How to most compactly implement the code on DRF ORM
def read_rate(self, id): cursor = self.db.cursor() cursor.execute('SELECT volume FROM rate WHERE cur_id = ' + str(id) + ' ORDER BY id DESC LIMIT 10') volume = cursor.fetchall() cursor.execute('SELECT rate FROM rate WHERE cur_id = ' + str(id) + 'ORDER BY id DESC LIMIT 1') (get,) = cursor.fetchone() rate = str(get) average = str(sum([float(x[0]) for x in volume])/len(volume)) cursor.close() return {'rate': rate, 'average_volume': average} Need to implement the code on DRF ORM, where queryset will return 'cur id', 'last rate' and 'average volume in the last 10 days' Model class Rate(models.Model): cur = models.ForeignKey(Cur, on_delete=models.CASCADE) date = models.DateField(auto_now=True) rate = models.FloatField() volume = models.FloatField() def __str__(self): return self.cur class Meta: ordering = ['-id'] and how I tried to implement class RateView(ListAPIView): serializer_class = RateSerializer def get_queryset(self): return Rate.objects.values( cur__id__in=[self.kwargs['id']]).order_by( '-id')[:10].annotate(Avg('volume'), 'rate', self.kwargs['id']) -
Is it possible to create dynamic Django variables with javascript?
I'm passing variable from django to my template. It is called {{object.price}} I want to build this variable in js and be able to still access it. What I've done so far: "{{"+"object."+"price"+"}}" The above returns Parse error for "." - Is it even possible to do that ? -
smtplib.SMTPConnectError: (451, b'Request action aborted on MFE proxy, SMTP server is not available.')
Please i have been facing this error for the past three days , i have already checked all answers and i have made appropriate corrections, allowed less secure apps, off 2 factor authentication, cross checked username/password But non of these help settings.py code SERVER_EMAIL = 'infopython@gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_HOST_USER = SERVER_EMAIL EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER ADMINS = [ ('admin', 'admin5@gmail.com'), ] MANAGERS = ADMINS Output Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\sendtestemail.py", line 33, in handle recipient_list=kwargs['email'], File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\mail\__init__.py", line 60, in send_mail return mail.send() File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\mail\message.py", line 294, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\mail\backends\smtp.py", line 103, in send_messages new_conn_created = self.open() File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\mail\backends\smtp.py", line 63, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\smtplib.py", line 254, in __init__ raise SMTPConnectError(code, msg) smtplib.SMTPConnectError: (451, b'Request action aborted on MFE proxy, SMTP server is not available.') -
Django: file upload folder relative runserver command
I have a small form for file upload. #import os from .models import Pkvjanosch def handle_uploaded_file(f, rgauswahl): #PROJECT_PATH = os.path.abspath(os.path.dirname(name)) d = Pkvjanosch.objects.filter(rg_id = rgauswahl) dateizusatz = d[0].rgsteller + " " + d[0].rgdatum.strftime("%d.%m.%Y") with open('documents/' + dateizusatz, 'wb+') as destination: #with open(PROJECT_PATH + '/documents/' + dateizusatz, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) When I run the runserver with python3 /var/services/[abbreviated]/DjangoProject/abrechnung/manage.py runserver 0:8000 from the root folder of the django app and I use this form, it works fine and the uploaded file ends up in the document folder. But if instead I start the runserver from within the documents folder, this results in an error. From the error message [Errno 2] No such file or directory: '[abbreviated]/DjangoProject/abrechnung/rgeingabe/documents/documents/filename.pdf' I can see that the path gets mixed up and that the folder document now is nested in itself. So, how can I resolve this without using an absolute path? Best regards -
How to get one of reverse foreign-key records when in a model queryset
I'm working on a django website for keeping track of devices in the network. I have a model Device: class DeviceManager(models.Manager): def get_queryset(self): return super().get_queryset().annotate( num_interfaces=Count('interface', distinct=True)) class Device(models.Model): objects = DeviceManager() uuid = models.UUIDField() name = models.CharField(max_length=30) class Meta: _base_manager = DeviceManager() and then I have model Interface: from .models import Device class Interface(models.Model): ip = models.GenericIPAddressField() device = models.ForeignKey(Device, on_delete=models.CASCADE) When displaying a list of devices, I need to list the number of interfaces for each device. So I created the Manager which pulls the count with one query, instead of having a separate query for each device in the list. Now I want to display a random IP for each device. It doesn't which one, if a device has multiple interfaces. I started writing another .annotate to my DeviceMangerand I am not sure what to do. I was thinking about using a subquery, something like: subquery = Interface.objects.filter(ip=OuterRef('ip')) so: class DeviceManager(models.Manager): def get_queryset(self): subquery = Interface.objects.filter(device_id=OuterRef('device')) return super().get_queryset().annotate( num_interfaces=Count('interface', distinct=True)).annotate( ip=Coalesce(Min(Subquery(subquery('ip'))), None) But then I realized that Interface depends on Device, and so I can't refer to Interface until Device is fully defined, so definitely not in DeviceManager What is the best way of doing this? -
Python for loop in Django returning random value in dictionary
I have a Wagtail page displaying the routing link block inside it and I'm adding an icon to the routing link model to display with title in the block on main page. In the main page I'm getting the context for uploaded file field for icon as below: def get_context(self, request): context = super().get_context(request) routing_links_queryset = self.routing_links for link in routing_links_queryset: i_link = link.link_icon if i_link: try: with i_link.icon.open() as file_obj: data = file_obj.read() data = data.decode("utf-8") context["iconlink_data"] = data except OSError: pass return context link_icon is field in routing_links model and icon is Filefield in Icon model. Now this is returning the context on the main page but if there are 2 routing link blocks on the main page, it will render the same icon for both. Do I have to append the context in each iteration? How exactly I could append in this case or any alternative way to do this? -
Django: Let high-level users register low-level users
I have a form that can access by the boss account, the boss will use this form to create his employee accounts def EmployeeForm(forms.Form): username = forms.CharField(max_length = 16) But the problem is I don't now how to validate this username field like UserCreationForm Does, and I think I need to do so -
Upload multiple files with one single input
Multiple files do not save in admin, only the first saved in admin. class Image(models.Model): imageuploader_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True) image = models.FileField(upload_to ='pictsagram/') image_caption = models.CharField(max_length=700) def upload(request): form = PostForm(request.POST,request.FILES) if request.method == "POST": if form.is_valid(): for f in request.FILES.getlist('image'): post = Image(image=f) post = form.save(commit=False) post.imageuploader_profile = request.user print(request.user) post.save() form.save() return redirect('/') else: form = PostForm() return render(request, 'upload.html', {"form": form}) class PostForm(forms.ModelForm): class Meta: model = Image fields = ('image_caption', 'image',) -
How to solve problem css/js file is conflic in djangocms plugin?
in example i have a 2 plugins such us plugin AAA and plugin BBB.The static file in Those two plugins have reference css/js to same tag like below pluginAAA/static/pluginaaa/css/style.css .text-style{ color : red; } pluginAAA/templates/text-example-A.html {% load static cms_tags sekizai_tags %} {% addtoblock "css" %} <link href="{% static "pluginaaa/css/style.css" %}" rel="stylesheet /> {% endaddtoblock %} <span class="text-style">Hello</span> pluginBBB/static/pluginbbb/css/style.css .text-style{ color : blue; } pluginBBB/templates/text-example-B.html {% load static cms_tags sekizai_tags %} {% addtoblock "css" %} <link href="{% static "pluginbbb/css/style.css" %}" rel="stylesheet /> {% endaddtoblock %} <span class="text-style">Hello</span> Then i use command "python manage.py collectstatic" to collect static file and run "python manage.py runserver".Those two plugins it show all blue color.How i can solve this problem without change css/js class name. because fact file css have a multiple line and more than two plugins.i want to pluginAAA show red color and pluginBBB show blue color -
Sending data between views in Django
I want to send data between 2 views in Django. Main logic is that on main mage I have a simple form where I input url. After submit I scrap data from this url and redirect to endpoint /bokeh. From this endpoint I want to go to endpoint /days (from the navbar) and operate on the same given URL. I was trying to use session, but it didn't work well. My code looks like: views.py def home(request): if request.method == 'POST': url = request.POST['url'] request.session['url'] return redirect('bokeh',url=url) return render(request,'home.html') def bokeh(request,url): cl = CalculationLogic() return cl.get_data_from_url(request,url) def days(request,url): cl = CalculationLogic() url = request.session.get('url') return cl.show_days_of_the_week(request,url) So, after sending data from home.html to bokeh, everything is fine and I do my CalculationLogic. When I want to go to days I get NoReverse Match error: NoReverseMatch at /days/https://github.com/USER/PROJECT/commits/master Reverse for 'days' with keyword arguments '{'url': ''}' not found. 1 pattern(s) tried: ['days/(?P<url>.+)'] and my urls looks like: urlpatterns = [ .... url(r'^days/(?P<url>.+)',views.days,name='days'), .... ] in my base.html file I have: <body> <nav> <a class="nav-link" href="{% url 'days' url=url %}">Days</a> </nav> </body> Does anyone know why this soulution does not work? -
Django 3 - Making Model's FK Dropdown Display Current User's Data Only
I'm creating my first app with Django and still have a lot to learn, but right now I am completely stuck and need some help. I have a model for Customers and Tickets. I have it so different users can save new customers/tickets and only view their data from the dashboard once logged in. However, when creating a new ticket, there is a dropdown option to select customer for the ticket - and the current user is able to see every users customers. Here is the code, I'll share more code if needed, but I think this covers what I have going on... forms.py class TicketForm(ModelForm): class Meta: model = Ticket fields = ['number', 'customer','date_created','work_description','mechanics','status'] views.py def createTickets(request): form = TicketForm() if request.method == 'POST': form = TicketForm(request.POST) if form.is_valid(): newticket = form.save(commit=False) newticket.shopowner = request.user newticket.save() return redirect('tickets') context = { 'form': form } return render(request, 'createticket.html', context) models.py class Ticket(models.Model): def default_number(): no = Ticket.objects.count() return no + 1 shopowner = models.ForeignKey(User, on_delete=models.CASCADE, default=1) number = models.CharField(max_length=30, unique=True, default= default_number) customer = models.ForeignKey(Customer, default=1, on_delete= models.SET_DEFAULT, blank=True) date_created = models.DateField(default=timezone.now) work_description = models.TextField(verbose_name="Service Details: ") mechanics = models.ForeignKey(Mechanic, default=1, on_delete=models.DO_NOTHING, blank=True, verbose_name="Mechanic") status = models.BooleanField(default=True, verbose_name="Open Ticket") class … -
I have a problem Django , authViews.LoginView.as_view(template_new="")
from django.contrib.auth import views as authViews is that module My code path("user/", authViews.LoginView.as_view(template_new="users/user.html"), name="user"), path("exit/", authViews.LogoutView.as_view(template_new="users/exit.html"), name="exit"), My problem is server does not see as_view(template_new="") -
"Site can't be reached" when hosting 2 different django websites on uwsgi emperor
I'm currently trying to host two different Django websites on a single AWS server using Nginx and Uwsgi emperor. Here are my config files: website1.ini [uwsgi] # django-related settings # the base directory (full path) project_name = backend base_dir = /home/ubuntu/website1/ virtualenv = /home/ubuntu/website1/env #chdir = location where manage.py is present chdir = %(base_dir)/backend # django's wsgi file module = %(project_name).wsgi:application # the virtualenv (full-path) # process related settings # master master = true # maximum number of processes processes = 10 # the socket (use the full path to be safe) socket = /home/ubuntu/server_files/website1socket.sock # ... with appropriate permissions - may be needed chmod-socket = 666 # clearn environment on exit vacuum = true website2.ini [uwsgi] # django-related settings # the base directory (full path) project_name = website2backend base_dir = /home/ubuntu/website2/ virtualenv = /home/ubuntu/website2/env #chdir = location where manage.py is present chdir = %(base_dir)/djangoRestApi # django's wsgi file module = %(project_name).wsgi:application # the virtualenv (full-path) #:home = /home/ubuntu/website2/env # process related settings # master master = true # maximum number of processes processes = 5 # the socket (use the full path to be safe) socket = /home/ubuntu/server_files/website2socket.sock # ... with appropriate permissions - may be needed chmod-socket = … -
Why is my Django filter query using dates not returning expected results?
I'm using Django 2.2.6. I have a model like this: class NetflowRecord(models.Model): ############# # Help Text # ############# min_mac_length_error_message = "Must be at least 12 characters long" data_help_text = "Bytes" direction_help_text = "True if record reflects downloaded bytes.<br>False if data reflects uploaded bytes." ########## # Fields # ########## timestamp = models.DateTimeField(auto_now_add=True, blank=False, null=False, editable=False) mac = models.CharField(max_length=17, unique=False, blank=False, null=False, validators=[MinLengthValidator(12, min_mac_length_error_message), validate_mac], editable=False) data = models.BigIntegerField(default=0, blank=False, null=False, help_text=data_help_text, validators=[MinValueValidator(0)], editable=False) direction = models.BooleanField(blank=False, null=False, help_text=direction_help_text, editable=False) site = models.ForeignKey(Site, on_delete=models.CASCADE, blank=False, null=False, related_name="netflow_records") ########## # Extras # ########## class Meta: verbose_name = "Netflow Record" verbose_name_plural = "Netflow Records" ordering = ['mac', 'timestamp'] def __str__(self): formatted_date = self.timestamp.astimezone().strftime("%b %d, %Y - %I:%M:%S %p") if self.direction: return f"Download record for {self.mac} on {formatted_date}" else: return f"Upload record for {self.mac} on {formatted_date}" Seems pretty basic. I have a bunch of records in the database in the table this model created. Using the interactive shell, if I do this: >>> from django.utils import timezone >>> from my_app.models import NetflowRecord >>> >>> for record in NetflowRecord.objects.filter()[:3]: ... print(record.timestamp) ... 2020-02-06 19:20:41.758768+00:00 2020-02-06 20:20:46.491537+00:00 2020-02-06 19:07:57.482944+00:00 >>> for record in NetflowRecord.objects.filter(timestamp__year=2020)[:3]: ... print(record.timestamp) ... 2020-02-06 19:20:41.758768+00:00 2020-02-06 20:20:46.491537+00:00 2020-02-06 19:07:57.482944+00:00 >>> for record in … -
Add button under CKEditor is not visible
I have used CKEditor django plugin in my form modal. But when i try to show ADD button below the CKEditor, the button doesn't appear in the UI at all. As shown in the below image, I have currently kept the Add button on the top of the CKEditor text box as its not appearing when placed at the bottom. Below is the HTML code snippet <div class="row"> <div class="col-md-12"> <div class="form-group"> <label for="">Driver Name</label> <input type="text" class="form-control" name="dn" id="dnn" required="True" /> </div> <div class="form-group"> <label for="st">Driver Description</label> <textarea name="editor1" id="editor1"></textarea> <script> CKEDITOR.replace( 'editor1' ); </script> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary up"> ADD </button> </div> </div> </div> <script src="https://cdn.ckeditor.com/4.5.6/standard/ckeditor.js"></script> Can someone please suggest how to make the add button make it appear below ckeditor. -
Django Random FileField Problem when is deleted
I have a project where I upload files with random file name class Exames(models.Model): #models.py title = models.CharField(max_length=50) patient = models.ForeignKey(User, on_delete=models.CASCADE) exame_pdf = models.FileField(upload_to=RandomFileName('exames')) def __str__(self): return self.title def filename(self): return os.path.basename(self.exame_pdf.name) But when I delete a 'Exames' obj I want to the file to be deleted as well so I used this piece of code(It was working before the random file thing) @receiver(models.signals.post_delete, sender=Exames) def auto_delete_file_on_delete(sender, instance, **kwargs): """ Deletes file from filesystem when corresponding Exames object is deleted. """ if instance.exame_pdf: if os.path.isfile(instance.exame_pdf.path): os.remove(instance.exame_pdf.path) @receiver(models.signals.pre_save, sender=Exames) def auto_delete_file_on_change(sender, instance, **kwargs): """ Deletes old file from filesystem when corresponding Exames object is updated with new file. """ if not instance.pk: return False try: old_file = Exames.objects.get(pk=instance.pk).exame_pdf except Exames.DoesNotExist: return False new_file = instance.exame_pdf if not old_file == new_file: if os.path.isfile(old_file.path): os.remove(old_file.path) How can I make this work again