Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: Object of type LinkPreview is not JSON serializable
I'm using the following link preview python package in my django 3.2 api. https://github.com/meyt/linkpreview When I post a link from my frontend flutter app and attempt to preview it, I get the error as stated. TypeError: Object of type LinkPreview is not JSON serializable Here are the views.py my flutter app hits : class PreviewLink(APIView): permission_classes = (IsAuthenticated, IsNotSuspended) throttle_scope = 'link_preview' def post(self, request): serializer = PreviewLinkSerializer(data=request.data, context={"request": request}) serializer.is_valid(raise_exception=True) data = serializer.validated_data link = data.get('link') user = request.user link_preview = user.preview_link(link) return Response(link_preview, status=status.HTTP_200_OK) class LinkIsPreviewable(APIView): permission_classes = (IsAuthenticated, IsNotSuspended) throttle_scope = 'link_preview' def post(self, request): serializer = PreviewLinkSerializer(data=request.data, context={"request": request}) serializer.is_valid(raise_exception=True) data = serializer.validated_data link = data.get('link') try: is_previewable = link_preview(url=link) except Exception as e: is_previewable = False return Response({ 'is_previewable': is_previewable }, status=status.HTTP_200_OK) The PreviewLinkSerializer class ---> class PreviewLinkSerializer(serializers.Serializer): link = serializers.CharField(max_length=255, required=True, allow_blank=False) The link_preview function: def link_preview(url: str = None,content: str = None,parser: str = "html.parser"): """ Get link preview """ if content is None: try: grabber = LinkGrabber() content, url = grabber.get_content(url) except InvalidMimeTypeError: content = "" link = Link(url, content) return LinkPreview(link, parser=parser) I have only pasted the relevant code above. The complete code is available in the link I shared. -
Django Multiple Database - Duplicate tables in default
I have a Django Application with two database. Even with routers, subapp tables are written in default DB. SubApp DB has only its own table. In core.models Im not define the appl_label In subapp models.py for every class, I define the app_label SubApp models.py class MyModel ... ... class Meta: app_label = 'subapp_name' db_table = 'my_model' In default settings I have defined the routing: DATABASE_ROUTERS = ["core.routers.DefaultRouter" , "subapp.routers.SubAppRouter"] In subapp router in allow_migrate, I have this: def allow_migrate(self, db, app_label, model_name = None, **hints): if app_label == 'subapp_name' and db == 'subapp_name': return True return None This works well. In SubApp Database I only have MyModel table and a DjangoMigration table (this one has all migrations rows, even from default modules). This is the allow_migrate in DefaultRouter: def allow_migrate(self, db, app_label, model_name = None, **hints): route_app_labels = { "admin", "auth", "contenttypes", "core", "sessions" } if app_label in self.route_app_labels: return db == "default" return None Unfortunally, subapp MyModel is create in default database too but subapp is not inside route_app_labels. Why is this happening? -
Is there any settings to use Django timezone other than TIME_ZONE?
I am using django and postgres. I set this in settings.py TIME_ZONE = 'Asia/Tokyo' USE_TZ = True in my models.py there is models which uses DateTimeField. class CustomUser(AbstractUser): detail = models.JSONField(default=dict,null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) pass then check admin console http://localhosg:8000/admin, but time zone is not applied. Still UTC is used in created_at and updated_at Is there any other things I need to check? -
Django Admin Dashboard ImageField Problem
In my django admin dashboard i made a model for an ImageField, problem is that i will use that for a carousel but for that i need to upload more than one image, django limits to only uploading 1 image at a time, and i tried looking around for about 3 hours and i couldnt find any solutions for it, everytime i find something either it doesnt work anymore or its not what im looking. So overall i just want a solution for the Choose Files button when i click it i can choose more than one file/img i tried looking for solutions for more than 3 hours and couldnt find anything that would work -
Customize Django Admin, Order and place of model
I have a Django project in this project i have app a with model A and app b with model B. # a/models.py class A(models.Model): pass # b.models.py class B(models.Model): pass So i see Model A under section of app a and same for Model B. But I want to change this placement because from the first of project I was bad in layout. notice: I've tried putting BModelAdmin(admin.ModelAdmin) in admin file of app a and it has not worked. please tell me an absolute answer. -
django admin panel data
Hi Team i have a written code in admin.py. At this time i am getting urls and other feilds . what i want as url can be duplicate for ex i have google url but each url consist if different crud operations . what i want is grouping . Please advise how we can do that. class UrlAccessAdmin(admin.ModelAdmin): list_display = ('method', 'clickable_url', 'has_access', 'get_roles', 'description') list_filter = ('method',) search_fields = ['url', ] list_per_page= 15 def get_roles(self, obj): return obj.role_list if obj.role_list != 'ALL' else 'All Roles' def clickable_url(self, obj): url_length = 50 if len(obj.url) > url_length: truncated_url = f'{obj.url[:url_length]}...' else: truncated_url = obj.url return mark_safe(f'<a href="{obj.url}" target="_blank">{truncated_url}</a>') clickable_url.short_description = 'URL' admin.site.register(UrlAccess, UrlAccessAdmin) -
Django images don't show up on the web-site
settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') template <img src="{{ group_avatar.avatar.url }}" style="width:30%" alt="Group Avatar" class="navbar-brand"> urls.py `urlpatterns = [ path('admin/', admin.site.urls), # Django admin route path("", include("apps.authentication.urls")), # Auth routes - login / register # ADD NEW Routes HERE # Leave `Home.Urls` as last the last line path("", include("apps.home.urls")) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)` Instead of getting an image, I get an alt text... I've tried to fix it up for a long time, but nothing works... Django version 3.2.16, using settings 'core.settings' I suppose that the problem is in the project structure. It was done before I started working on the project and it would be difficult to change it... application is in the folder apps, which is in the root folder, and template which is needed is also there. But the folder 'media' is in the root directory. Although I'm not sure that the problem is in this. Interesting fact is that if I manually write the way to the image from static folder (static folder is also localed in apps directory) it will work. Would be glad for any help) Searching, reading documentation. I expect a hint how to fix it or where to search the … -
Django Paginator with bulk_update only updates odd pages
I have a two tables that have around 1M rows and in one of them, I've added a new migration that adds two new columns to one of them and that requires some computation to add their values. What I did was a command that fetches all rows in that table, and use Paginator with a chunk size of 1000, and after adding the new values, I perform the bulk_update. The problem is that only the odd pages are updated, the even ones stay with the null value. I start with 1000 pages to update, then I need to run again only to update 500 pages, and so on. I've also tested with chunks of 10, and the problem persists. Is there something wrong with this code? def add_values_to_columns(foo): foo.col1=... foo.col2=... class Command(BaseCommand): def handle(self, *args, **options): try: queryset = Foo.objects.all() \ .filter(col1__isnull=True, col2__isnull=True) \ .order_by("id") \ .select_related("bar") chunk_size = 1000 paginator = Paginator(queryset, chunk_size) pages = paginator.page_range number_pages = pages[-1] for page_number in pages: page = paginator.page(page_number) updated_rows = [] for foo in page.object_list: add_values_to_columns(foo) updated_rows.append(foo) Foo.objects.bulk_update(updated_rows, ["col1", "col2"]) except Exception as e: self.stdout.write(e) -
Django VS-Eextenstion is not colorizing syntax inside cotation
I am using Django extension to highlight my text. it works perfectly outside but fails to highlight inside citations. not working under cotations I expect if there is any solution to overcome this. I want it to highlight the code inside exactly as outside , what can i do to overcome this. -
List column data in Django template can not be iterated
Please read my code <p>{{request.POST}}</p> <p>langchi : {{request.POST.langchi.0}}/{{request.POST.langchi.1}}/{{request.POST.langchi.2}}/{{request.POST.langchi.3}}<p> <p>langeng : {{request.POST.langeng.0}}/{{request.POST.langeng.1}}/{{request.POST.langeng.2}}/{{request.POST.langeng.3}}</p> <p>langjpn : {{request.POST.langjpn.0}}/{{request.POST.langjpn.1}}/{{request.POST.langjpn.2}}/{{request.POST.langjpn.3}}</p> Output Screen We can tell in the request.Post, there are 3 list data langchi, langeng and langjpn. But when I try to read them by request.Post.langchi.0,request.Post.langchi.1... I can not get the actual value. Did I do something wrong? Appreciate for any help. Appreciate for any help. -
Django admin panel CSS files are denied to access to GC bucket
In my Django rest framework project, I have used the filter from django admin panel to filter users This is what I'm using : my codein admin.py based on their profile. This work fine in my local host localhost filtering users Now I'm hosting my project on GCP, once I push to live staging the screen display like this : the panel after pushing to staging . What I got in the console when I go to filter users is console when I use the filter the network tab in condole when I click over one of the error Thanks a lot of any suggestions https://github.com/jschneier/django-storages/issues/454 -
How to get User queryset from his Profile
Good afternoon. I am creating a referral system and at the last stage a question appeared. I need to get request.User and inviting.User querysets for Friends.create.objects(inviting=current_user, invited=inviting_query.user) How i get they? My models Post function -
artichels_pagination.get() missing 1 required positional argument: 'request'
class artichels_pagination(ListView): queryset =models.article.objects.all().order_by('-upload') template_name = 'blog.html' def get(self,request): page_artichel = Paginator(self.queryset, 2) page_number = request.GET.get('page') page_obj = page_artichel.get_page(page_number) render(request,self.template_name,context={'artichel':page_obj}) this is eror: artichels_pagination.get() missing 1 required positional argument: 'request' -
How to create a Standalone Shopify Public App Using Django
I am taking reference from https://github.com/Shopify/sample-django-app. This repository makes an Embedded shopify app. Is there a way to turn this into a standalone shopify app? If this repository can't be turned into an Standalone Shopify app, what are the ways to make a standalone shopify app in Django. I tried surfing the internet to find any solution but there is not any solution that uses Django. Any help would be appreciated. -
how to use json in django
{ "symbol": "GOLD", "rates": [{ "time": "2023.08.02 09:00:00", "open": 1948.75000, "high": 1950.30000, "low": 1947.92000, "close": 1949.57000, "tick_volume": 3342, "spread": 0, "real_volume": 0 },{ "time": "2023.08.02 08:00:00", "open": 1946.28000, "high": 1949.90000, "low": 1946.27000, "close": 1948.78000, "tick_volume": 6574, "spread": 0, "real_volume": 0 },{ "time": "2023.08.02 07:00:00", "open": 1949.27000, "high": 1949.28000, "low": 1945.18000, "close": 1946.29000, "tick_volume": 3716, "spread": 0, "real_volume": 0 },{ "time": "2023.08.02 06:00:00", "open": 1948.18000, "high": 1949.44000, "low": 1946.58000, "close": 1949.27000, "tick_volume": 4494, "spread": 0, "real_volume": 0 },{ "time": "2023.08.02 05:00:00", "open": 1947.54000, "high": 1949.80000, "low": 1947.03000, "close": 1948.19000, "tick_volume": 6357, "spread": 0, "real_volume": 0 },{ "time": "2023.08.02 04:00:00", "open": 1949.14000, "high": 1949.79000, "low": 1947.58000, "close": 1947.60000, "tick_volume": 6730, "spread": 0, "real_volume": 0 },{ "time": "2023.08.02 03:00:00", "open": 1952.12000, "high": 1952.35000, "low": 1948.27000, "close": 1949.17000, "tick_volume": 5801, "spread": 0, "real_volume": 0 },{ "time": "2023.08.02 02:00:00", "open": 1951.14000, "high": 1952.80000, "low": 1950.44000, "close": 1952.10000, "tick_volume": 3464, "spread": 0, "real_volume": 0 },{ "time": "2023.08.02 01:00:00", "open": 1947.38000, "high": 1951.78000, "low": 1945.56000, "close": 1951.08000, "tick_volume": 5473, "spread": 0, "real_volume": 0 },{ "time": "2023.08.01 23:00:00", "open": 1944.36000, "high": 1944.82000, "low": 1943.97000, "close": 1944.24000, "tick_volume": 1335, "spread": 0, "real_volume": 0 } ] } This is the data I sent to the background, I named it data … -
Not Found: /static/frontend/styles.css (Docker, Django, Nginx)
I am trying out docker for the first time to deploy in production environment I followed some you- tube tutorials but i was successful in containerizing my Django project. but when i run it nothing appears and i get a 404 error saying not found static/fronted/styles.CSS. Please refer to the attached snippet: error: Here is my Docker file: FROM nikolaik/python-nodejs:python3.8-nodejs14-bullseye ENV PYTHONUNBUFFERED 1 ENV LC_ALL C.UTF-8 ENV LANG C.UTF-8 RUN python3 -m pip install --upgrade pip RUN set -ex && mkdir /app WORKDIR /app # Copy the requirements file and install dependencies COPY d_requirements.txt /app/ RUN pip install -r d_requirements.txt # Copy the application code COPY . /app/ # Create the /opt/ai_sensei_data_source directory and set permissions RUN mkdir /opt/ai_sensei_data_source WORKDIR /opt RUN chmod a+x+w+r ai_sensei_data_source # Copy the .env file to /opt/ai_sensei_data_source/ COPY /.env /opt/ai_sensei_data_source/.env # Change back to the frontend directory to install frontend dependencies WORKDIR /app/frontend # Install frontend dependencies RUN npm install -f RUN npm install -g @angular/cli RUN ng build --configuration production # Copy build static files to nginx conf dir & set permissions RUN mkdir -p /home/kchavan/Desktop/dlops-portal/static RUN cp -r /app/static/* /home/kchavan/Desktop/dlops-portal/static/ # # RUN chown -R <user>:<group> /home/kchavan/Desktop/dlops-portal/ && \ # # chmod -R … -
Can not configure postgres database in GitHub actions pipeline using Docker
I am creating pipeline for my Django Project with GitHub actions and can't make it working correctly. As I use docker, when I start the Docker and start my tests with 'python manage.py test' it works correctly. But when my tests are started I get an error. The reason is probably is that it does not know how to connect to DB, as Docker works with that in my case. I tried to use github secrets, but it seems that it does not work. Here is the traceback in GitHub Actions: Creating test database for alias 'default'... /opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/db/backends/postgresql/base.py:405: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. warnings.warn( Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/db/backends/base/base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Found 2 test(s). File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 275, in get_new_connection connection = … -
Semantic-ui multiple How about customizing the display?
I have created a multi-selection dropdown box, but I don't want it to increase by one every time I click on it. I envisioned that it would display no more than three values, and if it did, it would display "4 for 10 selection", is there anything I can do to make this happen? I have tried this method but it gives me an error. //Customize the text that is displayed after multiple selections onLabelCreate: function(value, text) { if ($('.ui.dropdown').dropdown('get value').length > 3) { return '4 of 6 selected'; } } -
Django Form Does Not Validate With Correct Files
class RentalImageForm(forms.Form): images = forms.FileField(validators= [FileExtensionValidator(allowed_extensions=['jpg', 'jpeg', 'png'], message='Only JPG, JPEG, PNG, and GIF files are allowed.')]) @login_required def createListing(request): if request.method == 'POST': createListingForm = RentalForm(request.POST) if request.FILES.getlist('images'): uploaded_files = request.FILES.getlist('images') print(uploaded_files) for files in uploaded_files: rental_image_form = RentalImageForm({'images':files}) if rental_image_form.is_valid(): print('VALID') else: print(rental_image_form.errors) <input type="file" name="images" accept="image/*" required multiple id="id_images" /> _____________________________________________________ I am trying to validate each file I upload to my input and then put them in a loop to verify that all files are in correct extensions. Even when my extensions are all correct my Rental Image Form gives out false when I check with .is_valid(). Overall I have checked and seen that my images files are correctly uploaded but when it comes to validating the form it fails. -
toggle table row based on unchecked checkbox
Not super familiar with frontend, but I have 4 checkboxes I'm using to filter table data. Any number of them can be selected at once. What I want to accomplish: get all unchecked boxes if no boxes are checked pass (meaning don't hide any rows) if a box is checked, for any box that is NOT checked, exclude the row associated with that unchecked box This is for a Django app and the table row id is being generated via database query. The table will have max 100 rows. Per the query I'm executing, any table row will be either: id="audio", id="video", id="writing", id="games" HTML: <div> <input type="checkbox" value="music" id="music_filter"> <input type="checkbox" value="video" id="video_filter"> <input type="checkbox" value="writing" id="writing_filter"> <input type="checkbox" value="games" id="games_filter"> </div> <table class="table"> <thead> <tr> <th>Col 1</th> <th>Col 2</th> </tr> </thead> {% for i in query_set %} <tbody> <tr id="{{i.media_type}}"> <td>{{some data}}</td> <td>{{some other data}}</td> </tr> </tbody> I have jQuery loaded via CDN in the html file and trying this: JQUERY/JS: $(document).ready(function(){ $('#music_filter', '#video_filter', '#writing_filter', '#games_filter').on('click',function(){ var notChecked = $("input:checkbox:not(:checked)"); if (notChecked.length > 0) { for (let i = 0; i < notChecked.length; i++) { $('#i').toggle(); }; }; }); }); A little help to see my mistake(s)? Thanks! -
Django: Auto populate data based on selection
I am trying to create an invoice/PO Form and need some help. I am using 4 models: Client, Shipping, Billing, and PO models. I have the OneToOne relationship between shipping and billing models to the client model and both as foreign keys (please let me know if this method is still ok) in PO model. models.py ClientBillingAddress and ShippingAddress are identical, except "billing" is replaced with "shipping" class ClientBillingAddress(models.Model): client = models.OneToOneField(Client, on_delete=models.CASCADE, related_name='billing_address') billing_location_name = models.CharField(max_length=255, unique=True) address_line_1 = models.CharField(max_length=200, blank=True, null=True) address_line_2 = models.CharField(max_length=100, blank=True, null=True) address_city = models.CharField(max_length=50, blank=True, null=True) address_province = models.CharField(max_length=50, blank=True, null=True) address_postal = models.CharField(max_length=15, blank=True, null=True) address_country = models.CharField(max_length=50, blank=True, null=True) phone = models.CharField(max_length=15, null=True, blank=True) email_to = models.CharField(max_length=150, null=True, blank=True) email_cc = models.CharField(max_length=150, null=True, blank=True) bill_contact_name = models.CharField(null=True, blank=True, max_length=50) is_default = models.BooleanField(default=False) def get_formatted_address(self): address_lines = [self.billing_location_name, self.address_line_1, self.address_line_2] address_city_info = f"{self.address_city}, {self.address_province}, {self.address_postal}" address_lines.append(address_city_info) address_lines.append(self.address_country) return "\n".join(address_lines) def __str__(self): return self.billing_location_name class ClientPO(models.Model): client_PO_number = models.CharField(max_length=50, unique=True) customer_company = models.ForeignKey(Client, on_delete=models.CASCADE, related_name="customer_name_PO") order_reserved_total = models.PositiveBigIntegerField(default=0) order_total = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=Decimal("0.00")) order_line = models.PositiveBigIntegerField(default=0) order_product = models.ForeignKey(InventoryItemDetail, on_delete=models.CASCADE, related_name="order_products") order_qty = models.PositiveBigIntegerField(default=0) order_unit_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=Decimal("0.00")) order_extended_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=Decimal("0.00")) order_units = models.CharField(max_length=10, … -
Reactjst-WebSocket is already in CLOSING or CLOSED state
I created chat system using Django and Reactjs,when i want to send Message then in console give me Error of : WebSocket is already in CLOSING or CLOSED state. my code is let socket = new WebSocket(ServerUrl.WS_BASE_URL + ws/users/${CommonUtil.getUserId()}/chat/); const messageSubmitHandler = (event) =\> { event.preventDefault(); if (inputMessage) { socket.send( JSON.stringify({ action: SocketActions.MESSAGE, message: inputMessage, user: CommonUtil.getUserId(), roomId: CommonUtil.getActiveChatId(match), }) ); } setInputMessage(''); }; \<div className="flex-grow-0 py-3 px-4 border-top"\> \<form onSubmit={messageSubmitHandler}\> \<div className="input-group"\> \<input onChange={(event) =\> setInputMessage(event.target.value)} onKeyUp={chatMessageTypingHandler} value={inputMessage} id="chat-message-input" type="text" className="form-control" placeholder="Type your message" autoComplete="off" /\> \<button id="chat-message-submit" className="btn btn-outline-warning"\> Send \</button\> \</div\> \</form\> \</div\> I search in stackOverflow but there is no Such solution -
Add field in swagger ui using drf-yasg
My code is hosted here. It uses drf-yasg, jwt and the django rest framework. I am trying to set up a patch method to have the user edit his task. The code in a nutshell is as follows def get_payload(request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('Unauthenticated!') try: payload = jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated!') return payload class TaskView(APIView): pk = openapi.Parameter('pk', openapi.IN_QUERY, description="field you want to order by to", type=openapi.TYPE_INTEGER) @swagger_auto_schema( request_body=openapi.Schema( manual_parameters=[pk], type=openapi.TYPE_OBJECT, properties={ 'taskname': openapi.Schema(type=openapi.TYPE_STRING, description='Add taskname'), 'completion': openapi.Schema(type=openapi.TYPE_BOOLEAN, description='completion'), } ) ) def patch(self, request, pk): payload = get_payload(request=request) task = Tasks.objects.filter(id=pk, username=payload['username']).first() serializer = TaskSerializer(task, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) However, the swagger ui does not display the field for pk. I can see the sample body but the field for pk is missing. How do I add the field for pk here? -
How to change related object when creating object in DRF
I want to change is_available field in Book object when reservation is being create. I found a way which I am pasting here, but this digging in request looks messy, so as it often is with so mature frameworks as drf there are probably better ways to do that. So I have serializer.py class BookSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = BookModel fields = ["number", "title", "author", "is_available"] class ReservationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ReservationModel fields = ["reserved_by", "book", "started_at", "valid_until"] And views.py class BookViewSet(viewsets.ModelViewSet): queryset = BookModel.objects.all() serializer_class = BookSerializer permission_classess = [] class ReservationViewSet(viewsets.ModelViewSet): queryset = ReservationModel.objects.all() serializer_class = ReservationSerializer permission_classess = [] def perform_create(self, request, *args, **kwargs): super().perform_create(request, *args, **kwargs) book = BookModel.objects.get(pk=request.data.serializer.instance.book_id) book.is_available = False book.save() I posted what I did, Please teach me do it better - proper way -
How can I assert that a pdf file was returned in python?
I am working on asserting that a pdf is returned from my request. Here is what my test looks like so far. @mock.patch('path.to.class._get_file', return_value=MockResponse(status.HTTP_200_OK, 'application/pdf')) def test_get_should_successfully_return_the_requested_pdf(self, get_file_mock): response = self.client.get(f'/api/v1/path/to/file/abc123.pdf, content_type='application/vnd.api+json') self.assertEqual(response.status_code, status.HTTP_200_OK) # works great self.assertEqual(response['Content-Type'], 'application/pdf') # works great self.assertEqual(response, <abc123.pdf>) # not so great If I do a print to see whats in the response: print(response) <HttpResponse status_code=200, "application/pdf" I am pretty sure I am not setting up the @patch correctly. Specifically, this: status.HTTP_200_OK, 'application/pdf' I've seen a lot of posts about reading or opening files, but I just need to make sure it was in fact a pdf (file) that was returned. How can I set my mock up so that I can assert a pdf (file) was returned?