Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I start my server in debug mode for my VS Code Django application?
I'm using Visual studio Code 1.52.1. I want to debug a Django application. I created this launch.json file ... launch.json { "version": "0.2.0", "configurations": [ { "name": "Run Django", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}/app", "remoteRoot": "/usr/src/app" } ], "port": 3500, "host": "127.0.0.1", } ] } and added the sections between "start new section" and "end new section" to my manage.py file ... #!/usr/bin/env python import os import sys if __name__ == '__main__': # start new section from django.conf import settings if settings.DEBUG: if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'): import ptvsd ptvsd.enable_attach(address=('0.0.0.0', 3500)) print('Attached!') # end new section if 'test' in sys.argv: print("test activated!") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "article_project.settings.test") elif os.environ['DJANGO_DEVELOPMENT'] == 'true': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "article_project.settings.dev") else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "article_project.settings.prod") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) However, when I start up my server, I get an error. $ python manage.py runserver Traceback (most recent call last): File "manage.py", line 9, in <module> if settings.DEBUG: File "/Users/davea/Documents/workspace/article_project/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/Users/davea/Documents/workspace/article_project/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 64, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: … -
Django circular import error, trying to allow location to access activity
ImportError: cannot import name 'Activity' from partially initialized module 'vacaplusapi.models.activity' (most likely due to a circular import) (/Users/name/project/server/projectname/models/activity.py) models/activity.py from django.db import models from .activity import Activity class Activity(models.Model): activity = models.OneToOneField(Activity, on_delete=models.CASCADE) description = models.CharField(max_length=255,) date = models.DateField(default="0000-00-00",) photo = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100) models/location.py from vacaplusapi.models import Activity from vacaplusapi.models.vacauser import VacaUser from django.db import models from .vacauser import VacaUser class Location(models.Model): time = models.DateField(models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True)) activity = models.ForeignKey(Activity, on_delete=models.DO_NOTHING, related_name="activity") user = models.ForeignKey(VacaUser, on_delete=models.DO_NOTHING, related_name="vacauser") title = models.CharField(max_length=50) description = models.TextField(max_length=200) photo = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100) -
Best model for storing list of dates | Django
I'd like to store the different launch dates for my Django object for multiple regions, e.g. object 1: US: July 29, 2014 Asia: July 30, 2014 UK: August 1, 2014 I'm not sure what is the best model to use. Is it better to create a different DateField field for each region, or is there a better way to group them all together in a JSON object, or other type? I'll be displaying them together on a page. I'm expecting to run queries to show, for example, all releases in a region, or to display the first release date for that object. Thanks -
Heroku Django cant find template
Despite that I have 'DIRS': [os.path.join(BASE_DIR, 'templates')], in my settings, still Heroku cant find the template. By the way Heroku finds some templates, but it seems that he cant finds those on CBV's. Any idea what might me be problem? Thank you in advance. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 'DIRS': [BASE_DIR / 'templates'], 'DIRS': [os.path.join(BASE_DIR, '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', ], }, }, ] -
Loop through JSON from django model in template
I don't know how to loop thorugh JSON object with javascripit in template (I know how to do it in HTML part but i need it to be in javascript). I figure out that if I safe my JSON object in variable like this: <script> let schedule = "{{ barber.schedule.schedule_day | safe}}" </script> it's saved as string type and I can't work with it, schedule[0] shows first character which is [ I can't JSON.parse it either because error appears "Unexpected token ' in JSON at position 2" i guess it's because my schedule has single quotes insted of dubble ones this is how it my schedule looks when I console.log it [{'start': 8, 'end': 10}, {'start': 12, 'end': 14}, {'start': 15, 'end': 16}] this is how JSON from models looks like { "schedule_day": [ { "start": 8, "end": 10 }, { "start": 12, "end": 14 }, { "start": 15, "end": 16 } ] } views.py class Barber_schedule(DetailView): model = Barber context_object_name = 'barber' models.py schedule_template = ''' { "schedule_day": [ { "start": 8, "end": 16 } ] } ''' class Barber(models.Model): name = models.CharField(max_length=30) start_time = models.IntegerField(default=8, validators=[MaxValueValidator(16), MinValueValidator(0)]) JSON_schedule_template = json.loads(schedule_template) schedule = models.JSONField(default=JSON_schedule_template) photo = models.ImageField(upload_to='barber_avatar', default='default.png') def … -
How to get ajax data in django views?
Here I simply want to get data from ajax call in my django views. I am using type GET ajax call for my purpose. I dont know how to get data from that into my django views.I am newbie please tell me how can i fix all that. <span class="test">yes</span> ajax call <script> /* On focus out on input nickname, call AJAX get request to check if the nickName already exists or not. */ $(".test").focusout(function (e) { e.preventDefault(); // get the nickname var text = $(this).text(); // GET AJAX request console.log('test hoon') console.log(text) $.ajax({ type: 'GET', url: "{% url 'dashboard' %}", data: {"text": text}, success: function (response) { // if not valid user, alert the user }, error: function (response) { console.log(response) } }) }) </script> Views.py class Dashboard(TemplateView): template_name = "dashboard.html" def get(self,*args, **kwargs): amount = self.request.GET.get('text') print("I m here !",amount) return render(amount,'dashboard.html',) -
How to read images uploaded via post request using opencv
I have an opencv script on document scanner and I want to create a post request that returns the scanned image as a response. I get the below error when I tried to read the image(using opencv) via post request. What are the possible way I can get around this. I have tried the various method but is not working for me. Modey.py class ImageScanner(models.Model): name= models.CharField(max_length=500) date = models.DateTimeField(auto_now_add=True) ImageFile = models.FileField(upload_to=upload_to) def __str__(self): return self.name + ": " + str(self.ImageFile) def save(self, *args, **kwargs): super(ImageScanner, self).save(*args, **kwargs) Img = Scanner(self.ImageFile) Opencv script def Scanner(image): # now = timezone.now() # load the image and compute the ratio of the old height # to the new height, clone it, and resize it image = cv2.imread(image) ratio = image.shape[0] / 500.0 orig = image.copy() image = imutils.resize(image, height = 500) # convert the image to grayscale, blur it, and find edges # in the image gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (5, 5), 0) edged = cv2.Canny(gray, 75, 200) # show the original image and the edge detected image print ("STEP 1: Edge Detection") cv2.imshow("Image", image) cv2.imshow("Edged", edged) seriliazer.py from rest_framework import serializers from .models import ImageScanner from django.contrib.auth.models import … -
Case 1: Convert following UnitTest Code into PyTest:
How to convert following unitest code into a pytest code class ModelTests(TestCase): def test_create_user_with_email_successful(self): """Test creating a new user with an email is successful""" email = "test@londonappdev.com" password = "Password123" user = get_user_model().objects.create_user(email=email, password=password) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) def test_new_user_email_normalized(self): """Normalize Email""" email = "teast@AIOWoev.com" password = "Password123" user = get_user_model().objects.create_user(email=email, password=password) self.assertEqual(user.email, email.lower()) def test_new_user_invalid_email(self): """Creating user with no email fails""" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, "test123") I have written following tests into a pytest but has issue with test_new_user_invalid_email, how to correct it: def test_create_user_with_email_successful(client) -> None: email = "test@londonappdev.com" password = "Password123" user = get_user_model().objects.create_user(email=email, password=password) assert user.email == email assert user.check_password(password) def test_new_user_email_normalized(self): """Normalize Email""" email = "teast@AIOWoev.com" password = "Password123" user = get_user_model().objects.create_user(email=email, password=password) assert user.email == email.lower() def test_new_user_invalid_email(self): """Creating user with no email fails""" with pytest.raises(ValueError) as e: get_user_model().objects.create_user(None, "test123") -
Django redirecting after clicking Like button
I'm doing Like/Unlike system in my project. After clicking Like button should just redirect on the same page but updated with +1 like but it is not. Have looked on youtube videos with this system and thay got it worked but I can't figure it out what is the problem with my code. views.py def like_view(request, pk): cocktail = get_object_or_404(AddCocktails, id=request.POST.get('cocktail_id')) liked = False if cocktail.likes.filter(id=request.user.id).exists(): cocktail.likes.remove(request.user) liked = False else: cocktail.likesadd(request.user) liked = True return HttpResponseRedirect(reverse('cocktails:cocktail-details', args=[str(pk)])) class CocktailDetails(LoginRequiredMixin, DetailView): model = AddCocktails template_name = 'cocktails/cocktail-details.html' def get_context_data(self, *args, **kwargs): cocktail_data = AddCocktails.objects.filter(id=self.kwargs['pk']) context = super().get_context_data(**kwargs) stuff = get_object_or_404(AddCocktails, id=self.kwargs['pk']) total_likes = stuff.total_likes liked = False if stuff.likes.filter(id=self.request.user.id).exists(): liked = True context['cocktail_data'] = cocktail_data context['total_likes'] = total_likes context['liked'] = liked return context urls.py path('cocktail-details/<int:pk>/', CocktailDetails.as_view(), name='cocktail-details'), path('likes/<int:pk>/', like_view, name='likes'), template {% for cocktail in cocktail_data %} <h4>Cocktail Name</h4> {{ cocktail.cocktail_name }} <h4>Cocktail Category</h4> {{ cocktail.cocktails_category }} <h4>Type of Glass</h4> {{ cocktail.crockery_category }} <h4>Method Category</h4> {{ cocktail.method_category }} <h4>Ingredients</h4> {{ cocktail.ingredients }} <h4>Execution</h4> {{ cocktail.execution }} <img src="{{ cocktail.image.url }}" width="350" height="350"> <form action="{% url 'cocktails:likes' cocktail.pk %}" method=POST> {% csrf_token %} {% if liked %} <button type="submit" name="cocktail.id" value="{{ cocktail.id }}" class="btn unlike">Unlike </button> {% else %} <button type="submit" … -
Django Get Root Path From Current URL
I am developing a Django website using the Wagtail CMS. I have a navbar at the top of the page where using template tags, it loops through pages in the navigation variable. {% for item in navigation.menu_items.all %} <a class="nav-link {% if request.get_full_path == item.link %}active{% endif %}" href="{{ item.link }}" {% if item.open_in_new_tab %} target="_blank"{% endif %}>{{ item.title }}</a> {% endfor %} Say that the URL is http://localhost:8000/blog/ and the page URL is the same, then the active class is applied to that iteration. The problem arises when I am on a page with the URL such as http://localhost:8000/blog/example-blog-post/, this does not match with http://localhost:8000/blog/ and the active class is not applied, even though I am in the blog. Is there a way to strip the URL and only keeping the root path, so http://localhost:8000/blog/example-blog-post/ becomes http://localhost:8000/blog/ so that the active class can be applied to subpages in the directory? -
How to access user infos from consumer.py django?
I am building a social media app with react.js and django, django-rest-framework, djoser, django-channels==3.0.2.. well the problem is i want to make an notification system on friend request and on like of post and comment. The problem is I want to have some kind of security that when I send a request through the websocket from react, I want to check if the sender is the authenticated user,by sending the user id on the websockets, and comparing it to the logged in user's id.Since I can't get the self.scope['user'] because i'm using Djoser for authentication, is there any other way to achieve this ? -
bootstrap table: filter control not working
With my bootstrap table I want to use the extension Filter Control Server side I'm using django. I include following css and js: {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.18.1/bootstrap-table.min.css"/> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.18.1/extensions/filter-control/bootstrap-table-filter-control.min.css"> <script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.18.1/bootstrap-table.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.18.1/extensions/filter-control/bootstrap-table-filter-control.min.js" ></script> And here my html table: <table id="table" data-toggle="table" data-pagination="true" data-pagination-h-align="left" data-pagination-detail-h-align="right" data-page-size="25" data-page-list="[10, 25, 50, 100, all]" data-search="true" data-show-columns="true" data-filter-control="true" data-show-search-clear-button="true" data-show-refresh="true" data-url="../get_track_list"> <thead> <tr> <th data-field="datetime_start" data-formatter="DateFormatter" data-sortable="true" data-switchable="false" data-searchable="false">Date</th> <th data-field="name" data-formatter="ActivityLinkFormatter" data-switchable="false">Name</th> <th data-field="sport" data-formatter="SportSymbolFormatter" data-sortable="true" data-searchable="false" data-filter-control="select">Sport</th> </tr> </thead> </table> My data-url is a json file from a django request. The resulting table looks like this: I don't have any errors in the browser console. I also see the the filter-control div was created but not the dropdown field? What I'm doing wrong, so that the data-filter-control="select" field is not created? The table is rendered without using any js functions, in my js file are just the custom data-formatter -
Missing DataDog metrics when using ThreadStats for a Celery task in Django
The problem I have a scheduled Celery task that queries x number of rows, does some processing and upon success (or error) it increments a specific metric using ThreadStats. For each execution of this task, the metric should be incremented by x at a specific time. The problem is that some of these increments are not posted to DataDog. Ex. if the total number of rows is 100 and the task processes x=10 at a time, some of those task executions fails to increment the metric and it ends up displaying only 60. Attempts for resolution This is what I tried to do without success: Manually flushing the metrics in the task by setting flush_in_thread=False and calling the flush() method. Using dogstatsd-collector library to delay the submission -
Permission denied: '/app/manage.py' Docker
I'm having a permissions issue when trying to run my docker-compose command docker-compose run app sh -c "django-admin.py startproject app ." ERROR: PermissionError: [Errno 13] Permission denied: '/app/manage.py' I've done some research and found a similar issue here: docker-compose , PermissionError: [Errno 13] Permission denied: '/manage.py' However I think I'm doing something wrong when trying to change permissions in my Dockerfile Dockerfile: FROM python:3.8-alpine MAINTAINER Nick ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user RUN chown user:user -R /app/ RUN chmod +x /app USER user I add RUN chown user:user -R /app/ and RUN chmod +x /app running docker build . works succesfully however I still keep getting permissions issue docker-compose.yml version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app /app command: > sh -c "python manage.py runserver 0.0.0.0:8000" -
django-admin command can't be run because files are not in the right place
So I thought I installed anaconda and Django correctly but I guess I didn't because my django-admin commands don't work. As you can see here, I have the file paths for a couple Django files all screwed up: /Users/user/anaconda3/bin/django-admin /Users/user/anaconda3/bin/django-admin.py /Users/user/anaconda3/lib/python3.8/site-packages/Django-3.1.5.dist-info/* /Users/user/anaconda3/lib/python3.8/site-packages/django/* This makes it so I can't run any django-admin commands that I need to run to start a new project in PyCharm. -
Geodjango + PostGIS. Aggregate polygon area in square meters
I am using geodjango(3.1) + postgis and I want to receive the area of a polygon in square meteres. Therefore, I am using the Geographic Database Functions of Django. My code looks the following: City.objects.annotate(area=Area('geom')) I think the result I am reciving is in degree. When I use the distance function the same way, I get the right result in square meters. When I am executing ST_Area(geom, use_spheroid=true) as RawSQL, the result also fits and is in square meteres but I would like the avoid RawSQL. Thanks for any help =) -
Python Django Regex: multiple optional arguments
I use Django DRF @action decorator to create a search API view. I would like to match all these url and capture parameters: # 'my_search' captured in search_terms var http://127.0.0.1:8000/api/medias/search/my_search/ # 'my_search' captured in search_terms var, and '1' captured in tags_id var http://127.0.0.1:8000/api/medias/search/my_search/tags/1/ # 'my_search' captured in search_terms var, and '1/2/' captured in tags_id var (or a list like [1,2]) http://127.0.0.1:8000/api/medias/search/my_search/tags/1/2/ I actually have this code/regex, but that match only url with tags. @action(detail=False, methods=['get'], url_path=r'search/(?P<search_terms>[^/]+)/tags/(?P<tags_id>[\d/]+)', url_name='search') def search(self, request, search_terms, tags_id): ... If someone have an idea it will be great. -
How to use Bootstrap-Tooltips for each list item in Django_filters queryset result
I have a template matches.html that displays the Django_filters queryset result from dropdown choices. I cannot seem to figure out how to make Bootstrap-Tooltip work in this instance, and I have not found many examples or documentation to help. matches.html displays Django_filters Queryset results from startSearch template: <div class="row"> {% for animal in filter.qs %} #Queryset <div class="col-md-6 col-lg-4"> <div class="card rounded-0 card-hover-overlay"> <div class="position-relative" style="background-image:url('{{ animal.profilePic.url }}')"> <img class="card-img rounded-0" src="{{ animal.profilePic.url }}" alt=""> </div> <div class="card-img-overlay"> <h3><a href="{% url 'animals:animalDetail_view' animal.id %}">{{ animal.name }}</a></h3> <p class="text-white">{{ animal.tagLine }}</p> </div> <div class="card-footer bg-transparent"> <ul class="list-unstyled d-flex mb-0 py-2"> #for each list item, use Bootstrap-Tooltip <li><button class="btn-like px-2" data-toggle="tooltip" data-placement="top" title data-original-title="Favorite this listing"> <i class="fas fa-heart text-primary" aria-hidden="true"></i> <span>{{animal.favs}}</span> </button> </li> <li class="ml-auto"> <a class="px-2" href="{% url 'animals:animalDetail_view' animal.id %}">More Details</a> </li> </ul> </div> </div> </div> {% endfor %} <script> $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip(); }) </script> -
What does AWS_S3_MAX_MEMORY_SIZE do in django-storages
According to the documentation AWS_S3_MAX_MEMORY_SIZE(optional; default is 0 do not roll over) The maximum amount of memory (in bytes) a file can take up before being rolled over into a temporary file on disk. Can someone explain this a bit more? Is this a way I could throttle upload sizes? What does "being rolled over" refer to? Thank you -
Cannot run django-admin commands because files are located in anaconda3 folder?
So I thought I installed anaconda and Django correctly but I guess I didn't because my django-admin commands don't work. As you can see here, I have the file paths for a couple Django files all screwed up: /Users/user/anaconda3/bin/django-admin /Users/user/anaconda3/bin/django-admin.py /Users/user/anaconda3/lib/python3.8/site-packages/Django-3.1.5.dist-info/* /Users/user/anaconda3/lib/python3.8/site-packages/django/* This makes it so I can't run any django-admin commands that I need to run to start a new project in PyCharm. I'm a total noob so I'm sorry if this is a simple question. Thank you! -
Django REST framework: SearchFilter doesn't work with 2 and more values in search bar if they are from the same field
I use SearchFilter to search for therapists: class TherapistSearchListAPIView(generics.ListAPIView): permission_classes = [IsAuthenticated] search_fields = ['first_name', 'therapist_profile__skills__title', 'therapist_profile__counselling_areas__title'] filter_backends = [filters.SearchFilter] queryset = Therapist.objects.all() serializer_class = TherapistSearchSerializer Generally It works great, but there is a problem: When several values are entered in search bar, if among these values 2 or more values are from the same field, even though the request matches with any of therapists, the search returns NULL. Example: Therapist: [ { "first_name": "Thomas", "skills": [ { "id": "0658374347844fd7b69b3d033e17f9b1", "title": "Self-reflection" }, { "id": "2c6ab46d4ebb4cb1a46c934f0c30ebbe", "title": "Patience" }, { "id": "f22c8210dd4d4a3299ea8887c1da7c30", "title": "Flexibility" } ], "counselling_areas": [ { "id": "5fb0c57ced4c41129829b3620076dda4", "title": "Body dysmorphic disorder" } ] ] If I write in search bar "Thomas self-reflection patience", it will return me NULL even though everything matches with the therapist in database. How can I fix this? Is there any solution or I need to write my own search filtering function from the scratch? -
django not displaying error_messages in forms
i am new to django and i have this form i am working on i have tried everything possible i cant seem to display the form error messages. i have tried using a def clean method nothing happens when i try to submit an empty form..i have tired switing to using FormView i have also tried using function view i have tried using a for loop and adding {{ form.non_field_errors }} in my template nothing pops up. my app/forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField( label='Your Name', min_length=2, max_length=25, required=True, error_messages ={'required':'Please tell Oluwafemi your name'}) email = forms.EmailField(label='Your Email', required=True, error_messages={'invalid':'Please fill in a valid email'}) subject = forms.CharField(label='Subject', min_length=4, max_length=100, required=True) message = forms.CharField(widget=forms.Textarea(attrs={'placeholder':'Write Oluwafemi a Message'}), error_messages ={'required':'Please write something for Oluwafemi'}) my app/views.py from django.views.generic import TemplateView from django.shortcuts import render from django.core.mail import send_mail from .forms import ContactForm from django.http import HttpResponseRedirect # Create your views here. class ProfilePageView(TemplateView): template_name = 'femi_profile.html' form_class = ContactForm success_url = 'femiir' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] subject = form.cleaned_data['subject'] message = … -
Mock a method that raise an exception a number of times
I have looked for how to do this all day, without luck. I'm using Django 1.11 and Python 2.7 (no possibility to upgrade). I have a method that calls an external API. This API sometimes fails with 504 or 502 errors. So, we decide to, in that case, retrieve the call some times (3 times for now). So, I wrote something like this. def call_external_api(arg_1, arg_2): attempts = 3 data = None ext_api = ExternalAPI() # wrapper class, its method call the external api while attempts > 0: try: data = ext_api.get_data_details(arg_1=arg_1, arg_2=arg_2) except Exception as exception: attempts -= 1 log_message(exception) raise ExternalAPIError('Error calling EXT-API: %s' % str(exception)) return data So, I want to test this, but I do not know how to mock the exception. I know that it is possible to use @patch(SomeClass, 'method_name') to simulate the call to another class, but how to simulate the exception, so the code enters on the except branch and reduces "attempt," repeating the cycle? Notes: I thought that if I can mock the exception, I could test that log_message was called 3 times. What do you think about this approach? -
How do I use filter search table in my Django project
How do I go about assertationError when using django-filter in my Django project assertationError:setting 'Meta.model' without either 'Meta.fields' or 'Meta.exclude' has been deprecated. -
How to save Audio file to django model from the server itself with REST API
I am: Sending .wav file with API Class Converting to .mp3 with pydub Saving converted file to MEDIA_ROOT I want: Save the converted file (.mp3) to my model. I have: AWS S3 bucket on production, everything saved in my models lands there. I have model with FileField: def content_file_name(instance, filename): filename = "{}_".format(today.strftime("%y-%d-%m")) + filename return os.path.join('content', "{}".format(instance.user.email), 'tracks', filename) class Track(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True ) # ... file = models.FileField( upload_to=content_file_name, null=True, blank=True) I am using MultiPartParser and audio gets saved correctly but the original one in .wav. I want to save mp3 once I convert it. from django.core.files.storage import FileSystemStorage class TrackAPIView(UpdateAPIView): serializer_class = FileSerializer permission_classes = (permissions.IsAuthenticated,) parser_classes = [MultiPartParser, ] queryset = Track.objects.all() lookup_field = 'uid' def put(self, request, *args, **kwargs): file_obj = request.data # Using File storage to save file for future converting fs = FileSystemStorage() file_name = fs.save(audio_file.name, audio_file) audio_file_url = fs.url(file_name) # Preparing paths for convertion upstream = os.path.dirname(os.path.dirname(os.path.dirname( os.path.abspath(__file__)))) path = os.path.join(upstream, 'media', audio_file.name) mp3_filename = '.'.join([audio_file.name.split('.')[0], 'mp3']) new_path = os.path.join( upstream, 'media', mp3_filename) # Converting to mp3 here wma_version = AudioSegment.from_file(path, "wav") wma_version.export(new_path, format="mp3") user_id = self.request.user.id # I was trying to create a Track instance, the mp3 …