Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use composite primary keys in django?
I want to use composite primary keys in django but I can't find a solution, I tried it in different ways, even trying to make an alter in the table but it won't let me, I want to use it based on this model class Contiene(models.Model): id_boleto = models.OneToOneField("Boleto", primary_key=True, on_delete=models.CASCADE) boleto_cdg = models.CharField(default='', max_length=50) # Asegúrate de que este campo sea opcional num_orden = models.ForeignKey("OrdenCompra", on_delete=models.CASCADE) cantidad_total = models.IntegerField() def generate_random_code(self): numbers = ''.join(random.choices(string.digits, k=12)) # Genera 12 números aleatorios letters = ''.join(random.choices(string.ascii_uppercase, k=3)) # Genera 3 letras aleatorias return numbers + letters def save(self, *args, **kwargs): # Si no se ha proporcionado un boleto_cdg, entonces genera uno automáticamente if not self.boleto_cdg: self.boleto_cdg = self.generate_random_code() # Llamar al método save de la superclase para guardar el objeto super(Contiene, self).save(*args, **kwargs) def __str__(self): return f"{self.id_boleto}{self.num_orden}{self.cantidad_total}{self.boleto_cdg}"` Where num_orden and id_boleto would become composite pk, please help!!! I tried different composite key libraries but it gave errors when migrating -
500 Internal Server Error on Django App Deployment on Render.com
I am encountering a persistent 500 Internal Server Error when trying to deploy my Django project on Render.com. The error message is not providing detailed information, and I am struggling to diagnose the issue. Here's the error log from Render: 127.0.0.1 - - [04/Jan/2024:18:01:36 +0000] "GET / HTTP/1.1" 500 145 "-" The project runs fine locally, but the problem occurs when I deploy it to Render. I have configured my settings.py for production as follows (relevant parts shown): # settings.py import os from pathlib import Path import dj_database_url BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = False ALLOWED_HOSTS = ['mydomain.com', 'renderproject.onrender.com'] DATABASES = { 'default': dj_database_url.config(default=os.environ.get('DATABASE_URL')) } # Static files settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # ...other settings... My requirements.txt includes all the necessary packages like Django, gunicorn, psycopg2-binary, whitenoise, etc. I am looking for suggestions on what could be causing this error and how to resolve it. Any insights or debugging tips would be greatly appreciated! --- [[[enter image description here](https://i.stack.imgur.com/9BAjv.png)](https://i.stack.imgur.com/y3M2C.png)](https://i.stack.imgur.com/XwOKC.png)python, django, deployment, render, http-status-code-500 I have tried deploying my Django application on Render.com, expecting it to run as smoothly as it does on my local development environment. The application functions correctly locally, with all views … -
django field local for every user
How can I create a field that is different for every user. For example if we have an instance of a Comment model and there is a field that is different for every user that tells if user has liked that comment. So when I map through the objects i can just check if a user has liked it. Something like a local field for every user. -
403 "detail": "Authentication credentials were not provided."
I have assignment to build API project. I have to create Endpoint: /api/users/users/me/ Role: Anyone with a valid user token Method: GET Purpose: Displays only the current user When testing API endpoint Insomnia and curl return same response: 403 "detail": "Authentication credentials were not provided." Please help! I've tried two methods: Djoser: Using Djoser I managed to create user and generate auth token. I've also created token manually in Django admin panel for several users, including superuser. I've sent Get request to Djoser endpoint http://127.0.0.1:8000/auth/users/me/ using Insomnia and curl. In Insomnia I've chosen Bearer token and entered valid token. Custom View: Endpoint : /api/users/users/me/ I created custom view but still same response. Settings.py (copied related part of settings file) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'LittleLemonAPI', 'rest_framework', 'djoser', 'rest_framework.authtoken', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] DJOSER = { "USER_ID_FIELD" :"username" } REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.DjangoModelPermissions', ], } Project-level urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('LittleLemonAPI.urls')), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.authtoken')), ] Views.py from django.shortcuts import render from django.contrib.auth.models import … -
How to filter objects based on a field in parent model
I want to find the therapist that have visited the patient. my visit model: class visit(models.Model): costumer_name=models.ForeignKey(costumerprofile, on_delete=models.CASCADE) therapist_name=models.ForeignKey(therapistProfiles, on_delete=models.CASCADE, default=1) the first query works fine but it cannot find the matching query for the second one: @property def getthefee(self): costumer = costumerprofile.objects.get(c_name=self.costumer_name) therapist=therapistProfiles.objects.get(name=self.therapist_name) so i used this filtering: therapist=therapistProfiles.objects.distinct().filter(name__contains=str(self.therapist_name)[0:10]) it works fine but when i change the string length to 12 or longer it returns None. Both parent models are the same. -
Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread
*Don't know what the problem is. I am not able to run any of my Django servers. Every time gets the same error. And don't have any idea about this. Tried reinstalling windows, python and all. But still gets same error. ** Don't know what the problem is. I am not able to run any of my Django servers. Every time gets the same error. And don't have any idea about this. Tried reinstalling windows, python and all. But still gets same error. Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Fiqri Ali Sakha\anaconda3\lib\threading.py", line 980, in _bootstrap_inner self.run() File "C:\Users\Fiqri Ali Sakha\anaconda3\lib\threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "C:\Users\Fiqri Ali Sakha\anaconda3\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Fiqri Ali Sakha\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "C:\Users\Fiqri Ali Sakha\anaconda3\lib\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( File "C:\Users\Fiqri Ali Sakha\anaconda3\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Fiqri Ali Sakha\anaconda3\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Users\Fiqri Ali Sakha\anaconda3\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() File "C:\Users\Fiqri Ali Sakha\anaconda3\lib\site-packages\django\urls\resolvers.py", line 494, in check for pattern in self.url_patterns: File "C:\Users\Fiqri Ali Sakha\anaconda3\lib\site-packages\django\utils\functional.py", line 57, … -
Mocking signals function in unit test
I'm using Django version 4.2.6. I have a file, signals.py, that includes a pre-save handler for my entity: def do_stuff(sender, instance, **kwargs): ... stuff... pre_save.connect(do_stuff, sender=MyEntity) ... so that when an instance of MyEntity is either created or updated, the do_stuff() function is executed. How do I mock do_stuff() in unit tests? I have a number of tests that create and update MyEntity instances, so do_stuff() is being called during the execution of the unit test. My implementation of do_stuff() is making a call to an external source amongst other functionality, so I want to mock it when the unit test runs. I have tried declaring the following a part of my unit test: @mock.patch("application.package.signals.do_stuff", autospec=True,) ... but when I execute the test, I can see that do_stuff() is still being executed. -
N+1 query optimization problem with Django custom user
I override the Django's built-in user django.contrib.auth.user and I created app called core for this purpose I override it like this in core/models.py path: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): email = models.EmailField(unique=True) also I changed the corresponds form and django admin. by the way I have store app which is contain several models, but problem is the every model of my store app need to go and create separately query for each user in database. here is my customer and comment model: class Customer(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='customer') and my comments model is: class Comment(models.Model): author = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='comments') body = models.TextField() raiting = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)], blank=True, null=True) I use this query in drf ModelViewSet for catch the comments with it's corresponding author: def get_queryset(self): product_pk = self.kwargs["product_pk"] return Comment.objects.select_related('author__user').filter(product_id=product_pk).all() but in debug toolbar still I have multiple similar queries and here there are: SELECT ••• FROM `core_customuser` WHERE `core_customuser`.`id` = 1 LIMIT 21 7 similar queries. SELECT ••• FROM `core_customuser` WHERE `core_customuser`.`id` = 2 LIMIT 21 7 similar queries. SELECT ••• FROM `core_customuser` WHERE `core_customuser`.`id` = 3 LIMIT 21 7 similar queries. SELECT ••• FROM `core_customuser` WHERE `core_customuser`.`id` = 4 LIMIT 21 7 … -
How to change time input format in Django Admin?
The Django docs describe the use of TIME_INPUT_FORMATS, and say that the formats are described using the Python datetime module syntax. But in Django Admin 4.2 none of the directives - I'm using %H, %M, %I, %p - are making any difference. Instead, both 12-hour and 24-hour time inputs are accepted, with and without leading zeros. How do I gain control over the format, preferably without altering admin templates? Here are the other relevant settings: settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Denver' USE_TZ = True USE_I18N = False There's the input_formats argument for DateTimeField, but that includes date formats, and I need just the time formats separately (for a Django Admin detail view of an object that has a datetime field). There's also another question about display of times that looks interesting, but I'm concerned now with time input. -
why do links and css styles work in python 3.9 and not work in python 3.12?
Can someone tell me why python version 3.9 imports these css styles and runs the interactive page and in wesrja 3.12 I get the error TemplateDoesNotExist at /includes/stylesheets.html ? {% load static %} <link href="{% static 'css/vendors.bundle.css' %}" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Roboto+Slab:100,300,400,700" rel="stylesheet"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css"> <link href="https://cdnjs.cloudflare.com/ajax/libs/tag-it/2.0/css/jquery.tagit.min.css" rel="stylesheet" type="text/css"> <link href="{% static 'css/styles.bundle.css' %}" rel="stylesheet" type="text/css"> <link rel="stylesheet" type="text/css" href="{% static 'css/toastr.min.css' %}"> I have diagnosed the problem and the fault lies in the python version, on version 3.11.7 it also does not import the stylesheet.html file. It is a total code from the Internet, which I want to adapt for my site but well it can't be done -
How to use if else statement to apply filter in subquery
I have this code (this is simplified example, but I have much more complicated query to apply this knowledge) #models.py class Post(models.Model): name = models.CharField(max_length=255) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) number = models.IntegerField() Then I populated the DB: """shell post_a = Post.objects.create(name="post_a") post_b = Post.objects.create(name="post_b") # POST a comments comment_with_number_1 = Comment.objects.create(post=post_a, number=1) -- "post_a" 1 comment_with_number_1 = Comment.objects.create(post=post_a, number=1) -- "post_a" 1 comment_with_number_2 = Comment.objects.create(post=post_a, number=2) -- "post_a" 2 POST b comments comment_with_number_1 = Comment.objects.create(post=post_b, number=1) -- "post_b" 1 comment_with_number_1 = Comment.objects.create(post=post_b, number=1) -- "post_b" 1 comment_with_number_1 = Comment.objects.create(post=post_b, number=1) -- "post_b" 1 comment_with_number_1 = Comment.objects.create(post=post_b, number=1) -- "post_b" 1 comment_with_number_1 = Comment.objects.create(post=post_b, number=1) -- "post_b" 1 comment_with_number_1 = Comment.objects.create(post=post_b, number=1) -- "post_b" 1 comment_with_number_1 = Comment.objects.create(post=post_b, number=1) -- "post_b" 1 comment_with_number_1 = Comment.objects.create(post=post_b, number=1) -- "post_b" 1 comment_with_number_1 = Comment.objects.create(post=post_b, number=1) -- "post_b" 1 comment_with_number_1 = Comment.objects.create(post=post_b, number=1) -- "post_b" 1 """ #views.py queryset = Post.objects.all() if OuterRef("name") == Value("post_a"): else_if_filters = Q(number=2) elif OuterRef("name") == Value("post_b"): else_if_filters = Q(number=1) else: else_if_filters = Q() comments = Comment.objects.filter( else_if_filters, post_id=OuterRef("pk"), ).values("post_id").annotate( number_of_posts=Count("id") ).values("number_of_posts") queryset = queryset.annotate( comments_num=Subquery(comments) ).values("name", "comments_num") The disired output: post_a has comments_num=1 (one comment where Comment.number = 1 - my query condition in if-else statement … -
Django + Stripe (Orders and Items)
Please help me to find an error in my code I have a Django + Stripe project that has to process single item purchase and order purchase at the same time With single items it works perfectly and I get redirected to Stripe form once I click on Buy button but I get > Not Found: /order_checkout/1/ [04/Jan/2024 15:47:47] "GET > /order_checkout/1/ HTTP/1.1" 404 2953 for order purchase Why? this is my views.py import stripe from django.conf import settings from django.http import HttpResponse, JsonResponse from django.shortcuts import get_object_or_404 from django.views import View from django.views.generic import TemplateView from .models import Item, Order, OrderItem stripe.api_key = settings.STRIPE_SECRET_KEY class ProductLandingPageView(TemplateView): template_name = 'landing.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) item_id = self.kwargs["item_id"] item = get_object_or_404(Item, id=item_id) context['item'] = item context.update({ "STRIPE_PUBLIC_KEY": settings.STRIPE_PUBLISHABLE_KEY }) return context class CreateCheckoutSessionOrderView(View): def get(self, request, *args, **kwargs): order_id = self.kwargs["order_id"] DOMAIN: str = 'http://127.0.0.1:8000' order = Order.objects.get(id=order_id) session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'usd', 'unit_amount': order.get_total_cost() * 100, 'product_data': { 'name': order.__str__, }, }, 'quantity': 1, }, ], payment_intent_data={ 'metadata': { 'order_id': order.id, }, }, mode='payment', success_url=DOMAIN + '/success/', cancel_url=DOMAIN + '/cancel/', ) return JsonResponse({'id': session.id}) class CreateCheckoutSessionView(View): def get(self, request, *args, **kwargs): item_id = … -
django models field that is different for every user
I have a model called post and I want to check if a user has liked that post. I want to do it by adding a boolean field in post model that changing it doesn't affect another user. So if user 1 changes it to true for all other users it will be false. Is that possible? -
How to filter a queryset to show unique items of certain category in a database using django?
In my database for a website I am making to learn django, there objects each with a state, I want to be able to a page with a list of the unique states. I have tried using distinct but I get a "DISTINCT ON fields is not supported by this database backend" error. My code at the moment just displays a list of all the states. Is there a simple way of doing this / getting around this problem? Thanks The code which works but shows all of the states models.py class TowerSite(models.Model): siteName = models.CharField(max_length=255) siteState = models.CharField(max_length=2) def __str__(self): return self.siteName + ', ' + self.siteState views.py class StateList(ListView): model = TowerSite template_name="towers_states.html" queryset = TowerSite.objects.all() html <ul> {% for item in object_list %} <li>{{ item.siteState }}</li> {% endfor %} </ul> When I try with queryset = TowerSite.objects.all().distinct('siteState') I get the error -
Can't create Django Custom User from Django admin page
I've created a custom user model named User that inherits from AbstractUser to add two additional fields for two-factor authentication (otp_base32 and otp_auth_url). Additionally, I've defined a custom manager (CustomUserManager), which extends BaseUserManager and generates otp_base32 otp_auth_url fields of User using the pyotp library. Now, when I create a User from Django admin page, otp_base32 and otp_auth_url fields are not generated, however I have defined such functionality in Custom Manager. models.py from django.db import models from django.contrib.auth.models import AbstractUser from .managers import CustomUserManager class User(AbstractUser): otp_base32 = models.CharField("2FA base32", max_length=255, blank=True) otp_auth_url = models.CharField("2FA URL", max_length=255, blank=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] objects = CustomUserManager() managers.py from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import gettext_lazy as _ import pyotp class CustomUserManager(BaseUserManager): def create_user(self, username, password, **extra_fields): if not username: raise ValueError(_("The Username must be set")) user = self.model(username=username, **extra_fields) user.set_password(password) otp_base32 = pyotp.random_base32() user.otp_base32 = otp_base32 user.otp_auth_url = pyotp.totp.TOTP(otp_base32).provisioning_uri( name=username, issuer_name="starglassonline.uz") user.save() return user def create_superuser(self, username, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_active", True) if extra_fields.get("is_staff") is not True: raise ValueError(_("Superuser must have is_staff=True.")) if extra_fields.get("is_superuser") is not True: raise ValueError(_("Superuser must have is_superuser=True.")) return self.create_user(username, password, **extra_fields) admin.py: from django.contrib import admin from .models import User admin.site.register(User) I … -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 65: invalid start byte
(env) PS C:\Users\kurtf\OneDrive\Desktop\music-app-back\app> python manage.py makemigrations spotify Traceback (most recent call last): File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\app\manage.py", line 22, in <module> main() File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\app\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\core\management\base.py", line 106, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\core\management\commands\makemigrations.py", line 158, in handle loader.check_consistent_history(connection) File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\db\migrations\loader.py", line 313, in check_consistent_history applied = recorder.applied_migrations() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\db\migrations\recorder.py", line 89, in applied_migrations if self.has_table(): ^^^^^^^^^^^^^^^^ File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\db\migrations\recorder.py", line 63, in has_table with self.connection.cursor() as cursor: ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\db\backends\base\base.py", line 316, in cursor return self._cursor() ^^^^^^^^^^^^^^ File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\db\backends\base\base.py", line 292, in _cursor self.ensure_connection() File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\db\backends\base\base.py", line 275, in ensure_connection self.connect() File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\db\backends\base\base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\django\db\backends\postgresql\base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kurtf\OneDrive\Desktop\music-app-back\env\Lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, … -
Can I use drf-spectacular's GET_MOCK_REQUEST setting to fake a request when testing my API with Swagger UI?
I'm using drf-spectacular to document the API endpoints of a Django / DRF project, mainly with the @extend_schema decorator and it works nicely for the Swagger UI. What I would like to do is to "alter the behaviour" of some of the API endpoints so that when they are called from Swagger UI, we end up with a faked response of some sort (instead of regularly processing the request through the code). So I'm trying things with the GET_MOCK_REQUEST setting, but I can't get anywhere : its function seems to be called for every detected endpoint during api schema generation (but I can't see any changes in the yaml schema file, is this revealing ?). when playing with the supposed "altered endpoints" in Swagger UI, this function is not called. I'm probably missing something here, I might have misunderstood what GET_MOCK_REQUEST is meant for... Some help would be appreciated. -
Django AppRegistryNotReady when running Unittests from vscode
My UnitTest test cases in a Django project run fine when running them directly from the Django utility (python manage.py test). However, when trying to run them from VSCode's test explorer, I get django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.. I found several similar questions that were already answered here on SO, but none of the solutions seem to work. Here's what I tried: import my classes (e.g. models) within the SetUpTestData method and the actual test methods of the test class, rather than at the top of the file. This seemed to help a bit, in the sense that the tests now do show up in the test explorer (previously they didn't), but I still get an error when running them. set the DJANGO_SETINGS_MODULE environment variable at the top of the file containing the test class: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings") add a .env file to my root directory, containing DJANGO_SETINGS_MODULE = my_project.settings add a configuration with purpose debug-test to launch.json: "configurations": [ { "name": "Django test", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "test" ], "purpose": ["debug-test"], "django": true, "justMyCode": true } ] remove tests.py from my app folder, as my tests are stored in a separate folder (and apparently … -
I have a model named AvailableMentor and MentorTimeSlot: in which i want that chosen mentor's(before submission) specific slot comes as options
I have two models AvailableMentor and MentorTimeSlot in which i want that whichever date user chooses in html form(before submission)based on that date those mentors whose start_date and end_date cover that date i.e in between them or on start_date or end_date comes as an option in choose mentor field as options and whichever mentor user chooses in select field(before submission) that specific mentor's time slot come as an options in another select field from the MentorTimeSlot Model. CHOICES={ ("startupClinic","Startup Clinic"), ("entrepreneurCharcha","Entrepreneur Charcha"), ("entrepreneurNetwork","Entrepreneur Network"), ("sellToGovt","Sell To Govt"), ("schoolSanitization","School Sanitization"), } class AvailableMentor(models.Model): is_available = models.BooleanField(default=True) start_date=models.DateField() end_date=models.DateField() mentor_name = models.CharField(max_length=255) service_allotted = models.CharField(max_length=255,choices=CHOICES,) def __str__(self): return self.mentor_name Mentor Time Slot Model class MentorTimeSlot(models.Model): mentor = models.ForeignKey(AvailableMentor, on_delete=models.CASCADE) date = models.DateField(help_text="Choose a date between the available start date and end date.") start_time = models.TimeField(help_text="Choose time carefully.It is 24 hour format") end_time = models.TimeField(help_text="Choose time carefully.It is 24 hour format") is_available = models.BooleanField(default=True) def __str__(self): return f"{self.mentor.mentor_name} - {self.start_time} to {self.end_time} on {self.date}" I have tried javascript,ajax, smart selects and much more but i dont know why on any of those code the options are not coming.So. is there any way that i can solve this problem. -
uploaded images not alwasy visible on production azure environment
I have dockerized a django applicaton and deployed with NGINX on Azure.I also executed the command: manage.py collectstatic for copying the static files to the directories that are served by the file server. So I created on the azure environment a App service and I pushed everything to the docker containers. And everything is working fine. But a user has the ability to upload an image. And now comes the strange part. After some time, the uploaded image is not displayed in the app. And sometimes it is displayed in the app For example this image"with url: .azurewebsites.net/media/media/photos/animals/Grey_Wolf_klein_formaat_232396120.jpg is displayed. But this image with url: azurewebsites.net/media/media/photos/animals/335946586_Gestreepte_jakhals_klein_formaat.jpg is not displayed and gives a 404: 404 Not Found nginx/1.25.3 So I will show you partly the the settings.py of django: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_DIRS = [ (BASE_DIR, 'static') ] STATICFILES_DIRS = [BASE_DIR / 'static'] STATIC_ROOT = BASE_DIR / 'staticfiles/' MEDIA_ROOT = BASE_DIR / 'media' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' and the NGINX.conf file looks: upstream DierenWelzijn { server web:8000; } server { listen 80; server_name https://dockerdierenwelzijn.azurewebsites.net; location / { proxy_pass http://DierenWelzijn; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 10M; proxy_redirect off; } location … -
Deployment problem with railway and django
When doing the deployment with Raiway I have a perhaps very common error because I found it in this answer Why do I get this error when I deploy a Django App in Railway? but the problem is that none of the possible solutions they mention have worked for me. What should I do to solve my error? Structure of my project C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog\apps C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog\blog C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog\files C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog\static C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog\templates C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog\apps\publicaciones C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog\apps\publicaciones\migrations C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog\apps\publicaciones\__pycache__ C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog\apps\publicaciones\migrations\__pycache__ C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog\blog\settings C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog\blog\__pycache__ C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog\blog\settings\__pycache__ C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog\files\imagenes C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog\static\css C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog\static\images C:\Users\Jesus\OneDrive\Documentos\sideprojects\portafolio\blog\static\js requirements.txt asgiref==3.7.2 contourpy==1.1.1 cycler==0.12.1 distlib==0.3.7 dj-static==0.0.6 Django==4.2.7 django-ckeditor==6.7.0 django-js-asset==2.1.0 filelock==3.13.1 fonttools==4.43.1 gunicorn==21.2.0 kiwisolver==1.4.5 matplotlib==3.8.0 numpy==1.26.0 packaging==23.2 pandas==2.1.1 Pillow==10.0.1 platformdirs==3.11.0 prettytable==3.9.0 psycopg2-binary==2.9.9 pyparsing==3.1.1 python-dateutil==2.8.2 pytz==2023.3.post1 setuptools==68.2.2 simpy==4.1.1 six==1.16.0 sqlparse==0.4.4 static3==0.7.0 tzdata==2023.3 wcwidth==0.2.8 whitenoise==6.6.0 Error ERROR: failed to solve: process "/bin/bash -ol pipefail -c python -m venv --copies /opt/venv && . /opt/venv/bin/activate && pip install -r requirements.txt" did not complete successfully: exit code: 1 Error: Docker build failed -
Dual Django stack on same database
We have just finished migrating our very old Django 1.6 (with South)/ Python 2 app to a new well-maintained OS running a well-maintained version of PostgreSQL There were several attempts to upgrade the Django app code, but it's so old it relies on libraries that are no longer supported or have a new version with a radically changed APIs. We finally settled to copying the entire virtual environment and run old code on old libraries. It actually works just fine internally. However, third party APIs have moved on and don't support old libraries anymore. Not that they were working on the old server. So we would like to create a new Django 5 / Python 3 stack that would cover the following Social login Modern Django Rest framework A new frontend with a modern framework, eventually Now, running two nginx server {} or location {} with separate gunicorns doesn't scare me but I'm wondering: can the two stacks use the same database ? can I interact with sessions using one stack and expect the other to follow ? how can I evolve the model properly on both stacks ? -
Facing issue while trying to importing a class from views in django
I'm new to python and django, i'm working on a project and trying to import the classes in views in other file but i'm getting an error as "Import error: No module found". the folder structures is as follows please help. Travel -app - settings.py -travello - views ( its a folder as i have multiple view files) - __init__.py - views_first.py ( has class First) - views_second.py ( has class Second) - tests - __init__.py - test_views.py ( in this file trying to import First and Second class mentioned above) importing First and Second class in test_views.py as below from ml.views.views_first import First from ml.views.views_second import Second getting "import error" please help -
Rendering a images in HTML template using django template tags
Want to render images in a HTML template using Django template tags. I tried the following template tags inside the HTML files. I rendered HTML template passing with the list of images as shown below. I have also includes load_staitc command at the top of the template. {% for image_url in image_urls %} <img src="{{ image_url }}" alt="Image"> {% endfor %} Following is the my view.py method. def image_gallery(request): image_urls = ['images\filter.JPG', 'images\logo1.png', 'images\profile1.jpg'] return render(request, 'myapp/image_gallery.html', {'image_urls': image_urls}) Images are not being loaded in the HTML template. What is wrong with the code? -
get url on item in AWS s3
hello i am using a django app and host my media files on a AWS S3 bucket saving and showing in my app its fine but i need to generate a url of image to put in on a email i use django boto3 and this code to get the url : import boto3 from decouple import config AWS_ACCESS_KEY_ID = config("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = config("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = 'wiini' AWS_S3_REGION_NAME = 'ca-central-1' AWS_S3_SIGNATURE_NAME = 's3v4' AWS_S3_FILE_OVERWRITE = False def get_s3_favicon_url(): s3_client = boto3.client( 's3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_S3_REGION_NAME, config=boto3.session.Config(signature_version=AWS_S3_SIGNATURE_NAME) ) favicon_key = 'favicon-32x32.png' url = s3_client.generate_presigned_url( 'get_object', Params={'Bucket': AWS_STORAGE_BUCKET_NAME, 'Key': favicon_key}, ExpiresIn=3600, # Set an appropriate expiration time in seconds HttpMethod='GET', # Specify the HTTP method ) print("Generated URL:", url) return url but when i click on the generated url i get : <Code>AuthorizationQueryParametersError</Code> compelete error is here : This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>AuthorizationQueryParametersError</Code> <Message>Query-string authentication version 4 requires the X-Amz-Algorithm, X-Amz-Credential, X-Amz-Signature, X-Amz-Date, X-Amz-SignedHeaders, and X-Amz-Expires parameters.</Message> <RequestId>MBZZHKZF2ZJEGNJ2</RequestId> <HostId>1u9Jg6UQWPsdbmN2Qh88HYhsVNILR3CY58RzIMu3Be6FALR6D8qu+GnLEND/Mwee4Mkx0p7zoR8=</HostId> </Error> can someone help me to fix this problem ?