Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to add double filter in admin page add model(foreign field items)
class BodyPart(models.Model): name = models.CharField(max_length=100) class Exercise(models.Model): name = models.CharField(max_length=200) body_part_primary = models.ForeignKey(BodyPart, on_delete=models.CASCADE) class ExerciseTracker(models.Model): time = models.DateField(auto_now_add=True) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE) In the above code, the Excercise model includes the BodyPart model as a foreign key. While adding a new ExerciseTracker entry on the admin page it shows a drop-down of the foreign key. But How to add a filter for exercise based on BodyPart in ExerciseTracker? So that the field is a double dropdown -
how to get multiply two columns of a row in formset django?
i'm working on a project which admins can write make invoice , every invoice contains several items with different quantities and prices , in order to give right total price i have to make some calculation in the template before save it ! i've made the template and it works fine , but whenever i try to use inlineformset in django , it doesnt make the calculation this is my template {% extends 'base.html' %} {% load widget_tweaks %} {% load static %} {% block title %} create new invoice {% endblock %} {% block content %} <form method="POST">{% csrf_token %} {{items.management_form}} <div class="w-full md:w-11/12 mx-auto realative p-2 bg-gray-200 invoice" style="direction: ltr !important;"> <div class="p-1 pr-2 pb-1 text-xs border border-black rounded-lg flex flex-wrap"> <div class="flex w-8/12 lg:w-9/12"> <div class="w-10/12 ml-8 border-b border-gray-600 border-dotted"> {{form.customer | add_class:'bg-transparent w-full text-right focus:outline-none'}} </div> <div class=""> : ناو </div> </div> </div> <!-- table --> <div class="mt-1 border border-black"> <!-- header --> <div class="flex flex-wrap grayBG text-sm text-white"> <div class="w-1/12 text-center border-r"> <i class="fas fa-cog"></i> </div> <div class="w-2/12 border-r text-center"> total price </div> <div class="w-2/12 border-r text-center"> discount </div> <div class="w-1/12 border-r text-center"> cash </div> <div class="w-1/12 border-r text-center"> loan </div> <div class="w-1/12 border-r text-center"> … -
Jquery autocomplete two fields doesn't work
I'm using jquery to autocomplete form field in django template. Problem is, after adding second function both of them aren't working. How to write it properly? var cities = {{cities|safe}}; $( function() { $("#id_city").autocomplete({ source: cities, }); var categories = {{categories|safe}} $( function() { $("#id_category").autocomplete({ source: categories, }); -
Django Rest Framework and existing forms
I have an existing application with some rather complicated forms already written. I'm asked to add an API (will be using Django-Rest-Framework) for a lot of those forms. Is there any way to cleanly use the existing forms I have to validate the Serializers using the existing forms validation I've already written ? According to the documentation, DRF uses an entirely different validation system that the one I currently have (form validation and model validation). I do not want to write the same validation twice (one for the API, other for the Serializers). I'm thinking of submitting the forms in the ModelSerializer.validate method, but this feels more of dirty hack than clean development to me since DRF does seems to want to be decoupled from Django form system. Any idea on this ? -
Inserting 200 rows of dataframe in the Django models takes like 7 seconds. Is there anyway i can speed up the process?
for transaction in df.itertuples(): transaction_obj = Transactions() transaction_obj.portfolio = strategy.portfolio transaction_obj.strategy = strategy transaction_obj.transaction_price = transaction.TransactionPrices transaction_obj.time_stamp = transaction[0] transaction_obj.transaction_type = name transaction_obj.brokerage = transaction.Brokerage if name == Transactions.LONG: if transaction.EntryLong: transaction_obj.action = Transactions.BUY if transaction.ExitLong: transaction_obj.action = Transactions.SELL elif name == Transactions.SHORT: if transaction.EntryShort: transaction_obj.action = Transactions.SELL if transaction.ExitShort: transaction_obj.action = Transactions.BUY transaction_obj.save() my code here works all fine with no problem. I just want to reduce the execution time. Currently it takes like 7 seconds to insert around 180 lines of row. I am using "Postgresql" database -
Stream framework with django redis celery
I have followed stream framework conf but still getting error like int has no items , pinmanager is not json serialised can any one say version of redis ,celery and conf setting so that i can setup -
unable to query for a specific "user subscription" in django
I'm creating a django ecommerce site; This site "sells" digital items. I'm unable to fetch a specific " user subscription", meaning a user has bought this digital item and I want to display it in a template. in this case I'm interested in displaying the "plan_name" (from subscription model), "created_date" and "expiry_date" in the template for a specific user but somehow I'm unable to. Hereunder the code: models.py class Subscription(models.Model): plan_name = models.CharField(max_length=50, null=True, blank=True, verbose_name="Subscription Plan Name") description = models.TextField(verbose_name="Subscription Plan Description") price = models.FloatField(verbose_name="Subscription Plan Price") start_date = models.DateTimeField(auto_now=False, auto_now_add=False, verbose_name="Subscription Plan Start Date") end_date = models.DateTimeField(auto_now=False, auto_now_add=False, verbose_name="Subscription Plan End Date") active = models.BooleanField(default=False) class Meta: verbose_name = "Subscription" verbose_name_plural = "Subscriptions" def __str__(self): """Unicode representation of Subscription""" return " Subscription type: {}, Description: {}, Price: {}, Is active: {}".format( self.plan_name, self.description, self.price, self.active ) class UserSubscription(models.Model): user = models.ForeignKey(User, related_name= 'tosubscriptions', on_delete=models.CASCADE, null=True, blank=True) subscription = models.ForeignKey("Subscription", related_name = 'tosubscriptions',on_delete=models.CASCADE, null=True, blank=True) created_date = models.DateTimeField(auto_now_add=True, verbose_name="Created Date") expiry_date = models.DateTimeField(auto_now=False, auto_now_add=False, verbose_name="Expiry Date") is_canceled = models.BooleanField(default=False, verbose_name="Is Canceled") cancel_date = models.DateTimeField(auto_now=False, auto_now_add=False, blank=True, null=True) class Meta: verbose_name = "User Subscription" verbose_name_plural = "User Subscriptions" def __str__(self): """Unicode representation of UserSubscription""" return "PK: [{}] Subscription of: {}, … -
MultiValueDictKeyError at /api/register/ Django API
I'm trying to connect my API to my frontend so I have read about Ajax but it receive this error. My API work perfectly on Postman. My URL for this API is http://127.0.0.1:8000/api/register/. File "C:\Users\vinhv\Dropshipping-e-commercial-website\home\views.py", line 176, in post password = user["password"] Django 3.1.4 Python 3.8.2 Here is my API view: class RegisterView(generics.GenericAPIView): serializer_class = AccountRegisterSerializer def post(self, request): user = request.data password = user["password"] salt = bcrypt.gensalt() # Generate a salt for hashing password hashed = bcrypt.hashpw(password.encode('utf8'),salt) user["salt"] = salt.decode("utf8") user["password"] = hashed.decode("utf8") serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data del (user_data['salt']) return Response(user_data, status=status.HTTP_201_CREATED) Here is my HTML: <div class="col-lg-6 col-md-6"> <div class="account_form register" data-aos="fade-up" data-aos-delay="200"> <h3>Register</h3> <form action="http://127.0.0.1:8000/api/register/" method="post"> {% csrf_token %} <div class="default-form-box mb-20"> <label>Email address <span>*</span></label> <label> <input type="text" id="email"> </label> </div> <div class="default-form-box mb-20"> <label>Username<span>*</span></label> <label> <input type="text" id="username"> </label> </div> <div class="default-form-box mb-20"> <label>Passwords <span>*</span></label> <label> <input type="password" id="password"> </label> </div> <div class="register_submit"> <button id="register_btn" type="submit" value="register">Register</button> </div> <script> $('#register_btn').click(function () { var email = $('#email').val(); var username = $('#username').val(); var password = $('#password').val(); console.log(email); console.log(username); console.log(password); var form = $(this).closest("form") $.post({ url: "http://127.0.0.1:8000/api/register/", data: user, dataType:'json', success: function (response) { if(response == '201'){ console.log("Register Success") }else{console.log("Email already exist") } } });}) … -
Django channels working with WS:// but not with WSS://
I followed explanations from django-channels tutorial and was able to run a chat locally. However, it does not work in production. Here is the output from debugger : WebSocket connection to 'wss://www.example.com/ws/chat/lobby/' failed: Error during WebSocket handshake: Unexpected response code: 404 (anonymous) @ (index):23 (index):40 Chat socket closed unexpectedly chatSocket.onclose @ (index):40 (index):56 WebSocket is already in CLOSING or CLOSED state. document.querySelector.onclick @ (index):56 document.querySelector.onkeyup @ (index):47 Here is the javascript I use to try having it work with our https website : const roomName = JSON.parse(document.getElementById('room-name').textContent); var loc = window.location; var wsStart = 'ws://'; if (loc.protocol === 'https:') { wsStart = 'wss://' } const chatSocket = new WebSocket( wsStart + window.location.host + '/ws/chat/' + roomName + '/' ); I use redisgreen for redis : CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('redis://:xxxxxxx@great-whale-0077a76ca7.redisgreen.net:11042/')] }, }, } The rest of the code is as per the tutorial. I am not sure how I should address this issue. Any clue ? Is it required to implement Daphne to run channels in production ? Or did I do something wrong ? Thanks a lot for your help. -
Django rest and ManyToMany through model
I'm trying to build a basic CRUD api that will return the nutrients of a recipe. models.py class Ingredient(models.Model): name = models.CharField(max_length=100) kcal = models.FloatField(null=True) carb = models.FloatField(null=True) sugar = models.FloatField(null=True) protein = models.FloatField(null=True) class Recipe(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey(User, related_name="recipes", on_delete=models.CASCADE, null=True) ingredients = models.ManyToManyField(Ingredient, through='RecipeIngredient', blank=True) class RecipeIngredient(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) amount = models.FloatField(null=True) The basic functionality of creating and viewing ingredients and recipes is already implemented, but how do I implement the many-to-many relationship including the ingredient amount into serializers, views and urls? And maybe as a bonus; how does the http request look like to test that functionality? Even a nudge towards the right literature would be much appreciated, thanks in advance. -
Replacing response output messages with some code(say Msg007) and translate them when we hit api in django
I need each of my API method output messages into some code(say Msg112) and all those codes should be in single file. And I should replace those output messages with that code. And if I hit some API, the relevant output message should come as translated message. I tried using django-admin makemessages and compile messages command but this is not working. -
Django model with @classmethod testing
I have some problem with my model testing. I have model . > class Reminder(models.Model): > STATUS = ( > (1, 'Active'), > (2, 'Archived'), > (3, 'Deleted'), > ) > user = models.ForeignKey(User, on_delete=models.CASCADE) > title = models.CharField(max_length=64, blank=False) > text = models.CharField(max_length=256) > date_create = models.DateTimeField(auto_now_add=True, verbose_name="Reminder was created") > date_start = models.DateField() > date_finish = models.DateField() > time_reminder = models.TimeField() > day_of_week = models.ManyToManyField(DayOfWeek) > status = models.IntegerField(choices=STATUS, default=1) def __str__(self): return r'{} --> {}'.format(self.title, dict(self.STATUS).get(self.status)) @classmethod def from_db(cls, db, field_names, values): instance = super().from_db(db, field_names, values) instance._loaded_values = dict(zip(field_names, values)) return instance def clean(self): super(Reminder, self).clean() start = self.date_start finish = self.date_finish now = datetime.datetime.now().date() if not self._state.adding: if self._loaded_values['status'] == 2 and self.status == 1: if start < now: raise ValidationError('Updating: Date start has to be grater current date.') Everything works fine but tests. def test_Model_test_create_rem_start_gt_now(self): reminder2 = Reminder.objects.create( user=self.user, title='title2', text='text2', date_start=datetime.datetime.strptime('18 Sep 2020', '%d %b %Y'), date_finish=datetime.datetime.strptime('19 Sep 2021', '%d %b %Y'), time_reminder=self.time ) reminder2.refresh_from_db() # tried this try: reminder2.full_clean() except ValidationError as err: self.assertEqual(err.messages[0], ' ') I have error ERROR: test_Model_test_create_rem_start_gt_now (myrem.tests.ReminderTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/cat/ProjectsGit/ProjectReminder/Reminder/myrem/tests.py", line 71, in test_Model_test_create_rem_start_gt_now reminder2.full_clean() File "/home/cat/ProjectsGit/NewReminder/venv/lib/python3.8/site-packages/django/db/models/base.py", line 1216, in full_clean self.clean() … -
Django not loading style file from static directry
I am facing a strange issue with the Django application on my local, the file is available in the static directory. The following is in the settings.py STATIC_ROOT = SITE_ROOT + '/static/' STATIC_URL = '/static/' this is how I am trying to include style file <link href="/static/msc.css?v=1.2" rel="stylesheet" type="text/css" /> the following is added in urls.py from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() The file exist in the static directory, but it is not loading, I am facing a 404 error in console for the URL: http://localhost:8000/static/msc.css?v=1.2 please help me in this regard thanks. -
I want to use jQuery, popover and BootStrap 5 in my project what should be the correct sequence here?
I am using BootStrap version 5.0.0 beta-2, I'm trying to add button dynamically in my popover which I can't. I've included scripts in the following order: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script> My code to update popover is like this: // Updating Popover function updatePopover(cart) { popStr = ""; i = 1; popStr = popStr + "<div class='my-2 mx-1'>"; for (item in cart) { popStr = popStr + "<b>" + i + ". </b>"; popStr = popStr + document.getElementById('name' + item).innerHTML + " | <b>Qty:</b> " + cart[item] + "<br>"; i += 1; } // Adding Clear Cart and Checkout buttons popStr = popStr + "</div> <a href='/shop/checkout'><button class='btn btn-primary' id='checkout'>Checkout</button></a> <button class='btn btn-primary' id='clearCart' onclick='clearCart();'>Clear Cart</button>"; console.log(popStr); // Getting popcart by ID var popcart = document.getElementById('popcart') // Enabling popover var popover = new bootstrap.Popover(popcart, 'data-bs-content') // Setting new value of popcart popcart.setAttribute('data-bs-content', popStr); // Showing the popover popover.show(); } My HTML division is like this: {% for i in product %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card align-items-center" style="width: 18rem; border: 0px;"> <img src="/media/{{i.product_img}}" class="card-img-top" alt="{{i.product_name}}"> <div class="card-body text-center"> <h6 class="card-title" id="namepid{{i.id}}">{{i.product_name}}</h6> <p class="card-text">{{i.product_desc|slice:":25"}}{% if i.product_desc|length > 25 %}...{% endif %}</p> <span id="divpid{{i.id}}" class="divpid"> <button … -
Display user by filtering database in Django
I have two types of users in my model. And I am trying to get only one type of user to display on my HTML page. I am new to Django, so I am having some small problems. And place try to explain in a comment This is my models.py file: class CustomKorisnici(AbstractUser): MAJSTOR = '1' KORISNIK = '2' USER_TYPE_CHOICE = ( (MAJSTOR, 'majstor'), (KORISNIK, 'korisnik') ) user_type = models.CharField(max_length=100,blank=True,choices=USER_TYPE_CHOICE) username = models.CharField(max_length=100,unique=True) last_name = models.CharField(max_length=100) first_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=100) profile_image = models.ImageField(null=True, upload_to="images/", default='korisnici/static/post_user/images/profile_image.png') is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) email = models.EmailField(max_length=100,unique=True) bio = models.TextField(default=" ") After this a setup my view.py file for filtering data from the database: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, TaskCategory,CustomKorisnici from .forms import PostForm, updatePost from django.urls import reverse_lazy,reverse from django.http import HttpResponseRedirect class MajstoriView(ListView): model = CustomKorisnici context_object_name = 'majstori' template_name = 'majstori_view.html' # html stranica na kojoj ce podaci biti prikazani def get_queryset(self): # get_queryset biblioteka iz paythona return CustomKorisnici.objects.filter(user_type="MAJSTORI") A setup URL after that: from django.urls import path from . import views from .views import MajstoriView urlpatterns = [ … -
Setting up site-specific static folders with Django Sites
I am using Django Sites. I want to be able to have site-specific templates and static files. My current directory structure is: ├── site_a │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py ├── site_b │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py └── templates ├── site_a │ ├── _navbar.html │ ├── home.html │ └── signup.html └── site_b ├── _navbar.html ├── home.html └── signup.html I know that I can move templates inside the site_x directory if I declare it as an app in INSTALLED_APPS. Is there another way to tell Django to use templates in site_a/templates without declaring site_a as an app? Also, I would also like to have site specific static files that are not placed in the project STATIC_ROOT so that my tree actually looks like: . ├── site_a │ ├── __init__.py │ ├── settings.py │ ├── static │ │ ├── css │ │ └── js │ ├── templates │ │ ├── _navbar.html │ │ └── home.html │ ├── urls.py │ ├── views.py │ └── wsgi.py └── site_b ├── __init__.py ├── settings.py ├── static │ ├── css │ └── js ├── templates │ ├── _navbar.html … -
django "ATOMIC_REQUESTS" 'Lost connection to MySQL server during query'
I found a strange phenomenon. When I added ATOMIC_REQUESTS:True to the database in the settings, django crashed when connecting to MySql. It kept prompting "Lost connection to MySQL server during query". Change ATOMIC_REQUESTS to False and it can be used normally. Someone Encountered similar problems? Djano 3.1 Mysql 5.7 centos6.9 -
Django how to conditionally update of field value based on other field value in a different model?
class Details(models.Model): name = models.CharField(max_length=60) group = models.CharField(max_length=60, choices = TopicCategory.choices) class ChoiceOptions(models.TextChoices): YES = 'YES', _('Yes') NO = 'NO', _('No') NA = 'NA', _('Na') class MakeAChoice(models.Model): myChoice = models.CharField(max_length=60, choices = ChoiceOptions.choices) class DetailsSerializer(serializers.ModelSerializer): class Meta: model = Details fields = ('name','group') class MakeAChoiceSerializer(serializers.ModelSerializer): class Meta: model = MakeAChoice fields = ('mychoice') Here are my models & serializers for the MakeAChoice and Details class. At present, I can make a choice and it gets saved when I fire a POST call. However, I want save my choice only if the value of the 'group' filed is 'Valid'. How do I write the condition for this please? I need to get the field value in the other Model and verify it against a value and only if the condition is true, I want to update the choice in the current model. -
Why the settings module needs a base.py file?
I changed the django configuration file path, and the error is as follows: ModuleNotFoundError: No module named 'app.settings.base'; 'app.settings' is not a package I know it needs a base.py file, why it doesn't work with __init__.py? it's a package with __init__.py -
Django- CSS is not working for other pages such as header tags
I have linked my css file in 'main/static/css/style.css' and my pages are in 'main/templates/main/pages.html'. But the CSS is not working for some pages such as the h2 tag is not taking the style. base.html {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> privacy.html {% extends 'main/base.html' %} {% block content %} <div class="main"> <h1><b>Privacy</b></h1> <div style="height:35px" aria-hidden="true"></div> <div class="text_para"> <h2 class="h2_privacy">Mission</h2> <p>paragraph<p> ....... style.css .main { -ms-flex: 70%; /* IE10 */ flex: 70%; background-color: white; padding: 20px; } .text_para { margin-right: 5%; text-align: justify; } /*heading h2 for privacy page*/ .h2_privacy { color: black; font-family: 'Lucida Calligraphy', sans-serif; } -
Unable to display images inline using Django templates
I am trying to display images inline into mails with Django but it does not work. Here is the line that I use to display the images inline : <img src='http://localhost:8000/static/myproject/media/mypic.jpg' width="125" height="120" style="display: block; border: 0px;" /> I got nothing actually.... Could you help me please ? Thank you very much ! -
pytest-django: Mock settings.DEBUG
To make manual testing easy, I want to create users when the login page gets shown. class LalaLoginView(LoginView): def get(self, request, *args, **kwargs): self.create_users() return super().get(request, *args, **kwargs) @classmethod def create_users(cls): if not settings.DEBUG: return admin = User.objects.update_or_create(username='admin', defaults=dict( is_superuser=True, is_staff=True))[0] admin.set_password('admin') admin.save() My Test: @pytest.mark.django_db def test_create_users_prod(settings): settings.DEBUG=False LalaLoginView.create_users() assert not User.objects.all().exists() But the mocking of settings.DEBUG does not work. In create_users() DEBUG is "True". How to mock settings.DEBUG with pytest-django? -
Docker-compose build error with django and mysql
I trying to build a Django project with docker-compose and MySQL, but when i run the "docker db uses an image, skipping Building with native build. Learn about native build in Compose here: Building web Sending build context to Docker daemon 22.02kB Step 6/6 : COPY . /code/ ---> 2f42d48fb668 Successfully built 2f42d48fb668 Successfully tagged djangonew_web:latest Traceback (most recent call last): File "docker-compose", line 3, in <module> File "compose/cli/main.py", line 80, in main File "compose/cli/main.py", line 192, in perform_command File "compose/metrics/decorator.py", line 18, in wrapper File "compose/cli/main.py", line 369, in build File "compose/project.py", line 521, in build File "compose/project.py", line 503, in build_service File "compose/service.py", line 1131, in build File "compose/progress_stream.py", line 22, in stream_output File "compose/utils.py", line 50, in split_buffer File "compose/utils.py", line 26, in stream_as_text File "compose/service.py", line 1894, in build FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpjwyh07ql' [16684] Failed to execute script docker-compose My Dockerfile: FROM python:3 ENV PYTHONBUFFERD=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ My docker-compose.yml file: version: "3.9" services: db: image: mysql environment: - MYSQL_DB=mysql_test - MYSQL_USER=test - MYSQL_PASSWORD=test - MYSQL_ROOT_PASSWORD=test web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: … -
Configuring django-cachealot with django_tenants
Trying to use django-cachealot with django_tenants. I get the following error right at the start. Anyone got a resolution? (cachalot.W003) Database engine 'django_tenants.postgresql_backend' is not supported by django-cachalot. HINT: Switch to a supported database engine. -
Is there a way to avoid patching IPython embed when patching sockets?
In my Django test suite, I typically use from IPython import embed; embed() in a test to debug when working locally. I have a mixin class that I use to patch all socket connections to avoid outgoing API calls as such: class ServicesTestMixin(object): @classmethod def setUpClass(cls): # Patch all network known issues mock_obj = patch('socket.socket.connect').start() mock_obj.side_effect = Exception('TESTS TRIED TO ACCESS SOCKET NETWORK!') mock_obj = patch('socket.socket').start() mock_obj.side_effect = Exception('TESTS TRIED TO ACCESS SOCKET NETWORK!') return super().setUpClass() I use it like this: from django.test.testcases import TestCase class MyTestCase(ServicesTestMixin, TestCase): def test_example(self): hello = True from IPython import embed; embed() self.assertTrue(hello) The issue is that now when I call from IPython import embed; embed() in a test the exception is raised because embed() is opening up a socket connection. Is there a way to circumvent or workaround this? Perhaps a way to monkey patch all connections except this embed one?