Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can this query be expressed in Django?
Apologies for the lack of conciseness in formulating this question - part of the problem is that I'm not a database expert and am unsure of the proper terminology for what I'm trying to do. I have the following set of models (simplified and renamed for the purpose of this question). A lot of other functionality has already been built on top of them so wholesale changes aren't possible, though small tweaks could be. class Customer(models.Model): # Company-specific ID format, used everywhere customerId = models.CharField(primary_key=True, max_length=9) name = models.CharField() email = models.CharField() ... class Trip(models.Model): """An event that customers may sign up for - think of a coach tour around Italy, for example.""" name=models.CharField() description=models.CharField() ... class Product(models.Model): """Anything that Customers can buy. This could be as significant as a hotel booking, or as small as a branded keyring.""" # All the Products we're concerned about here have codes, but there do # exist in the database some ad-hoc pseudo-products that don't. code = models.CharField(unique=True, null=True) ... class Payment(models.Model): # Various fields to do with banking, financial tracking, etc. The # relevant one for us is: is_paid = models.BooleanField(default=False) class Purchase(models.Model): """The fact of a Customer buying a Product""" # … -
Django , save_model , admin
okay the issue i am facing is that i am being able to add and save a user , no problem in that and once created , than i can easily assign therapist to that user again no problem , the problem arises when i try to assign the user with a therapist while creating the user , i am realy not getting that where am i making the mistake i mean , i have this feeling that i am assigning things to the user before even creating it but i cant find out which block of code is doing so or maybe just maybe the save_model is working in such a manner that that block code or block of codes need to be rearranged , kindly guide me def save_model(self, request, obj, form, change): # If this is an existing instance and ending is set, prevent changing treatment_therapist if change and obj.client_current_status in UserJourneyStatus.ending_status() and 'treatment_therapist' in form.changed_data: return # Don't save the change to treatment_therapist if 'treatment_therapist' in form.changed_data: # If this is the first time assigning a therapist if not obj.therapist_assigned_at and obj.treatment_therapist: obj.therapist_assigned_at = now() # If changing to a new therapist, update the assignment date … -
Managing Database Connections in a Microservice Architecture with Django
I am designing a microservice architecture using Django and I have encountered a major challenge in data management. I would appreciate it if you could share your experience and perspective. We have several separate services, each with its own database. For example: Core service: Responsible for managing core models such as User and uses the db_core database. WebSocket service: Responsible for managing real-time communications and uses the db_websocket database. Main challenge: How can we best manage the data connection between these two services? This challenge has two aspects: Read Access: The WebSocket service needs to read information from the User model of the Core service to authenticate the user (when connecting) or display his information (for example, the user's name next to a chat message). What is the correct approach for this? Managing Cross-Database Relationships: This challenge is more complex. Suppose we have a ChatMessage model in the WebSocket service that requires a ForeignKey to the User model in the Core service. Since it is not possible to create a FOREIGN KEY constraint between two physical databases, what is the recommended pattern for implementing this logical relationship? -
Telegram OAuth with django
im trying to integrate telegram oauth into my application, currently it successfully log in in telegram, but django doesnt received any data in callback, I have tryied many methods, but without any results views.py def telegram_callback(request): data = request.GET.dict() print('Telegram callback data:', data) if not verify_telegram_auth(data): return HttpResponseBadRequest("Invalid Telegram auth") telegram_id = data["id"] username = data.get("username", f"tg_{telegram_id}") first_name = data.get("first_name", "") last_name = data.get("last_name", "") user, created = User.objects.get_or_create( username=f"tg_{telegram_id}", defaults={ "first_name": first_name, "last_name": last_name, }, ) print(user, telegram_id) login(request, user) return HttpResponseRedirect(reverse("home")) urls.py path("telegram/login/", views.telegram_callback, name="telegram"), and my html <div class="w-full flex justify-center mb-3"> <script async src="https://telegram.org/js/telegram-widget.js?22" data-telegram-login="bot_username" data-size="large" data-radius="12" data-onauth="onTelegramAuth(user)" data-userpic="true" data-lang="en" data-auth-url="{% url 'users:telegram' %}" data-request-access="write"> </script> </div> -
Django project assistance [closed]
When I am creating a new Django project on PyCharm and Choosing to create it in a new enviornment using virtualenv Inheriting all global site packages and making available to all projects Choosing template language Django, template folder templates and application name Manovijay Why does the structure of the new project created not involve the folder named development? -
Best practices for structuring Django REST APIs for maintainability and scalability
I am building a Django-based backend for an e-commerce project with multiple models and REST API endpoints. I want to follow clean architecture and maintainability best practices. How should I structure views, serializers, and URLs for scalability and easier debugging? Tags: Python, Django, REST-API, Backend -
looking for face recognition and validation for registration
We’re building a registration flow where users upload a face image (stored on S3, backend gets the URL). We need to validate that the image has one clear face and check for possible duplicate faces across existing users; if similarity crosses a threshold, we block auto-approval and send it for admin review. We don’t want to build or train ML models and prefer a managed, production-ready AWS solution. **Currently considering AWS Rekognition ,is this the right approach, or are there better alternatives? techstack-Django,react** -
Django static files settings
In my app i combine Django and FastAPI. So I start my django server this way: from fastapi import FastAPI from django.core.asgi import get_asgi_application app = FastAPI() app.mount("/dj", get_asgi_application()) But when i open Django Admin panel i get many errors like: "GET /dj/static/admin/css/dashboard.css HTTP/1.1" 404 Not Found. How should i configure Django static files to get proper Admin panel? -
How do I create a Django ListView with FormMixin?
I have a working ListView with template. I want to filter the list based on the contents of a form, something like: class SampleListView(FormMixin, ListView): model = Sample paginate_by = 15 form_class = LookupForm def get_queryset(self): samples = Sample.objects.all() # filter based on validated form contents form = self.get_form() if form.is_valid(): samples = samples.filter(some_property__gte=form.cleaned_data['sample_number']) return samples class LookupForm(forms.Form): sample_number = IntegerField(widget=NumberInput) The template shows the form as: <form action="" method='get'> {% csrf_token %} {{ form.as_p }} <input type='submit' value='Query samples'> </form> This renders the page with my list and form, but the form always seems to be invalid. How can I integrate the validated form with my ListView? Is this the Avoid anything more complex? That is, should I just not be trying to put the FormMixin and ListView together? -
For files uploaded via Django, how can I use them with libraries that require a hard file path to the file?
I am currently working on a text extraction component of my Django backend, which intends to extract text from urls (working), pure text (working), and files (.pdf, .doc, .ppt, .md, .txt, .html). My current code works for hardcoded file paths to valid file inputs: def extract_from_file(uploaded_file): file_type = os.path.splitext(uploaded_file.name)[1].lower() if file_type == ".pdf": text = pdf_to_text(uploaded_file) elif file_type in [".doc", ".docx", ".docm", ".dot", ".dotx", ".dotm"]: text = doc_to_text(uploaded_file) elif file_type in [".ppt", ".pptx", ".pps", ".ppsx"]: text = ppt_to_text(uploaded_file) elif file_type in [".md", ".html", ".htm"]: text = html_to_text(uploaded_file, file_type) elif file_type == ".txt": # adapted from https://www.geeksforgeeks.org/pandas/read-html-file-in-python-using-pandas/ with open(uploaded_file, "r", encoding="utf-8") as f: text = f.read() else: raise ValueError("Unsupported file type: " + file_type) if text: return article_from_text(text) else: raise ValueError("No text could be extracted from the file.") def pdf_to_text(file): reader = PdfReader(file.file) return "".join([page.extract_text() for page in reader.pages]) def doc_to_text(file): document = Document() document.LoadFromFile(file) text = document.GetText() document.Close() return text def ppt_to_text(file): presentation = Presentation() presentation.LoadFromFile(file) sb = [] # Loop through all slides and extract test to sb list - O(n^3) - maybe better way to do later? - quite slow # based on https://github.com/eiceblue/Spire.Presentation-for-Python/blob/main/Python%20Examples/02_ParagraphAndText/ExtractText.py for slide in presentation.Slides: for shape in slide.Shapes: if isinstance(shape, IAutoShape): for tp in … -
Should a single API call handle everything to make life of frontend easy, or there be as many apis as needed [closed]
So I face this issue often. Apart from being a backend python dev, I also have to handle a team consisting of frontend guys as well. We are into SPAs, and a single page of ours sometime contain a lot of information. My APIs also control the UI on the frontend part. For example, a single could contain. Order Detail Buttons that will be displayed based on role. like a staff can only see the order, whereas a supervisor can modify it. And like this sometime there are even 10 of such buttons. Order metadata. Like a staff will only see the order date and quantity whereas manager can also see unit and sale cost. Also, let's say there is something like order_assigned_to, then in that case I will also send a list of eligible users to which order can be assigned. (In this particular case, i can also make one more API "get-eligible-users/<order_id>/". But which one is preferred. Somehow, my frontend guys don't like many APIs, I myself has not worked that much with next, react. So, I do what they ask me for. Generally what is preferred ? My APIs are very tightly coupled , do we take … -
Python as a backend developer [closed]
Hey developers i am currently working in small startup company as a backend developer using python language , i want some suggestions like backend devs on which things they have to focus more. -
django backend is good shoes to learn now?
I have some experience with Python, and I’m interested in backend development. Is Django still a good choice to learn in the current job market? I’m particularly interested in its relevance for modern web applications and career opportunities compared to other backend frameworks. -
DRF unable to find existing model item in API
I am creating an API with Django Rest Framework and I keep encoutering an issue where i am unable to pull a single item from my django model on the browser. I have two endpoints one that gets the consumer by id and the other that gets ll the consumers. The one that gets all the consumers works fine and I am able to load the onto the browser but when it comes to grabbing the a single item but id which is a UUID it seems to fail or more so it keeps hitting a 404. I have checked that the id exists in the DB and there are entries there Just to point out this is all dummy data Views.py @api_view(["GET"]) def get_power_consumer_by_id(request, power_consumer_id): power_consumer = get_object_or_404(PowerConsumer, id=power_consumer_id) serializer = PowerConsumerSerializer(power_consumer) return Response( serializer.data, status=status.HTTP_200_OK ) @api_view(["GET"]) def get_power_consumer(request): if request.method == "GET": try: power_consumer = PowerConsumer.objects.all() serializer = PowerConsumerSerializer(power_consumer, many=True) return Response(serializer.data, status=status.HTTP_200_OK) except Exception: return Response( {"error": "Failed to get power consumer data"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR ) Url Patterns urlpatterns = [ path("v1/power_consumer/<uuid:power_consumer_id>/", get_power_consumer_by_id), path("v1/power_consumer/", get_power_consumer) ] JSON Response [{"id":"bbbbbbb2-bbbb-bbbb-bbbb-bbbbbbbbbbbb","account_number":"PC-0002","billing_mode":"MANUAL_INVOICE","billing_cycle":"MONTHLY","billing_day_of_month":20,"billing_time":"02:00:00","predicted_bill_kobo":1200000,"deficit_amount_kobo":0,"is_at_risk":false,"next_billing_at":"2026-02-20T02:00:00Z","last_billed_at":"2026-01-20T02:00:00Z","supplier":"aaaaaaa1-aaaa-aaaa-aaaa-aaaaaaaaaaaa"},{"id":"bbbbbbb3-bbbb-bbbb-bbbb-bbbbbbbbbbbb","account_number":"PC-0003","billing_mode":"AUTO_CHARGE","billing_cycle":"WEEKLY","billing_day_of_month":null,"billing_time":"02:00:00","predicted_bill_kobo":300000,"deficit_amount_kobo":50000,"is_at_risk":true,"next_billing_at":"2026-01-29T02:00:00Z","last_billed_at":"2026-01-22T02:00:00Z","supplier":"aaaaaaa1-aaaa-aaaa-aaaa-aaaaaaaaaaaa"},{"id":"bbbbbbb4-bbbb-bbbb-bbbb-bbbbbbbbbbbb","account_number":"PC-0004","billing_mode":"MANUAL_INVOICE","billing_cycle":"BIWEEKLY","billing_day_of_month":null,"billing_time":"02:00:00","predicted_bill_kobo":800000,"deficit_amount_kobo":150000,"is_at_risk":false,"next_billing_at":"2026-01-28T02:00:00Z","last_billed_at":"2026-01-14T02:00:00Z","supplier":"aaaaaaa1-aaaa-aaaa-aaaa-aaaaaaaaaaaa"},{"id":"bbbbbbb5-bbbb-bbbb-bbbb-bbbbbbbbbbbb","account_number":"PC-0005","billing_mode":"AUTO_CHARGE","billing_cycle":"DAILY","billing_day_of_month":null,"billing_time":"02:00:00","predicted_bill_kobo":45000,"deficit_amount_kobo":0,"is_at_risk":false,"next_billing_at":"2026-01-26T02:00:00Z","last_billed_at":"2026-01-25T02:00:00Z","supplier":"aaaaaaa1-aaaa-aaaa-aaaa-aaaaaaaaaaaa"}] Model Code class PowerConsumer(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) supplier = models.ForeignKey(PowerSupplier, on_delete=models.CASCADE) account_number = models.CharField(max_length=100, unique=True) billing_mode … -
Unsure if I can learn Django [closed]
I have just completed Python fundamentals recently covering lists, tuples, dictionaries, basic OOP etc. However, I'm not certain whether it's the right time for me to dive into Django. -
Django-axes seems to ignore ipware settings behind Nginx
I'm struggling to set up my django-axes behind Nginx reverse proxy to take the HTTP_X_FORWARDED_FOR instead REMOTE_ADDR. I've tried all three variations as outlined here: https://django-axes.readthedocs.io/en/latest/4_configuration.html. I've tried setting the ipware fields in isolation as well as in combinations. Left-most and right-most also didn't make any difference., ip_address from Axes' attempts was always populated with REMOTE_ADDR. I'm 100% sure that request.META contains both HTTP_X_FORWARDED_FOR as well as REMOTE_ADDR. I checked this by inserting a debugging middleware in front of axes. My logs show that both values are valid and I can manipulate the IP logged by Axes by modifying REMOTE_ADDR in my middleware: class OverwriteRemoteAddrMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): logger = logging.getLogger('django.request') xff = request.META.get('HTTP_X_FORWARDED_FOR') logger.info(f"[Middleware] Before: HTTP_X_FORWARDED_FOR={xff}, REMOTE_ADDR={request.META.get('REMOTE_ADDR')}") # Set REMOTE_ADDR to a fixed unrelated value for testing request.META['REMOTE_ADDR'] = None logger.info(f"[Middleware] After: REMOTE_ADDR={request.META['REMOTE_ADDR']}, X-Forwarded-For={xff}") return self.get_response(request) This is my full settings.py that I'm currently using in a minimal django test project: """ Django settings for django_test project. Generated by 'django-admin startproject' using Django 6.0.1. """ from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-a8_oxq6w3m()1fh)%)srfm!prh_#4tsp3(kc2+37_@krm_++$%' DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'axes', 'app', ] … -
Django: exception in get_catalog()
I have a limited set of LANGUAGES: LANGUAGE_CODE='sl' # It's for locals first of all LANGUAGES=[ ('sl', _('Slovene')), # First is default ('en', _('English')), ('it', _('Italian')), ('de', _('German')), ('ru', _('Russian')), ] But not everything is translated, mainly they're to have additional fields for django_modeltranslation. I've added this line to see what's happening right after "while True" in django/views/i18n.py:get_catalog(): print(translation, translation._fallback) For en_US value in accept_language header, all is fine: <DjangoTranslation lang:en> <gettext.GNUTranslations object at 0x7f07f59cb070> <gettext.GNUTranslations object at 0x7f07f59cb070> <gettext.GNUTranslations object at 0x7f07f59cb0e0> <gettext.GNUTranslations object at 0x7f07f59cb0e0> None For sl_SI all is good as well: <DjangoTranslation lang:sl> None But for de_DE (or ru_RU) it crashes: <DjangoTranslation lang:de> <DjangoTranslation lang:sl> <DjangoTranslation lang:sl> <django_countries.EmptyFallbackTranslator object at 0x7f07f6ccbcb0> <django_countries.EmptyFallbackTranslator object at 0x7f07f6ccbcb0> None Internal Server Error: /jsi18n/ Traceback (most recent call last): File "/home/pooh/venv13/lib/python3.13/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/pooh/venv13/lib/python3.13/site-packages/django/core/handlers/base.py", line 198, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pooh/venv13/lib/python3.13/site-packages/django/views/generic/base.py", line 106, in view return self.dispatch(request, *args, **kwargs) ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/pooh/venv13/lib/python3.13/site-packages/django/views/generic/base.py", line 145, in dispatch return handler(request, *args, **kwargs) File "/home/pooh/venv13/lib/python3.13/site-packages/django/views/i18n.py", line 124, in get context = self.get_context_data(**kwargs) File "/home/pooh/venv13/lib/python3.13/site-packages/django/views/i18n.py", line 210, in get_context_data "catalog": self.get_catalog(), ~~~~~~~~~~~~~~~~^^ File "/home/pooh/venv13/lib/python3.13/site-packages/django/views/i18n.py", line 187, in get_catalog for key, value in translation._catalog.items(): ^^^^^^^^^^^^^^^^^^^^ … -
Why won't Django render its select widget with this code
I am trying to use Django's default select widget to render an html dropdown and I just can't seem to figure out what I am doing wrong... here is my models.py class VehicleYear(TimeStampedModel): oem_year = models.IntegerField( unique=True, null=False, blank=False, default=current_year, validators=[ MinValueValidator(1900), max_value_current_year]) here is my forms.py class SelectYear(forms.Form): vehicle_year = forms.ModelChoiceField(queryset=VehicleYear.objects.all(), label="Select Year") here is my views.py def Year(request): context = {'form': SelectYear()} return render(request, 'vehicles/select_year.html', context) here is my html template(select_year.html): {{ form.as_p }} select_year.html is part of select_filter.html and is using {% include "folder/select_year.html" %} -
How to migrate data for email field
So i have a char field which i was using to store emails. Now there are some rule/validation and processes for email fields like email validation and email normalization etc. I have to add the validation and email normalization on the field while keeping in CharField. what is the valid and safe ways to do this? I am using Django and DRF. -
Disable add, edit and delete views and widgets for a custom Wagtail ViewSet index page
I have this Django model: class Player(models.Model): class Meta: verbose_name = _("Player") verbose_name_plural = _("Players") first_name = models.CharField(verbose_name=_("First Name"), blank=False, null=False, max_length=255) last_name = models.CharField(verbose_name=_("Last Name"), blank=False, null=False, max_length=255) email = models.EmailField(verbose_name=_("Email"), blank=False, null=False, max_length=255) uid = models.UUIDField(unique=True, blank=False, null=False, editable=False) objects = PlayerManager() @property def name(self): return f"{self.first_name} {self.last_name}" # Add verbose name for custom property name.fget.short_description = _("Full Name") And this custom ViewSet to display it in the Wagtail Admin interface: class PlayerListViewSet(ModelViewSet): model = Player name = "players" add_to_settings_menu = False add_to_admin_menu = False list_display = ( "name", "email", "uid" ) search_fields = ("first_name", "last_name", "email",) # Disable Player CRUD create_view_enabled = False edit_view_enabled = False delete_view_enabled = False # Disable forms exclude_form_fields = "__all__" # Block CRUD permissions def has_add_permission(self, request): return False def has_edit_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return False def get_index_view_kwargs(self, **kwargs): kwargs = super().get_index_view_kwargs(**kwargs) kwargs["show_add_button"] = False return kwargs The problem is - I don't want the Player models to be created, edited or deleted via the admin interface - only a list view should be accessible. I added attributes above, but the edit/delete and add widgets are still displayed on the page. Is there a way to disable … -
django archive user if clicked for detail page view an error appears
so i have this user model and in admin.py which ofcourse is used by my client as admin page view and recently my client requested that the user/s who has been archived should not show in the active list page of in the django admin ,but can be viewed if filtered so i put the functionality in my base " get_queryset " which is as follow def get_queryset(self, request): qs = super().get_queryset(request) # detecting if archive date filter is applied archive_filter_applied = any( key.startswith("archived_at__") for key in request.GET ) # default behaviour which excludes archived users if not archive_filter_applied: qs = qs.filter(archived_at__isnull=True) if request.user.is_superuser: return qs # permission gate if not request.user.has_perm("api.view_user"): return qs.none() therapist_qs = qs.filter( Q(treatment_therapist=request.user) | Q(assessment_therapist=request.user) ) # data-driven therapist rule if therapist_qs.exists(): return therapist_qs return qs so what happens is as normal the users are shown who are active and not archived but if filter through a filter only those are shown which are archived so till here all is fine but when the archived user is clicked in the list page to see his details page an error appears like this " Client with ID “375” doesn’t exist. Perhaps it was deleted?" i have … -
How can I set up a new string for comments in PyCharm for DTL code in .html file?
In PyCharm we have a convinient way to turn off for a while a part of code by pressing Ctrl+/. Later we can turn it on by pressing the same key combination. However if I am in HTML page the combination Ctrl+/ generates comments <!--some error here-->. It works well in HTML code. But if use DTL (Dynamic Template Language) from Django the comments should be as follows: {% some error code here %}. Is there any way to set up the key combination Ctrl+/ in PyCharm for making the DTL comments i.e. {% some error code here %}? I use PyCharm 2023.1.2 (Community Edition) and Django 5.2.10. -
Designing a flexible relationships model in Django
I'm designing a small Django app, and writing some code snippets to go with the design. I have some simple models in the design, like Person and Book: from django.db import models class Book(models.Model): name = models.CharField(max_length=127) class Person(models.Model): name = models.CharField(max_length=127) I want to be able to express multiple types of relationships between multiple models in the application, as the application grows. In the example above, there are multiple possible types of relationships, for example: a Person is the author of a Book a Person is the editor of a Book a Person is the subject of a Book (e.g. if the book is a biography) a Person is both the author and the subject of a book (e.g. if the book is an autobiography) So I'm thinking of a model that expresses relationship types, like this: from django.contrib.contenttypes.models import ContentType class RelationshipType(models.Model): model_a = models.ForeignKey(ContentType, on_delete=models.PROTECT) model_b = models.ForeignKey(ContentType, on_delete=models.PROTECT) name = models.CharField(max_length=127) The use of ContentType allows me to create relationship types between any pair of models. Finally, I think this is approximately what the relationship would look like (pseudo-code): class Relationship(models.Model): type = models.ForeignKey(RelationshipType, on_delete=models.PROTECT) instance_a_id = models.PositiveBigIntegerField() instance_a = GenericForeignKey("model_a", "instance_a_id") instance_b_id = models.PositiveBigIntegerField() instance_b … -
Mocked Redis counter does not increment between requests for different users
I am testing a Django view that increments recipe view counters using Redis. The logic is: each user can increment recipe views only once different users should increment the counter Redis is mocked using MagicMock The first test passes, and part of the second test passes, but the counter never increments to 2 for the second user, even though I explicitly change mock return values. Django View # recipehub/apps/recipes/views.py from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404, render from recipehub.apps.recipes.models import Recipe from recipehub.redis import r @login_required def recipe_detail(request, slug): recipe = get_object_or_404(Recipe, slug=slug, moderation_status="approved") redis_user_recipe_view_key = f"user:{request.user.id}:recipe:{recipe.id}:view" redis_all_recipe_view_key = f"recipe:{recipe.id}:views" if not r.exists(redis_user_recipe_view_key): r.set(redis_user_recipe_view_key, 1) r.incr(redis_all_recipe_view_key) recipe_views = int(r.get(redis_all_recipe_view_key) or 0) return render( request, "recipes/recipe_detail.html", { "recipe": recipe, "views": recipe_views, }, ) Redis client definition # recipehub/redis.py import redis r = redis.Redis(host="localhost", port=6379, db=0) ** Redis mock fixture** import pytest from unittest.mock import MagicMock @pytest.fixture() def mock_redis(mocker): magic_mock = MagicMock() mocker.patch("recipehub.redis.r", magic_mock) return magic_mock Test 1 — first user increments counter (passes) @pytest.mark.django_db def test_recipe_detail_first_user_view_increments_counter(client, users_list, mock_redis): recipe = RecipeFactory.create(slug="fish", moderation_status="approved") user = users_list["first_simple_user"] mock_redis.exists.return_value = False mock_redis.get.return_value = b'1' mock_redis.incr.return_value = 1 mock_redis.set.return_value = True client.force_login(user) response = client.get( reverse("recipes:recipe-detail", kwargs={"slug": recipe.slug}) ) assertContains(response, '1 views') Test 2 … -
Windows Apache two django projects in separated venv
I need to host two separated apps, with separated venv and separated db, reason cut costs. Both of apps have been developed separately, no I have only single server to host them. core is running on port 80 , portal on 8081 I am able to access both apps at some point of time, remotelly means outside of server. But after some time doesn't matter what port I provide I am able to access only sigle app. Seems static files are served properly as ico is changes, but content is the same so I see portal for example on both ports. nut sure what trigers that and how to prevent it. here are my files. D:\Apache24\conf\httpd.conf Define SRVROOT "d:/Apache24" ServerRoot "${SRVROOT}" Listen 10.192.28.86:80 Listen 10.192.28.86:8081 LoadModule actions_module modules/mod_actions.so LoadModule alias_module modules/mod_alias.so LoadModule allowmethods_module modules/mod_allowmethods.so LoadModule asis_module modules/mod_asis.so LoadModule auth_basic_module modules/mod_auth_basic.so LoadModule authn_core_module modules/mod_authn_core.so LoadModule authn_file_module modules/mod_authn_file.so LoadModule authz_core_module modules/mod_authz_core.so LoadModule authz_groupfile_module modules/mod_authz_groupfile.so LoadModule authz_host_module modules/mod_authz_host.so LoadModule authz_user_module modules/mod_authz_user.so LoadModule autoindex_module modules/mod_autoindex.so LoadModule cgi_module modules/mod_cgi.so LoadModule dir_module modules/mod_dir.so LoadModule env_module modules/mod_env.so LoadModule include_module modules/mod_include.so LoadModule isapi_module modules/mod_isapi.so LoadModule log_config_module modules/mod_log_config.so LoadModule mime_module modules/mod_mime.so LoadModule negotiation_module modules/mod_negotiation.so LoadModule setenvif_module modules/mod_setenvif.so <IfModule unixd_module> User daemon Group daemon </IfModule> ServerAdmin admin@example.com <Directory /> AllowOverride …