Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extract filtered data in django
OrderFilter is a django-filter. The export is working but I have only the header ... when i remove the request.get.get i have all the data extracted so i assume there is problem somewhere in my get request Can you help me please Views.py def Order(request): filter= OrderFilter(request.GET, queryset=Order.objects.all()) orders= filter.qs.order_by('-Date') """ Don't work Category_query = request.GET.get('Category') qs = Order.objects.filter(Category= Category_query) """ if request.GET.get('Export') == 'Export': response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="data.xlsx"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Data') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Date', 'Category', 'Item'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows=qs.values_list('Date', 'Category', 'Item') for row, rowdata in enumerate(rows): row_num += 1 for col, val in enumerate(rowdata): if isinstance(val,datetime.date): val = val.strftime('%d/%m/%Y') ws.write(row_num, col, val, font_style) wb.save(response) return response return render(request, 'template.html',{'orders':orders,'filter': filter}) template.html <form method="get"> {{filter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> <form method="GET" > <button class="btn btn-warning" type="submit" value="Export" name="Export"> Export</button> </form> -
Grabbing data from Postrgresql to Django
I'm new to Postgresql (and databases in general) and I have one that I filled with a lot of data. But now I need to access that data and create models, register it in the admin, etc. Does anybody know how I can do that? This is the data that I retrieved: https://github.com/guenthermi/the-movie-database-import -
How to modify messages displayed in Admin change page?
I have a model Document, and the admin can upload an image to a FileField. When a document/image is successfully uploaded, I also save a sha256 "fingerprint" of the image to test if an admin tries to upload a duplicate image. If a duplicate image is detected, I don't save the duplicate image and display an error message to the admin through the messages framework. However, I also get the message that the document was successfully uploaded. How can I prevent this from happening? My code in an abbreviated form: class Document(Model): document_id = models.AutoField(primary_key=True) computed_sha256 = models.CharField(editable=False, max_length=64, default="foobar") storage_file_name = models.FileField('File name', upload_to=settings.DOCUMENT_FOLDER_ORIGINALS, default=settings.DEFAULT_IMAGE_XXXLARGE_PATH,) class DocumentAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if form.is_valid(): if not change: # Uploading one or more images files = request.FILES.getlist('storage_file_name') if files: for f in files: # Check if this file has been uploaded before by checking the fingerprint _file = form.cleaned_data["storage_file_name"] sha256 = image_processing_utils.compute_sha256(_file) duplicate_files = Document.objects.filter(computed_sha256 = sha256) if len(duplicate_files) > 0: messages.add_message(request, messages.WARNING, 'Uploading a duplicate of "%s" and it will not be saved' % f.name) break; # more image processing stuff else: # some more image processing stuff obj.metadata = form.cleaned_data['metadata'] super().save_model(request, obj, form, change) The resulting admin … -
Django REST Framework - Only first query parameter showing in request.get_params
I would like to filter a queryset in a view using multiple query parameters, but "request.query_params" is only able to get the first query parameter in my query string. Here is my URLConf: urlpatterns = [ ... re_path(r'^descsearch/$', views.DescriptionSearchView.as_view(), name='descsearch'), ] Here is the top of my view where I'm attempting to get two query parameters from the query string ("description" and "descSearchMethod"): class DescriptionSearchView(generics.ListAPIView): serializer_class = DrawingSerializer def get_queryset(self): print("request.query_params: " + str(self.request.query_params)) description = self.request.query_params.get('description') print("description: " + description) descSearchMethod = self.request.query_params.get('descSearchMethod') print("descSearchMethod: " + descSearchMethod) ... When I make this GET request using curl: curl -X GET http://127.0.0.1:8000/api/descsearch/?description=O-RING&descSearchMethod=and The print statements in the Django console show that only the first query parameter "description" is in QueryDict. request.query_params: <QueryDict: {'description': ['O-RING']}> description: O-RING Internal Server Error: /api/descsearch/ ... If I switch the order so that "descSearchMethod" is the first query parameter, only it shows. Why is only the first query parameter showing in QueryDict? -
How can I open page with celery task?
from celery import Celery from celery import shared_task from Group.models import Group from django.shortcuts import render, redirect @shared_task def hello(): print('hello') return render() I want to open certain page with this task in django, is possible? return render not working! -
How do I change some routes in Django Project after login?
Let me explain with an example. Like when we first open www.coursera.org we get to their homepage. Then we login. After we login the session starts and we are redirected to main course dashboard. but if we see URl it is www.coursera.org so now the home route has chanmged from homepage to say dashboard. Now in django i can redirect to project.com/dashboard from project.com/login but what i want is after login the user should not have access to homepage at any route. So i want to change project.com/ which before login showed homepage to now showing the dashboard view simply change the view function linked to project.com/ route I hope I explained my question correctly. Thank you for help in advance -
Django Heroku admin page formatting
I know this has been around stack, but I have tried all the fixes in other threads and nothing seems to work. I've built a web app using Django and deployed through Heroku. Everything works perfectly. The only problem is the formatting of my live site admin page. It is not formatted nicely like all the other pages. However, it is formatted perfectly when I bring up the site on localhost. I've tried checking all my code in the settings.py file, and I have a static folder set up with a placeholder.txt file. I have all my settings.py code correct I feel. I ran >heroku run python manage.py collectstatic, which executed fine, although when I ran it locally >python manage.py collectstatic, I got an error, saying "django.core.exception.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a file system path" import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '((___*)b^_@_+_!' #left out key # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True … -
Django-filter - group like values with different primary keys in form
My goal is to filter a model that refers to plants. Below is an abbreviated version of my model: class Plant(models.Model): sku = models.CharField('SKU', max_length=14) name = models.CharField('Name', max_length=50) genus = models.ForeignKey(Genus, on_delete=models.SET_NULL, null=True, blank=True) class Meta: ordering = ['genus', 'name'] def __str__(self): return self.name My related model, Genus, is very basic with just two fields: class Genus(models.Model): common = models.CharField('Common Genus', max_length=100) latin = models.CharField('Latin Genus', max_length=100) class Meta: ordering = ['common'] verbose_name_plural = 'genera' def __str__(self): return self.common The point here is that an entry for Genus will sometimes have the same value for latin. For example Cherry, Peach, and Almond are all prunus but each has its own entry. { [ 'common': 'Cherry', 'latin': 'Prunus' ], [ 'common': 'Almond', 'latin': 'Prunus' ], [ 'common': 'Peach', 'latin': 'Prunus' ] } My problem arises when I use django-filter to filter these values. I have a common name filter and a latin name filter. The common name filter is straightforward since the common names will always be unique, but the latin name might be common among many entries. class LatinChoiceField(ModelChoiceField): def label_from_instance(self, obj): return obj.latin class LatinFilter(django_filters.ModelChoiceFilter): field_class = LatinChoiceField class ProductFilter(django_filters.FilterSet): genus__common = django_filters.ModelChoiceFilter(queryset=Genus.objects.all(), label='Genus') latin_q = Genus.objects.all().order_by('latin') genus__latin … -
name 'slugify' is not defined
Once a user had logged into my site he could write a post and update it. Then I was making progress in adding functionality which allowed people to make comments. I was at the stage where I could add comments from the back end and they would be accurately displayed on the front end. Now when I try and update posts I get an error message. I assume it is because there is a foreign key linking the comments class to the post class. I tried Googling the problem and looking on StackOverflow but I wasn't entirely convinced the material I was reading was remotely related to my problem. I am struggling to fix the issue because I barely even understand / know what the issue is. # Create your models here. class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now()) author = models.ForeignKey(User, on_delete=models.CASCADE) url= models.SlugField(max_length=500, unique=True, blank=True) def save(self, *args, **kwargs): self.url= slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by … -
Django returning None instead of a HTTP response
OK im probably doing this all wrong! I am trying to run a function in a view which calls another view. This seems to pass my request into the next function as a POST method before loading the form from the second function. my views.py def joinLeague(request): if request.method == 'POST': league = JoinLeagueQueue(user=request.user) form = JoinLeagueForm(instance=league, data=request.POST) if form.is_valid(): form.save() context = league.id return confirmLeague(request, context) else: form = JoinLeagueForm() context = {'form':form} return render(request, 'userteams/joinleagueform.html', context) def confirmLeague(request, league): league = get_object_or_404(JoinLeagueQueue, pk=league) pin = league.pin if request.method == 'POST': if 'accept' in request.POST: # This refers to the action from my form which is waiting for a button press in a html form. LeaguesJoinedTo.objects.create( leaguePin = pin, playerjoined = request.user.id, ) return redirect('punterDashboard') else: context = {'league':league} return render(request, 'userteams/confirmleague.html', context) -
Url parameters not get in my views in Django
I want to add and edit in same template. Url showing parameters but id showing none still in my views. http://127.0.0.1:8000/edit_supplierdetails/1 IN My Template: {% for supplier in suppliers %} <a href="{% url 'edit_supplierdetails' supplier.id %}">Edit</a> IN My URL url(r'supplierdetails/', views.add_supplierdetails, name='add_supplierdetails'), url(r'^edit_supplierdetails/(?P<id>\d+)$', views.add_supplierdetails, name='edit_supplierdetails'), In My Views: def add_supplierdetails(request, id=None): print(id) brands = SupplierDetails.objects.all() if id: productcategory = get_object_or_404(SupplierDetails, id=id) title = 'Update' else: productcategory = SupplierDetails() title = 'Add' form = SupplierDetailsForm(request.POST or None, request.FILES or None, instance=productcategory) if request.POST and form.is_valid(): form.save() messages.success(request, "Brand "+ title +" successfully") return redirect('/brand') return render(request, 'products/add_supplier2.html', { 'form': form, 'suppliers': brands, 'title': title }) -
Can't create multiple dynamic sub menus using bootstrap 4
I am currently having issues creating dynamic submenus with bootstrap. Using a simple ajax request I want to get the name of the folders on my Django server and then display the chosen folder items, creating several submenus. I'm using bootstrap 4, the first JS snippet works as intended but I can't get the second one to behave similarly and iterate upon its parent object. HTML <div class="dropdown show"> <a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Analyze </a> <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink"> <li class="dropdown-submenu"> <a id='spec_library' class="dropdown-item dropdown-toggle" href="#">Library</a> <ul id='spec_lib' class="dropdown-menu"> <!-- <li><a class="dropdown-item" href="#">History</a></li> <li><a class="dropdown-item" href="#">Geography</a></li> <li><a class="dropdown-item" href="#">Sociology</a></li> --> </ul> </li> <li><a class="dropdown-item" href="#">Upload</a></li> </ul> </div> JS The first snippet works as intended $('#spec_library').on('click', function(e) { $.ajax({ type: "GET", url: "spectro_lib", /* Call python function in this script */ /* Passing the text data */ success: callback }); function callback(response){ console.log(response) instrument = response size = response.length; spec_lib = document.getElementById("spec_lib") console.log(spec_lib.childNodes.length) $("#spec_lib").empty(); if (spec_lib.childNodes.length <= size){ for (i = 0; i <= size - 1;i++){ var spec_lib_x = "spec_lib_" + i var lib_submenu = document.createElement("li"); lib_submenu.id= spec_lib_x lib_submenu.className="dropdown-item dropdown-submenu" document.getElementById("spec_lib").appendChild(lib_submenu) var lib_subitem = document.createElement("a"); lib_subitem.id= "spec_lib_instrument" lib_subitem.className="dropdown-item dropdown-toggle" lib_subitem.href="#" lib_subitem.innerHTML = response[i] document.getElementById(spec_lib_x).appendChild(lib_subitem) var … -
React vs django native templating language with django as backend
Recently I had started learning react. But I am a django developer. I had got a doubt that which one is to be used as frontend with django as backend. Is react as frontend and django APIs as backend Or Django templating language with django plain views as backend -
Where does Django stdout output go when running with nginx and Gunicorn?
In my my_application/settings.py file, for example, I have a couple of print statements, thus: print( 'running settings.py: ALLOWED_HOSTS: ' ) print( '\n'.join( ALLOWED_HOSTS ) ) ... where does this output actually go on a remote server running nginx and Gunicorn? NB I am aware this may be an egregious security breach to print ALLOWED_HOSTS anywhere, for all I know. This is merely an example: I am at the learning/experimentation stage. -
Google Drive API - File Download Issues with Service Account
I'm setting up a Django-Heroku app to allow users to download videos up to a size of 75MB. I have tried this two ways now, and neither works how I want, so I'd like to know if I'm hitting some limitation or not doing it properly. Environment I have a basic G Suite account with a service account that has the delegate-authority enabled. The JSON key is in place, the API is enabled, the account is authorized with the proper scopes and I am able to download the file contents. What I Want The user clicks on a link and the file downloads directly from Google Drive with no web app pass-through, no sign-in, no virus warning pop-up, etc. It should be seamless for the user -- click once and the file downloads. class GoogleDrive(): connection = None def __init__(self, version='v3', permissions=['read'], autoconnect=True, *args, **kwargs): super(GoogleDrive, self).__init__(*args, **kwargs) self.service = 'drive' self.version = version self.permissions = permissions # Connect automatically if autoconnect: self.connect() # Calls build() with appropriate scope / credentials Attempt 1 - Download GD file and return as HTTPResponse # Build a GD service with "readonly" scope gd = GoogleDrive() request = gd.connection.files().get_media(fileId='<SOME_GD_ID>') stream = io.BytesIO() downloader = … -
Dynamic Image Source Creating using Django
I want to make shopping website using Django and html + css. For this purpose, I have to have specific picture for each item and i am trying to find this picture source using combination of static file tagging. I could not store the image in the database, so images are chosen dynamically from the static folder. however, my code does not work, can someone help me to solve this issue? My HTML Code def sales_page(request): all_storage_products=Storage.objects.all(); sales_page_product={'all_storage_products_dict':all_storage_products} form1=search_field(); file_path =os.path.join(STATIC_DIR,'images'); if(request.method=='POST'): form1=search_field(request.POST); if(form1.is_valid()): all_storage_products=Storage.objects.filter(product_description__icontains=form1.cleaned_data['your_name'] ); sales_page_product={'all_storage_products_dict':all_storage_products} form1=search_field(); return render(request, 'first_app/sales_page.html',{'all_storage_products_dict':all_storage_products, 'forms':form1, 'image_path':file_path}); <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <style> .main_page_nav { width: 100%; height: auto; display: flex; } .main_page_nav ul{ height: auto; width: 100%; background-color: rgb(243,243,243); } .main_page_nav ul li{ display: inline; padding: 1rem; } .main_page_nav ul li a{ font-size: 2rem; } .main_page_nav ul li a:hover{ font-size: 2rem; border-style: solid; border-left-color: rgb(243,243,243); border-top-color: rgb(243,243,243); border-right-color: rgb(243,243,243); border-bottom-color: green; } #main_page_nav_last_item{ float: right; padding: 0; } #search_field{ width: 100%; } table, tr, td{ background-color: white; border-style: solid; } form p{ width: 100%; display: flex; justify-content: center; font-size: 2rem; } input[name="your_name"]{ width: 50%; border-radius: 5%; } input[name="your_name"]:focus{ outline-color: green; … -
How would i use django-filter if the search function and the results are on different pages?
how would django-filter work if the search function and the filtering are on different pages? For example, I have a home page with a search function, the results of the search are listed in the results page. On these results I want to apply filters ( like airbnb does for example). I'm able to filter results on the same page as the results currently. -
How to combine several models in the one DetailView
I have 3 models Course,CourseSection,SectionVideo and last 2 connected to the Course model. I want to create DetailView for the Course, which will contain all models, i mean where i can show sections inside and inside section show videos. How to do that? class Course(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=150, null=True, blank=True) description = models.TextField() image = models.ImageField(upload_to='courses/course_images',blank=True,null=True) cover = models.ImageField(upload_to='courses/course_covers',blank=True,null=True) tutor = models.ForeignKey(User,related_name='tutor_courses',on_delete=models.CASCADE,null=True) students = models.ForeignKey(User,related_name='course_students',blank=True,on_delete=models.CASCADE,null=True) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) category = models.ForeignKey(CourseCategories,on_delete=models.CASCADE) certificate = models.ImageField(upload_to='courses/course_certificates',blank=True,null=True) languages = LanguageField(blank=True) rank_score = models.FloatField(default=0.0) price = models.FloatField(default=0.0) discount_price = models.FloatField(blank=True, null=True) class CourseSections(models.Model): title = models.CharField(max_length=50) course = models.ForeignKey(Course,on_delete=models.CASCADE,null=True) class SectionVideos(models.Model): video = models.FileField(upload_to='courses/course_videos',max_length=100) section = models.ForeignKey(CourseSections,on_delete=models.CASCADE,null=True) -
Get Data from Multiple ForeignKey Query Results
I have the following models.py set up: Student(models.Model): id = models.CharField(max_length = 15, primary_key = True, unique = True) first_name = models.CharField(max_length = 25) last_name = models.CharField(max_length = 25) ... Fine(models.Model): name = models.CharField(max_length = 25) description = models.CharField(max_length = 100) value = models.DecimalField(max_digits = 6, decimal_places = 2) StudentFines(models.Model): student = ForeignKey(Student, on_delete = models.CASCADE) fine = ForeignKey(Fine, null = True, on_delete = models.SET_NULL, related_name = 'fines') created = models.DateTimeField(auto_now = True) I've assigned two fines to a particular user in my database, so in my view.py I have this to get the fines that are assigned to the user: def detail(request, id): ... fines = StudentFines.objects.filter(student_id = id) ... context = { ... 'fines': fines, } And when I call it in my template with {% for fine in fines %}A fine.{% endfor %}, I get two results. Now I want to report the specific details of the fines: the name, description, and value. Eventually I plan to use a form to add an entry directly from the page, but that's future stuff. I've scoured the Internet and came across several ways to try and get the ForeignKey's data, but none of what I try has worked. I've … -
How to carry out calculations in Django Rest Framework viewsets.ModelViewSets?
I have an API that pulls from a MySQL game database and I would like to get a list of top unique scorers. My Viewset looks like this: -
Form not uploading imageField in Django
I'm following an online course about Django. I need to upload an image via a form but it doesn't work. My form is in blog/contact and when I submit it goes back to blog/ without saving the for, also I can see the that form is bound= false and valid = false after submitting. If anyone can help me ? Here is my code : # views.py def nouveau_contact(request): sauvegarde = False #il ne faut pas oublier le request.FILES sinon ça ne marche pas form = NouveauContactForm(request.POST or None, request.FILES or None) print ("erreur : ") print(form.is_valid) if form.is_valid(): contact = Contact() contact.nom = form.cleaned_data["nom"] contact.adresse = form.cleaned_data["adresse"] contact.photo = form.cleaned_data["photo"] contact.save() sauvegarde = True return render(request, 'blog/contact.html', { 'form': form, 'sauvegarde': sauvegarde }) # forms.py class NouveauContactForm(forms.Form): nom = forms.CharField() adresse = forms.CharField(widget=forms.Textarea) photo = forms.ImageField() # Media files MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") I am using anaconda and I have already downloaded pillow Thank you in advance for your help -
Unexpected tokens in <!DOCTYPE html> in pycharm community edition
I am new in using pycharm but I am loving it gradually. I am getting a red underline on and the error is "Unexpected Token". Why pycharm shows it? I can't understand. -
Django save image form data
I currently have a 3x3 grid of images. I want the user to select an image press next and record that response in the database. I've been trying to solve this for a while and I am not sure what to do. Any help is greatly appreciated. templatetag: random_Image.py {% random_images_category1 3 as images_normal %} <div class="row no-pad display-flex my-row"> {% for image in images_normal %} <div class="col-xl-4 col-lg-4 col-md-4 col-sm-4 col- my-col my-col-xl-4 col-lg-4 col-md-4 col-sm-4 col-4 my-col"> {% csrf_token %} <input class="img-thumbnail" type="image" id="image" alt="Image" src="{{ MEDIA_URL}}{{ image }}"> {# <img class="img-thumbnail" src="{{ MEDIA_URL}}{{ image }}">#} </div> {% endfor %} </div> template_tag: @register.simple_tag def random_images_category1(count=3): valid_extensions = ('.jpg', '.jpeg', '.png', '.gif') rand_dir = '/static/app_pickfeel/images/normal/' path = '/app_pickfeel/static/app_pickfeel/images/normal/' files = [f for f in os.listdir(settings.BASE_DIR + path) if f[f.rfind("."):] in valid_extensions] print(random.sample(files, count)) return [rand_dir + filename for filename in random.sample(files, count)] -
ModuleNotFoundError For Rest Framework
I've installed django rest framework using pip install djangorestframework And added the rest framework to the INSTALLED_APP: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', ] yet I still get this error when I run python3 manage.py runserver: ModuleNotFoundError: No module named 'rest_framework' And to rectify this error I have already tried all this: 1.Tried to install django rest framework using: pip3 install djangorestframework 2.Checked for , after adding 'rest_framework' to INSTALLED_APPS 3.My virtual environment is active 4.I have added markdown and django-filter also using : pip install markdown pip install django-filter 5.Upgraded my pip using: python -m pip install --upgrade pip 6.Tried adding 'rest_framework' as the first app in INSTALLED_APPS 7.Tried deactivating and the activating again the virtual environment I'm using Django == 3.0.2 and Django REST Framework == 3.11.0 So now what should I do to remove this error?? -
AttributeError: This QueryDict instance is immutable for test cases
I am trying to change my request.data dict to remove some additional field. It is working completely fine in views. But when I run test cases for the same, I get this error: AttributeError: This QueryDict instance is immutable Here is my viewset: def create(self, request, *args, **kwargs): context = {'view': self, 'request': request} addresses = request.data.pop("addresses", None) serializer = self.get_serializer(data=request.data, context=context) serializer.is_valid(raise_exception=True) response = super(WarehouseViewSet, self).create(request, *args, **kwargs) if addresses is None: pass else: serializer = self.get_serializer(data=request.data, context=context) serializer.is_valid(raise_exception=True) addresses = serializer.update_warehouse_address(request, addresses, response.data["id"]) response.data["addresses"] = addresses return Response(data=response.data, status=status.HTTP_201_CREATED) and here is my test case for the same view: def test_create_warehouse_authenticated(self): response = client.post( reverse('warehouse_list_create'), data={ 'name': self.test_warehouse['test_warehouse']['name'], 'branch': self.test_warehouse['test_warehouse']['branch'], }, **{'HTTP_AUTHORIZATION': 'Bearer {}'.format( self.test_users['test_user']['access_token'] )}, ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) How to fix this error?