Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Got AttributeError when attempting to get a value for field `author` on serializer `CommentViewSerializer`
Here is the serializers.py class CommentViewSerializer(serializers.ModelSerializer): author = UserViewSerializer() class Meta: model = Comment fields = ('author','content','article') def create(self, validated_data): return Comment.objects.create(**validated_data) Here is the models.py class Comment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='articlefda') author = models.ManyToManyField(User,unique=False, related_name='articsles') parent = models.ForeignKey('self', null=True, blank=True,on_delete=models.CASCADE, related_name='replies') content = models.CharField(max_length=100) timestamp = models.DateTimeField(auto_now=True) why do i keep getting the error?There is no typo or something. Got AttributeError when attempting to get a value for field `author` on serializer `CommentViewSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no attribute 'author'. -
Django: Passing parameter to a URL pattern name inside views
In the example below, I'm trying to use the URL pattern name (ie, 'update_profile') instead of the absolute path (/profile/str:pk/update) in one of my views. This way if I later change my url path, I don't have to go an change each time I used the absolute path. My question: how do I pass 'pk' into a pattern name? I've tried things like: success_url = 'update_profile' % (pk) But that doesn't seem to work. urls.py path('/profile/<str:pk>/update', views.ProfileUpdateView.as_view(), name='update_profile'), views.py def submit_profile_form(request, pk): if request.method == "POST": success_url = 'update_profile' // <------ How do I pass 'pk' in here? ... return redirect(success_url) Thanks for your help! -
Can we upload a django project on cpanel and run it if the cpanel doesnt have a terminal?
I got the basic hosting plan from godaddy. Most tutorials on youtube are trash. So can we use a cpanel which doesn't have terminal to run a django project? and should we include the venv folder while we upload? -
Django NoReverseMatch at http://127.0.0.1:8000/boards/1/new/
This is my site urls: from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('boards.urls')) ] And this is my app urls: urlpatterns = [ path('',views.home,name='home'), path('boards/<int:pk>',views.board_topic,name='board_topic'), path('boards/<int:pk>/new/',views.new,name='new_topic') ] This is the Views for app: from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse,Http404 from .models import Board # Create your views here. def home(request): board = Board.objects.all() return render(request,'home.html',{ 'board':board, }) def board_topic(request,pk): # try: # board = Board.objects.get(pk=pk) # except: # raise Http404 board = get_object_or_404(Board,pk=pk) return render(request,'topics.html',{ 'board':board }) def new(request,pk): boards = get_object_or_404(Board, pk=pk) return render(request, 'new_topic.html', { 'board' : boards }) when I try to go to http://127.0.0.1:8000/boards/1/new/ then this error occurs: enter image description here please help me. -
Wagtail set default page explorer view location for PageChooserBlock in admin
Way to browse pages from particular location in PageChooserBlock, like browse "sub pages or same level pages" from current editing page in which this block is used. I observed that when any page is selected in PageChooserBlock then browsing starts from the same current selected page. I wanted to start default browsing from current edting page (in which this PageChooserBlock block is used) if no page is already selected. Is there any way to do it? I googled for some way or direction for doing it but no success. I also checked chooser hook but there is no way to get current editing page in this hook. So can't use it. Also tried to search in source code of PageChooserBlock for such possibility but no success for me or may be I missed the possible way. Your help is appreciated. -
Django Model Creating with Verbose Name
When creating a model object, can you use the verbose name to create? I have a model that has a dot in the name and I cannot have dot in a variable name. -
access Task attributes in comment CreateView(form) in Django
Good evening! I need a little help... Again :) I have two classes in my models.py (same app) Tasks and Comments, in order to create a comment I made a Class in views.py CreateView, is a built in form that django creates... Well when I send the user to comment_form to create a new comment I would like to have the task info in that page... Something like: {{user.username}} you're about to comment in {{task.title}} - {{task.content}} {{form}} The problem is that I can not access task.title, task.content and for that matters not even user.username variables in that form... I went through the docs and couldn't find a solution not even a clue on how to think to solve that. Models.py: class Task(models.Model): title = models.CharField(max_length=50) content = models.TextField(blank=True) date_created = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, default=User) responsable = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name="author", default=author) STATUS_CHOICES = [('D', 'Done'),('P','Doing'),('N','Not done')] Status = models.CharField(max_length=1,choices=STATUS_CHOICES, default='N') IMPORTANCE_CHOICES = [('H', 'High'),('M','Medium'),('L','Low')] importance = models.CharField(max_length=1,choices=IMPORTANCE_CHOICES, default='M') DEPARTAMENT_CHOICES = [('D', 'Dev'),('M','Marketing'),('H','HR'),('L','Legal'),('F','Finances'),('O','Others')] departament = models.CharField(max_length=1,choices=DEPARTAMENT_CHOICES, default='M') is_public = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("task-detail", kwargs={"pk": self.pk}) class Comment(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, default=User) body … -
Paginating FormView
My goal is to create a mixin that would take care of paginating both ListView and FormView that has a list of FormSets in the template. While ListView part is mostly straight forward, I'm having hard times trying to paginate created formsets. Is there any clever way to include pagination inside generic views? All tips and any contribution will be highly appreciated! -
how to run docker-compose up . i get this ERROR: ""Top level object in './docker-compose.yml' needs to be an object not '<class 'NoneType'>'.""
I using python 3.8, Docker version 19.03.13, build 4484c46d9d 3.8 version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 -
Serve multiple web requests in Django
I am using Django with Nginx and want to serve multiple requests in parallel. We have Docker configuration and one pod has 10 cores. I am trying to create multiple workers in uWSGI like (uwsgi --socket /tmp/main.sock --module main.wsgi --enable-threads --master --processes=10 --threads=1 --chmod-socket=666) Request first lands to view and from there it calls service file which does heavy work. Actually, I am using openCV library in service file which has loop over all pixels to remove colored ones(pretty time consuming..) I also tried using multiple cores and 1 worker as (uwsgi --socket /tmp/main.sock --module main.wsgi --enable-threads --master --processes=1 --threads=10 --chmod-socket=666). But still performance did not improve. I think it is due to GIL which is getting acquired while doing heavy I/O operations, not sure how I can find a work around it. Or use all cores in some other efficient way? TIA! -
Django Celery Beat for periodic task in Django with Celery is not working
I wanted to add celery to my django project. But somehow it does not seem to work as expected although I followed the steps in the official documentation. Here are the parts of my Django project: # celery.py import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookProjectSetting.settings') app = Celery('bookProjectSetting') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() app.conf.beat_schedule = { 'update-lifetime': { 'task': 'tasks.update_life_time_of_books', 'schedule': crontab(minute='*/5'), }, } Then the init file: # __init__.py from .celery import app as celery_app __all__ = ('celery_app',) Now, in my app folder( called books), the tasks.py looks like follows: from books.models import Book from celery import shared_task @shared_task def update_life_time_of_books(): # Query all the books in our database print("Query all books.") books = Book.objects.all() # do sth. with books. for the sake of brevity I do not show this In my settings.py file I have this for celery: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_TIMEZONE = 'Europe/Berlin' # ... bla bla INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_celery_beat', 'rest_framework', 'books', ] I started the redis server in a second tab via the redis-server command so that it can take the part as a broker. I … -
Python Executing SQL fails over due to non existing field in json data
I am getting some JSON data from a third party API. I am trying to add that data into my own database to be used for a website. I loop through each record in the JSON and execute a SQL query to insert that data into my database. However some records in the JSON data doesn't exist, and therefore causes my query to fail. I have set defaults for these fields for this reason however it still falls over. isNonFoilOnly field will only appear in some of of the records in the JSON data. models.py class Set(models.Model): code = models.CharField(max_length=100, unique=True) keyrune_code = models.CharField(max_length=100) name = models.CharField(max_length=100) type = models.CharField(max_length=100) release_date = models.DateField() base_set_size = models.IntegerField() total_set_size = models.IntegerField() is_online_only = models.BooleanField(default=False) is_non_foil_only = models.BooleanField(default=False) is_foil_only = models.BooleanField(default=False) sale_status = models.BooleanField(default=False) def __str__(self): return self.name views.py response = requests.request("GET", "https://mtgjson.com/api/v5/SetList.json") data = response.json()["data"] sorted_obj = sorted(data, key=lambda k: k['releaseDate'], reverse=False) sql = """ INSERT INTO dashboard_set (code, keyrune_code, name, type, release_date, base_set_size, total_set_size, is_online_only, is_non_foil_only, is_foil_only, sale_status) VALUES ( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s ) ON CONFLICT (code) DO UPDATE SET keyrune_code = %s, name = %s, type = %s, release_date = %s, base_set_size … -
Exists check takes forever in Django SQLite
I am running a webservice where a user sends a word as a request, and I use that word to filter entries in my database (the default Django SQLite). The relationship word-to-entry is one-to-one. That means there are two possible cases: The word exists in the database -> Return the associated Entry. The word doesn't exist -> Throw exception. The following lookup should then return a QuerySet with 1 or 0 objects: Entry.objects.filter(word__iexact=word) Expected Behavior: Cases 1 and 2 do not differ perceptibly in speed. Current Behavior: Case 1 takes at most half a second. Case 2 takes forever, around 1-2 minutes. I find this puzzling. If an existing word can be looked up regardless of where it is in the database, then why does case 2 take forever? I am not a django or database expert, so I feel like I'm missing something here. Is it worth just setting up a different type of database to see if that helps? Here is the relevant portion of my code. I'm defining a helper function that gets called from a view: mysite/myapp/utils.py from .models import Entry def get_entry(word): if Entry.objects.filter(word__iexact=word).exists(): entry = Entry.objects.filter( word__iexact=word ) # Case insensitive exact lookup return … -
Multiple user types with multiple authectication methods in Django
How can i create multiple user types with multiple authentication method. Consider the following scenario. User Types: Admin, Staff, User, Writer, Business Admin and Staff types are need to authenticate with company email address and password Staff and Writer types are need to authenticate only with phone number. (no password) Business type is need to authenticate with email(any) and password. How can I create Django models, according to above example. -
ValueError could not convert string to float: ''
I'm having my app on heroku. I use timeme js to record user's active time spend on the page, and use a hidden form to store the value into the database. Additionally, I'm using otree package to write my app. The following is the code I use: models.py class Active(ExtraModel): active_duration = models.FloatField() active_record = models.LongStringField() views.py/pages.py in otree class intro_instructions(Page): def before_next_page(self): data = self.form.data p = self.player active = Active.objects.create(active_duration=data['active_duration'], active_record=data['active_record']) active.save() html <form method="post" role="form" id="form" autocomplete="off">{% csrf_token %} <input type="text" name="active_record" id="id_active_record" style="display: none" > <input type="number" step='any' name="active_duration" id="id_active_duration" style="display: none"> </form> The error ValueError could not convert string to float: '' { "csrfmiddlewaretoken": "vVhVRLrAUokmiNGRpzCaP78bnTOQyowf5VMfIDgKGglWGuEyQAU2wooWjQzXuBgD", "active_duration": "", "active_record": "" } Is it because active_duration is empty? Will it help if I set blank=true, null=true for the forms? I was assuming that every use would have value for the input. Also any ideas about why the input is empty? Could it be that the user used scripts to skip the page without visible fields? From the sentry error message, this happened to one user twice. -
Is it possible to use rows of one table as columns of other in django?
I am creating a quiz in Django where we add questions in one table and options in another table (using foreign key to link it to a question). I want to create a new table named Quiz which will store user input for each questions. I mean if I add four questions in Question table, having three Options objects each one, then quiz table has three columns which will store user input of each question. Quesions table : columns = ('id', 'question') rows = {(1, 'What is your name'), (2, 'Where do you live)} Choices table : Columns = ('id', 'choice', 'Question id(foreign key)') Rows = { ('1',"ram", QID-1,), ('2',"Sham", QID-1,), ('3',"India", QID-2,), ('4',"USA", QID-2,) } Quiz table (I want) : Columns = ('quizID', 'QID-1','QID-2') Rows = {('1', 'ChoiceID-1', 'ChoiceID-4'), ('2', 'ChoiceID-2', 'ChoiceID-4')} The idea is shown in the example...However, I don't find any other way than creating quiz columns manually for each question. I am trying to do this in Django. Kindly help me. or let me know if you have another idea to do the same thing. -
How to make a piece-by-piece decrease of an item from the cart
In template has a basket with arrows for adding and removing items. Adding made like this Template: <a href="{% url 'add' %}?new={{order.book.id}}" > Views def add(request): book = str(request.GET.get("new")) user = request.user order = Orders.objects.create(user = user, order_book = Book.objects.get(id=book)) order.save() return redirect("cart") And how to make a decrease by one element? This is how the cart view looks like: def cart(request): book_list = Orders.objects.filter(user = request.user) array = [b.order_book.id for b in book_list] array_price = sum([b.order_book.price for b in book_list]) result = {i: array.count(i) for i in array} ordered_list = [] for i in result: book = Book.objects.get(id = i) count = result[i] order = {'book': book, 'count':count, "price":book.price * count} ordered_list.append(order) """ Подсчет """ user = request.user order_list = Orders.objects.filter(user = user) count = len(order_list) context = {'ordered_list':ordered_list, "count":count, "price_total":price_total} return render(request, 'main/cart.html', context) Models.py: class Orders(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'users') order_book = models.ForeignKey(Book, on_delete=models.CASCADE) def __str__(self): return f'User {self.user} buy {self.order_book.title}' I tried to do this: def del_item(request): book = str(request.GET.get("new)) user = request.user del_book = Orders.objects.filter(user = user, order_book = Book.objects.get(id=book)) del_book.delete() return redirect("cart") But this removes all of the user's orders cleanly. It is also a useful function, but how can you do … -
Django ManyToMany intermediary through table & constraints for product watchlists
I want to implement multiple "watchlists" that each user can add products into. A basic reproduction of the tables I currently have is as follows: class Product(models.Model): name = models.CharField(blank=False, null=False, unique=True, default=None, max_length=100) sku = models.CharField(blank=False, null=False, unique=True, default=None, max_length=100, verbose_name='Stock Keeping Unit') description = models.TextField(blank=True) price = models.FloatField(blank=True) class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) display_name = models.CharField(max_length=30) subscription = models.CharField(null=False, blank=False, choices=SubscriptionChoices.choices, default=SubscriptionChoices.SILVER, max_length=100) watchlists = models.ManyToManyField(Product, through='Watchlist') class Watchlist(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) name = models.CharField(null=False, blank=False, max_length=20, default='WatchList1') As it can be seen above, I have chosen to use an intermediary 'through' table called Watchlist. I did so because I wanted to able to allow the user to rename the watchlist as they please, hence I included a field called name in the Watchlist table. I also have 3 levels of subscription that the user can have: Silver, Gold & Platinum. How do I do the following: Limit the number of watchlists to 2/5/10 depending on subscription level of user (2:Silver, 5: Gold etc). Limit the number of products in a watchlist to 10/20/30 again depending on subscription level of user. Add/remove products into a particular watchlist of a particular user. … -
Django Rest Framework: Serialize an Array in a multipart/form-data request
I am trying to send a List / array using multipart/form-data. The ModelSerializerdefines that field using class RequestSerializer(serializers.ModelSerializer): # ... in_categories = serializers.PrimaryKeyRelatedField(many=True, read_only=True) the Model field is defined as class Request(models.Model): # .... in_categories = models.ManyToManyField(to='Category', through='RequestToCategory', blank=False) now, I got a ModelViewSet defined as follows: class RequestViewSet(viewsets.ModelViewSet): # ... def create(self, request, *args, **kwargs): print(request.data) serializer = self.get_serializer(data=request.data) print(serializer.is_valid(raise_exception=True)) print(serializer.validated_data) However, the in_categories field never gets populated with actual data, nor does the validator raise an exception when called. I did not find any way to transmit the data in a way the field actually gets a list of keys as defined. I tried three things: Sending the data as literal resulting in request.data = <QueryDict: { ... 'in_categories': ['[2, 3]'] ... Sending the data as array resulting in request.data = <QueryDict: { ... 'in_categories[0]': ['2'], in_categories[1]': ['3'] ... Sending the data as array with extra key resulting in request.data = <QueryDict: { ... 'in_categories[0]id': ['2'], in_categories[1]id': ['3'] ... Each solution (i) arrives at the ViewSet, (ii) validates correctly but does (iii) not reflect into serializer.validated_data. Do I miss something? I spent already hours on this, finding no solution on how to make DRF understand what I want. -
admin Panel: TypeError: expected str, bytes or os.PathLike object, not list
I'm getting this error while trying to upload a picture in http://127.0.0.1:8000/admin/: TypeError: expected str, bytes or os.PathLike object, not list [23/Oct/2020 12:15:22] "POST /admin/store/category/4/change/ HTTP/1.1" 500 166634 I'm using MacOS 10.15.7 Python 3.9 Django 3.1.2 pandas 1.1.3 from django.db import models class Category(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='category', blank=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='product', blank=True) stock = models.IntegerField available = models.BooleanField(default=True) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) Do you have any idea how to solve it? Thanks -
Django multilanguage: language switcher does not respect prefix_default_language=False
I'm trying to implement a language switcher in a website with 2 languages. I use prefix_default_language=False in order to have English in the root domain without the subfolder /en/. The problem is that when I try to make a language switcher like it's explained in Django docs, it redirects me to /en/ which is also working. I just want en to be in the root without any subfolder as it is the default language. This is what I've done: Settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # Middleware for translations 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # Default language LANGUAGE_CODE = 'en-us' # Languages supported by translation LANGUAGES = [ ('en', ('English')), ('es', ('Spanish')), ] TIME_ZONE = 'UTC' # Enable translations USE_I18N = True USE_L10N = True USE_TZ = True # Directory for translations LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale') ] urls.py from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView from django.conf.urls.i18n import i18n_patterns from django.utils.translation import gettext_lazy as _ urlpatterns = [ # endpoint for the language switcher path('i18n/', include('django.conf.urls.i18n')), # Robots.txt file path('robots.txt', TemplateView.as_view(template_name="core/robots.txt", content_type='text/plain')), ] urlpatterns += i18n_patterns( path(_('admin/'), admin.site.urls), path('blog/', include('blog.urls')), path('', include('staticpages.urls')), # Hide language prefix in URLs for default language … -
Postgres optional array parameter in Django raw sql
So I've used this question to create optional parameters in my Django raw_sql snippet: select da.data_date, hll_union_agg(dau.users) users_union from sales_dailyaggregationusers dau join sales_dailyaggregation da ON da.id = dau.daily_aggregation_id where outlet_id in %(outlet_ids)s and currency = %(currency)s and (%(transaction_channels)s is NULL or transaction_channel in %(transaction_channels)s) and (%(transaction_types)s is NULL or transaction_types && %(transaction_types)s) However, Django gives the following error: django.db.utils.ProgrammingError: syntax error at or near "NULL" LINE 11: ... and (NULL is null or transaction_channel in NULL) So it looks like it's processing the entire query and deciding that it's badly formed (even though Postgres would optimize away the second half of the code). Is there a way around this? -
Django templates render newline as \n instead of <br>
I'm generating an XML file using Django template language and I came across a problem with linebreaks. I'm trying to render textarea but I need to keep newlines - \n because the facebook catalogue feed accepts only \n as a newline. I can't figure out how to make it work. linebreaks filter doesn't work. Also |safe doesn't seem to work. <description><![CDATA[{{ object.description|safe|truncatechars:5000 }}]]></description> Do you know how to do that? -
Why is Django Crispy Forms throwing "module 'django.forms.forms' has no attribute 'BoundField'"
When I use the "|crispy" or "|as_crispy_field" filters on my form/fields, I get an error that the field has no attribute BoundField. This was working fine, but I updated django/crispy forms, and I'm not sure whether I missed a trick? The form works fine without the filter. forms.py: from django import forms from django.utils import timezone from bootstrap_modal_forms.forms import BSModalForm from backgammon import models class MatchForm(BSModalForm): date_played = forms.DateField(initial=timezone.now) class Meta: model = models.Match fields = [ 'date_played', 'winner', 'score' ] views.py from django.contrib.auth.mixins import PermissionRequiredMixin from bootstrap_modal_forms.generic import BSModalCreateView from .forms import MatchForm class MatchCreate(PermissionRequiredMixin, BSModalCreateView): permission_required = 'backgammon.add_match' template_name = 'backgammon/match_form.html' form_class = MatchForm success_message = 'Match saved.' success_url = reverse_lazy('backgammon-index') match_form.html {% load crispy_forms_tags %} <div class="container bg-light"> <form method="post"> {% csrf_token %} <div class="modal-body"> {% for field in form %} <div class="form-group{% if field.errors %} invalid{% endif %}"> {{ field|as_crispy_field }} </div> {% endfor %} </div> <div class="modal-footer"> {% if object %}<a class="btn btn-danger mr-auto" href="{% url 'match-delete' pk=object.pk %}">Delete</a>{% endif %} <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="submit-btn btn btn-primary">Save</button> </div> </form> </div> Traceback: Traceback (most recent call last): File "C:\Users\harla\Anaconda3\envs\djangoenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\harla\Anaconda3\envs\djangoenv\lib\site-packages\django\core\handlers\base.py", line 202, in _get_response … -
how i can play a downloaded audio file in response with django
Hello everyone I wanted to give in response an audio file downloaded from youtube but when I go to the page as a client I get a 40kb file I thought that my file was not downloaded whole. Please how can I fix this problem? thank you in advance. here is the code def data(request): """ docstring """ url = "https://www.youtube.com/watch?v=QtTR-_Klcq8" video = pafy.new(url) audiostreams = video.audiostreams audio = audiostreams[3].download() response = HttpResponse(audio, content_type='"Content-Type: audio/mpeg"') response['Content-Disposition'] = 'attachment; filename="audio.m4a"' return response