Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-ckeditor 404 errors
I'm receiving several 404-errors when using django-ckeditor. This is what my static folder looks like The first is on the ckeditor.js file, which is located at static/boot/ckeditor/ckeditor and the error I receive is as follows: "GET /static/ckeditor.js HTTP/1.1" 404 1657 Following, I receive a few errors on other documents that are actually in the folders where I get an error: "GET .../AGAPE/static/boot/ckeditor/ckeditor/config.js?t=JB9C HTTP/1.1" 404 2494 "GET .../AGAPE/static/boot/ckeditor/ckeditor/skins/moono-lisa/editor.css?t=JB9C HTTP/1.1" 404 2548 "GET .../AGAPE/static/boot/ckeditor/ckeditor/lang/nl.js?t=JB9C HTTP/1.1" 404 2497 For the last three, I imagine that the error is caused by the characters that are added at the end of the file name, e.g. ?t=JB9C, but I don't get why these characters are added. Additionally, my settings.py file: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/boot/') STATIC_FILES_DIRS = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'boot'),] MEDIA_ROOT=os.path.join(os.path.dirname(BASE_DIR), 'media') MEDIA_URL="/media/" CKEDITOR_BASEPATH = os.path.join(os.path.dirname(STATIC_ROOT), 'ckeditor/ckeditor/') CKEDITOR_UPLOAD_PATH = "uploads/" CKEDIT_IMAGE_BACKEND = 'pillow' CKEDITOR_CONFIGS = { 'default': { 'toolbar':[ ['CodeSnippet', ], ], 'height': 400, 'width': 900, 'removePlugins': 'stylesheetparser', 'extraPlugins': 'codesnippet', }, } And the relevant models.py file (in the relevant app): from django.db import models from django.contrib.auth.models import User from ckeditor_uploader.fields import RichTextUploadingField from ckeditor.fields import RichTextField STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) cover = models.ImageField(upload_to='images/') … -
when im trying to add questions in the Question model with choices from Choice model it is showing all the choices from previous additions ,
when im trying to add questions in the Question model with choices from Choice model it is showing all the choices from previous additions ,but i want different choices for each here is my models.py code.. from django.db import models from django.contrib.auth.models import User class Assignment(models.Model): title = models.CharField(max_length=400) teacher = models.ForeignKey(User ,on_delete=models.CASCADE) slug = models.SlugField() def __str__(self): return self.title class GradedAssingnment(models.Model): student = models.ForeignKey(User,on_delete=models.CASCADE) assignment = models.ForeignKey(Assignment,on_delete=models.SET_NULL, blank=True , null=True) grade = models.FloatField() def __str__(self): return self.student.username class Choice(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.title class Question(models.Model): question = models.CharField(max_length=1000) choice = models.ManyToManyField(Choice,related_name="hoice") answer = models.ForeignKey(Choice, on_delete=models.CASCADE , related_name='answer') assignment = models.ForeignKey(Assignment,on_delete=models.CASCADE ,related_name='questions') order = models.SmallIntegerField() def __str__(self): return self.question -
Django rest framework empty field in partial update not updated
When I try to do a partial update with patch or a update with put. The object first looks like this: { "name":"Amsterdam 1", "location":"Amsterdam", "client":"b9c7d1c9-4b1b-4f0d-af30-2d8ffb97647e" } Then I remove the client on the object and thus send this back: { "name":"Amsterdam 1", "location":"Amsterdam" } But this does not remove the client from the object. The model looks like this: class FixedLocation(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=155) client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True, blank=True) location = models.CharField(max_length=263) And this is how my serializer looks class FixedLocationSerializer(serializers.ModelSerializer): class Meta: model = models.FixedLocation fields = ["id", "name", "location", "client"] I expect when I don't send client back that it gets removed from the object. Does anybody know how I can achieve this? I also tried playing with null and blank on the foreign key. -
How can i link AI with django for movie recommendation system
i want to implement AI in my django .I am making movie recommendation system and i hav done simple recommendation system in jupyter notebook. So how can i link recommendation part and django? -
The view ProductCreateView didn't return an HttpResponse object. It returned None instead
How to redirect to another page from def form_valid(self): inside a generic FormView. I know I should do something like Super(className, self).form_valid(form): but this will never redirect to a dynamic link, but will only go to the success URL Here is my code : class ProductCreateView(FormView): form_class = ProductCreateForm template_name = 'back_office/product_create_form.html' success_url = reverse_lazy('product_recipe_wrapper') def form_valid(self, form): category = Category.objects.get(id=self.kwargs['pk']) name = form.cleaned_data['name'] image = form.cleaned_data['image'] big_size = form.cleaned_data['big_size'] mid_size = form.cleaned_data['mid_size'] small_size = form.cleaned_data['small_size'] new_product = Product.objects.create(category=category, name=name, image=image) big_size_object = ProductSize.objects.create(product=new_product, size=Size.objects.get(id=1), sell_price=big_size) mid_size_object = ProductSize.objects.create(product=new_product, size=Size.objects.get(id=2), sell_price=mid_size) small_size_object = ProductSize.objects.create(product=new_product, size=Size.objects.get(id=3), sell_price=small_size) if small_size_object.sell_price != 0: return reverse_lazy('product_small_recipe', args=[small_size_object.id]) def get_context_data(self, *args, **kwargs): context = super(ProductCreateView, self).get_context_data() context['category'] = Category.objects.get(id=self.kwargs['pk']) return context -
Why can't i access to all the info in my partyinstancemodel?
my admin model [my listview ][2] obtained result my model Expected Result [my template file ][4] -
Materialize CSS select dropdown arrow displaced
Below is a screen shot of the materialize css as seen from: https://materializecss.com/select.html But for some reason, I get the little arrow of the drop down under the list rather than on the side. I am using Django 3. How do I fix this? And the following is the HTML of the rendered page: <html><head> <meta name="viewport" content="width = device-width, initial-scale = 1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"> </script> <script> document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('select'); var instances = M.FormSelect.init(elems); }); </script> </head> <body class="vsc-initialized"> <nav> <div class="nav-wrapper"> <a href="#" class="brand-logo right">SIW</a> <ul id="nav-mobile" class="left hide-on-med-and-down"> <li><a href="/">Home</a></li> <li><a href="/Contact">Contact</a></li> </ul> </div> </nav> <div class="section"> <div class="row"> <form class="col s12"> <div class="input-field col s4"> <div class="select-wrapper"><input class="select-dropdown dropdown-trigger" type="text" readonly="true" data-target="select-options-07dbac11-476d-4358-8e69-a8d561e0df80"><ul id="select-options-07dbac11-476d-4358-8e69-a8d561e0df80" class="dropdown-content select-dropdown" tabindex="0" style=""><li class="disabled selected" id="select-options-07dbac11-476d-4358-8e69-a8d561e0df800" tabindex="0"><span>Choose your option</span></li><li id="select-options-07dbac11-476d-4358-8e69-a8d561e0df801" tabindex="0"><span>Option 1</span></li><li id="select-options-07dbac11-476d-4358-8e69-a8d561e0df802" tabindex="0"><span>Option 2</span></li><li id="select-options-07dbac11-476d-4358-8e69-a8d561e0df803" tabindex="0"><span>Option 3</span></li></ul><svg class="caret" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"></path><path d="M0 0h24v24H0z" fill="none"></path></svg><select tabindex="-1"> <option value="" disabled="" selected="">Choose your option</option> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select></div> <label>Materialize Select</label> </div> </form> </div> </div> <!--JavaScript at end of body for optimized loading--> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <div class="hiddendiv common"></div></body></html> -
Django form not saving multiple images into database
I am currently learning django. My django form is only saving a single image into the database even after selecting multiple images. any help will be highly appreciated. Here is my code; models.py class Post(models.Model): post = models.TextField(max_length=500, null=False, blank=False) image = models.ImageField(blank=True) date_published = models.DateTimeField(auto_now=True, verbose_name='date published') date_updated = models.DateTimeField(auto_now=True, verbose_name='date updated') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) def __str__(self): return self.detail @receiver(post_delete, sender=Post) def submission_delete(sender, instance, **kwargs): instance.image.delete(False) def pre_save_ad_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = slugify(instance.author.username + '-' + instance.detail) pre_save.connect(pre_save_ad_post_receiver, sender=Post) forms.py class CreatePostForm(forms.ModelForm): image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = Post fields = [ 'post', 'image'] views def home(request): context = {} form = CreatePostForm(request.POST or None, request.FILES or None) images = request.FILES.getlist('images') if form.is_valid(): for img in images: Post.objects.create(image=img) obj = form.save(commit=False) obj.author = user obj.save() form = CreatePostForm() context['post_form'] = form return render(request, 'posts/home.html', context) -
Not successfully added my profile model fields data to database django
My models.py file from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() from django import forms from django.contrib.auth.models import User from .models import Profile My forms.py file class UserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'email', 'password') class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('bio', 'location', 'birth_date') My views.py file def signup(request): if request.method == 'POST': user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): username = user_form.cleaned_data['username'] email = user_form.cleaned_data['email'] password = user_form.cleaned_data['password'] bio = profile_form.cleaned_data['bio'] location = profile_form.cleaned_data['location'] user = User.objects.create_user(username,email,password) user.save() usr = User.objects.get(id=id) profile = Profile(user=usr, bio=bio, location=location) profile.save() messages.success(request, _('Your profile was successfully updated!')) return redirect('login') else: user_form = UserForm() profile_form = ProfileForm() return render(request, 'profile.html', { 'user_form': user_form, 'profile_form': profile_form }) Not successfully added my profile model fields data to database but added id.Please help Not successfully added my profile model fields data to database but added id.Please help Not successfully added my profile model fields data … -
Custom Django manager filter
I'm using a custom manager for getting correct queryset class ReportManager(models.Manager): def get_queryset(self): queryset = None for subclass in BaseReport.__subclasses__(): try: reports = ( subclass.objects.select_related('aircraft', 'flight') .only('id', 'aircraft', 'flight', subclass.TRIGGER_FIELD) .annotate( description=F(subclass.TRIGGER_FIELD), report_datetime=F(subclass.DATETIME_FIELD), ) ) if not queryset: queryset = reports else: queryset = queryset.union(reports) except AttributeError: pass return queryset So the problem is when I'm trying to use the .filter() method from this manager, it doesn't work. I've checked the SQL query, there is no WHERE or LIKE keywords for filtering. I guess it's all because I'm using .only() -
Django says Pillow is not installed even though it is
I keep getting the same error when I try to run manage.py runserver: Cannot use ImageField because Pillow is not installed. I have seen several threads made by people that have encountered the same problem but none of them have a straightforward fix to this issue. I have already installed Pillow (pip install Pillow and pip3 install Pillow). I have uninstalled it several times, and reinstalled it. But whenever I run my server it says that Pillow is not installed. I am on Windows 10. Any help would be appreciated. -
Django - Display specific JSON parts only
I have a file that has some JSON data .. I click a button and it renders on my HTML page ... However I only want to see specific pieces from the file Here is my view.py def read_file(request): f = open('output.txt', 'r') file_content = f.read() f.close() context = {'file_content': file_content} return render(request, "index.html", context) Here is my html <html> <head> <title> Test Test 123 </title> </head> <body> <form action="/open_file/" method="post"> <input type="submit" value="Get Details"> <br><br> {% csrf_token %} {{ file_content | linebreaks }} </form> </body> </html> In the textfile the JSON looks like this ====================Response==================== { "responseBody": { "errorId": 200, "errorMsg": "ok", "userDetails": { "fname": "Andy", "lname": "Test", "status": "YES", "email": "testuser@.com", "userName": "usernametest1212", "deviceDetails": { "type": "Mobile", "osVersion": "5.0.0", "nickname": "Test Telephone", "deviceModel": "Samsung" }, "devicesDetails": [ { "type": "Watch", "osVersion": "iOS 11", "email": null, "hasWatch": yes }, } What i would like to see is the following: ErrorMsg UserDetails - username and email deviceDetails - type and device model -
How to add a background imageas static image in django
please help me with this. I have an image slider. it shoud add like this bellow.. <div class="slider-item" style="background-image: url('img/hero_2.jpg');"> <div class="container"> <div class="row slider-text align-items-center justify-content-center"> <div class="col-md-8 text-center col-sm-12 element-animate"> <h1>Delecious Food</h1> <p class="mb-5">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi unde impedit, necessitatibus, soluta sit quam minima expedita atque corrupti reiciendis.</p> <p><a href="#" class="btn btn-white btn-outline-white">Get Started</a></p> </div> </div> </div> </div> Not working like these ways <div class="slider-item" style="background-image: url({%static'/img/hero_1.jpg'%});"> or <div class="slider-item" style="background-image: url{%static'/img/hero_1.jpg'%}"> I don't want to add like an img tag like this way " <img src="{% static '/img/hero_2.jpg' %}" />" I am using Django latest version with python 3.0 all are latest version Thank you -
Django Create table statement return error - Database Error ORA-00922: missing or invalid option
I am trying to create a table in my oracle database from django view using the input from the user. Upon collecting the inputs and converting it to a string. I am able to get the below as string.. CREATE TABLE Zen.TableSample (TableSample_id NUMBER GENERATED BY DEFAULT AS IDENTITY NOT NULL, EMPNAME VARCHAR2(100), PRIMARY KEY(TableSample_id) ) TABLESPACE "MYTABLESPACE"; I have it in a variable called "sqlstring" and then I am trying to create the table using the following code.. with connection.cursor() as cursor: cursor.execute(sqlstring) print("Query Executed") I am getting an error as "Database Error ORA-00922: missing or invalid option" Any advise on how to fix this.. Please advise. -
How do I access other model's instances using @property and Foreignkey in Django?
I have this simple example to illustrate what I would appreciate your help with. from django.db import models # Create your models here. class A (models.Model): job = models.TextField name = models.ForeignKey('B', models.DO_NOTHING) @property def nick(self): return self.name.surname class B (models.Model): surname = models.TextField() I would expect 'nick' to have the value of a given related surname when I will need to use it somewhere later on. Instead, the surname gives the following error: 'Unresolved attribute reference 'surname' for class 'ForeignKey'' How to achieve that when I somewhere use 'nick' it will return the surname? Thank you in advance! -
Django signals with ATIMIC_REQUESTS=True
Using Django (and DRF) If I'm set ATIMIC_REQUESTS=True on the Database config, would this apply for signals as well? I'm trying to understand if there is a chance our transaction is finished after response -
How to send data from localhost to server using Python requests?
I am trying to send data from localhost to an API in remote server using Python Requests & Django through an API: /api/send-data/ Path for /api/send-data/ in urls.py is path('send-data/',view_send_data.send_data,name='send_data') This is my view_send_data.py in my localhost: @api_view(('POST',)) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def send_data(): # defining the API-endpoint API_ENDPOINT = "http://68.183.89.234/api/screen/" # data to be sent to API data = {'data':1234} # sending post request and saving response as response object r = requests.post(url = API_ENDPOINT, data = data) print(r.json()) return Response({"success": True}, status=status.HTTP_200_OK) Path for api at http://68.183.89.234/api/screen/ in urls.py is path('screen/',views_fr.screen_display,name='screen') This is my views_fr.py in my remote server: @api_view(['POST']) def screen_display(request): if request.method == 'POST': return Response({"success": True, "response": request.data}, status=status.HTTP_200_OK) When I call "http://127.0.0.1:8000/api/send-data/" in my browser, I am getting 405 Method Not Allowed Is this the correct way to do it or am I missing something? Thank you. -
Can we create foreign key without models in Django?
I am using SQL Server database and Django. I have a Database named as Person Database and Other database as Student Database. In Person database I created models, but in Student database there are no models because the tables and data are already existing. So I am getting data of Student database using Pyodbc. Now I am creating a new model in Person database where I need to create a foreign key for student database. Can Anyone help me out how to do it. -
CASE types text and integer cannot be matched
I want the value of the respective field using CASE in Django. The Django query that I have written is as below: Ads.objects.filter(adslot__clients__id__in = clients) .annotate(hour = models.functions.ExtractHour('specific_time')) .annotate(mins = models.functions.ExtractMinute('specific_time')) .annotate(st = Concat('hour', Value(':'),'mins')) .annotate(ad_logic_value = Case(When(specific_time__isnull=False,then="st"),When(no_of_times_per_hr__isnull=False,then="no_of_times_per_hr"), When(after_n_songs__isnull=False,then="after_n_songs"),distinct = True,output_field=models.TextField())).values('ad_logic_value') Unfortunately, When I hit the API on Postman I get the error as below: ProgrammingError at /api/adinformation/ CASE types text and integer cannot be matched LINE 1: ... "core_ads"."no_of_times_per_hr" IS NOT NULL THEN "core_ads"... The Django Model is as followed: class Ads(models.Model): ad = models.ForeignKey('Song') no_of_times_per_hr = models.IntegerField(blank=True, null=True) after_n_songs = models.IntegerField(blank=True, null=True) specific_time = models.TimeField(blank=True, null=True) Can anyone suggest what could be done in order to make this query work? Note: I cannot have two separate fields for ad_logic_values. -
how to implement jwt token in mysql with Django
I create API for android and ios applications in Django with MySQL database. Can anyone help me with how to implement JWT token with MySQL in Django? -
My Django website saying "It works! Python 3.6.8" [closed]
I deployed a Django website on namecheap and it has been running well until yesterday. It started showing me: It works! Python 3.6.8 What could be the cause of this problem. -
TemplateLoader looking for a file using \ instead of /
So as I tried running my django app on a remote linux server, rather than on my local windows machine I encountered this issue: The TemplateLoader is looking in the right folders when it's searching for templates, but always puts '\' instead of '/' when arriving to the file. Let me show you the exact error so that I can make things clearer django.template.loaders.filesystem.Loader: /home/rares/easystorage/store/templates/store\navbar.html (Source does not exist) The path is right up until store\navbar.html and I have no idea why it chooses to use '\' instead of '/'. Also I git cloned the entire project on the linux machine and I can find the file if I search for it in the console. The project runs perfectly fine on the local windows machine. This issue only happens on the new remote linux machine I'm using right now. Below is the templates part of my settings.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR,'templates'), 'store/templates/store' , 'store/templates', ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] and this is the entire TemplateLoader post-mortem: Using engine django: django.template.loaders.filesystem.Loader: /home/rares/easystorage/templates/store\navbar.html (Source does not exist) django.template.loaders.filesystem.Loader: /home/rares/easystorage/store/templates/store/store\navbar.html (Source does not exist) … -
TypeError('context must be a dict rather than Context.',)
I am sending an email from Django using the celery. the email was going out and all of a sudden I started getting below mention error, I am unable to figure out what is cause it. please help out. Thanks in advance. email.py from django.conf import settings from django.core.mail import EmailMessage from django.template import Context from django.template.loader import render_to_string def send_pam_request_email(email, message): c = Context({'email': email, 'message': message}) email_subject = render_to_string( 'pam/email/pam_email_subject.txt', c).replace('\n', '') email_body = render_to_string('pam/email/pam_email_body.txt', c) email = EmailMessage( email_subject, email_body, [settings.DEFAULT_FROM_EMAIL], [email] ) return email.send(fail_silently=False) view.py email = get_approvers_email() messeage_new = """ New Request from {} that needs your attention. url/{}/ """.format(requester,slug) send_new_request_email_task.delay(email, messeage_new) error [2020-06-10 08:34:22,773: INFO/MainProcess] Received task: send_new_request_email_task[ef9dbf20-6074-43e2-94dd-837f096bfeac] [2020-06-10 08:34:22,785: INFO/ForkPoolWorker-7] send_new_request_email_task[ef9dbf20-6074-43e2-94dd-837f096bfeac]: Sent New PAM request email to the approvers [2020-06-10 08:34:22,810: ERROR/ForkPoolWorker-7] Task send_new_request_email_task[ef9dbf20-6074-43e2-94dd-837f096bfeac] raised unexpected: TypeError('context must be a dict rather than Context.',)Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/celery/app/trace.py", line 412, in trace_task R = retval = fun(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/celery/app/trace.py", line 704, in __protected_call__ return self.run(*args, **kwargs) File "/code/web/pam/tasks.py", line 13, in send_new_request_email_task return send_pam_request_email(email, message) File "/code/web/pam/emails.py", line 11, in send_pam_request_email 'pam/email/pam_email_subject.txt', c).replace('\n', '') File "/usr/local/lib/python3.6/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/usr/local/lib/python3.6/site-packages/django/template/backends/django.py", line 59, in render context … -
DRF select_related and prefetch_related doesn't work
I'm try to decrease query counts for using prefetch_related and select_related. However, it seems doesn't work. Also when i delete def get_queryset(self): function, the api still work. I can't find where I'm doing wrong. Models.py class Game(models.Model): name = models.CharField(max_length=255) ... class Match(models.Model): name = models.TextField(blank=False, null=False) game = models.ForeignKey(Game, on_delete=models.SET_NULL, null=True) tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True, blank=True) .... serializers.py class MatchSerializer(serializers.ModelSerializer): class Meta: model = Match fields = '__all__' #exclude = ['participant', ] views.py class MatchDetailAPIView(RetrieveAPIView): serializer_class = MatchSerializer def get_queryset(self): queryset =Match.objects.all().prefetch_related('game_id') return queryset def get_object(self): gameslug = self.kwargs.get('gameslug') slug = self.kwargs.get('slug') # find the user game = Game.objects.get(slug=gameslug) return Match.objects.get(slug=slug, game__slug=game.slug) def get_serilizer_context(self, *args, **kwargs): return {'request': self.request} -
How to stop creation of new File when call save in django?
I am using Django Model like : pickle_embedding_file=models.FileField(upload_to='pickle_embedding/',blank=True,null=True) whenever I call below function: def set_pickle_embeddingFile(self,dict): content = pickle.dumps(dict) fid = ContentFile(content) self.pickle_embedding_file.save(str(self.user_id)+"pickle.pickle",fid) fid.close() It is creating a new file : 68b335fa-6838-4c11-bd2a-32526d9b112dpickle.pickle 68b335fa-6838-4c11-bd2a-32526d9b112dpickle_jHIn3B6.pickle 68b335fa-6838-4c11-bd2a-32526d9b112dpickle_KJ5zBG0.pickle 68b335fa-6838-4c11-bd2a-32526d9b112dpickle_PUepizZ.pickle 68b335fa-6838-4c11-bd2a-32526d9b112dpickle_TREbCvy.pickle I want to override files or want to delete old file how can I do that.