Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 ? -
dynamic check related relations in django
I have numerous models (OtherModels) associated with one main model (A). In the future, more models will be added. In my main model (A), which is connected to the others, I want to dynamically check whether any record from this main model (A) is related to other tables or not. What solution do you recommend? class A(models.Model): name = models.CharField(_('Name'), max_length=255) class OtherModels(models.Models): a = models.ForeignKey(A, on_deleted=models.PROTECT) I use related_name and it's working, But since my relationships have become numerous, I can't use this method, and in the future, as it seems to me, it's not the right approach, especially considering they are expected to increase further. -
How do i import an excel file into a table in django
I have this model to store information about computers. I am trying to add a feature to import Excel file containing data directly instead of typing data into the table in case there is a lot of data to input. models.py class Product(models.Model): model=models.CharField(max_length=50, null=True) serial=models.CharField(max_length=50, null=True) hd_size=models.CharField(max_length=50,null=True) ram=models.CharField(max_length=50, null=True) processor=models.CharField(max_length=50, null=True) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.serial + ' - ' + self.model Views.py @login_required def product_mgt(request): context['page_title'] = "Computer List" products = Product.objects.all() context['products'] = products return render(request, 'product_mgt.html', context) Forms.py class SaveProduct(forms.ModelForm): model= forms.CharField(max_length=50,) serial= forms.CharField(max_length=50, ) hd_size= forms.CharField(max_length=50, ) ram= forms.CharField(max_length=50, ) processor= forms.CharField(max_length=50, ) class Meta: model = Product fields = ('model','serial','hd_size','ram', 'processor') def clean_serial(self): id = self.instance.id if self.instance.id else 0 serial = self.cleaned_data['serial'] try: if int(id) > 0: product = Product.objects.exclude(id=id).get(serial = serial) else: product = Product.objects.get(serial = serial) except: return serial raise forms.ValidationError(f"{serial} Computer Already Exists.") -
Why even I passing the fetch method as POST in the final of the process the method is GET?
I am using fetch in JS to make changes in a model from django, to do this I am passing the method do fetch as POST, but in the end the request is get [My code](https://i.stack.imgur.com/Nw6ad.png The method to request should be post so I tried to use await, but it doen't work. -
Error in my ml model showing in streamlit app [closed]
XGBoostError: [15:56:35] C:\buildkite-agent\builds\buildkite-windows-cpu-autoscaling-group-i-0b3782d1791676daf-1\xgboost\xgboost-ci-windows\src\data\array_interface.h:492: Unicode-3 is not supported. Traceback: File "C:\Users\1979k\anaconda3\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 552, in _run_script exec(code, module.__dict__) File "C:\Users\1979k\PycharmProjects\Laptop_Price_Predictor\app.py", line 65, in <module> st.title("The predicted price of this configuration is " + str(int(np.exp(pipe.predict(query)[0])))) File "C:\Users\1979k\anaconda3\lib\site-packages\sklearn\pipeline.py", line 515, in predict return self.steps[-1][1].predict(Xt, **predict_params) File "C:\Users\1979k\anaconda3\lib\site-packages\sklearn\ensemble\_stacking.py", line 369, in predict return self.final_estimator_.predict(self.transform(X), **predict_params) File "C:\Users\1979k\anaconda3\lib\site-packages\sklearn\utils\_set_output.py", line 157, in wrapped data_to_wrap = f(self, X, *args, **kwargs) File "C:\Users\1979k\anaconda3\lib\site-packages\sklearn\ensemble\_stacking.py", line 972, in transform return self._transform(X) File "C:\Users\1979k\anaconda3\lib\site-packages\sklearn\ensemble\_stacking.py", line 293, in _transform predictions = [ File "C:\Users\1979k\anaconda3\lib\site-packages\sklearn\ensemble\_stacking.py", line 294, in <listcomp> getattr(est, meth)(X) File "C:\Users\1979k\anaconda3\lib\site-packages\xgboost\sklearn.py", line 1168, in predict predts = self.get_booster().inplace_predict( File "C:\Users\1979k\anaconda3\lib\site-packages\xgboost\core.py", line 2437, in inplace_predict _check_call( File "C:\Users\1979k\anaconda3\lib\site-packages\xgboost\core.py", line 282, in _check_call raise XGBoostError(py_str(_LIB.XGBGetLastError())) Solution of this error i want -
Django get str instead of date when annotate models.DateField
i have models below class TaskPackage(models.Model): name = models.CharField(max_length=32, blank=True) is_deleted = models.BooleanField(default=False) class Task(models.Model): name = models.CharField(max_length=32, blank=True) start_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) task_package = models.ManyToManyField(TaskPackage) is_deleted = models.BooleanField(default=False) when i annotate like this, i got start_date as str type >>> packages = TaskPackage.objects.annotate( ... start_date=Min("task__start_date", filter=Q(task__is_deleted=False)) ... ) >>> print(type(packages[0].start_date)) <class 'str'> but when i remove Q expression, start_date is date type >>> packages = TaskPackage.objects.annotate( ... start_date=Min("task__start_date") ... ) >>> print(type(packages[0].start_date)) <class 'datetime.date'> -
View categories list with posts under the categories, which have status='published' in django
I am working on a project, which have below models and views: Models: class InformationCategory(models.Model): # fileds here class InformationPost(models.Model): informations = models.ForeignKey(InformationCategory, on_delete=models.CASCADE, related_name="information_posts" ) # other fields here status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') Views def getInformed(request): template = 'getinformed/information-cat-list.html' categories = InformationCategory.objects.filter(Available=True) args = { 'categories': categories, } return render(request, template, args) Template {% for cat in categories %} <h2 class="catTitle"> {{cat.Title}} </h2> <ol class="itemTitle"> {% for post in cat.information_posts.all %} <li><a href="{{post.geturl}}">{{post.Title}}</a></li> {% endfor %} </ol> {% endfor %} I want to view the list of all categories, and the posts under each category, but the posts' status should be status=’published’. The code above shows all categories with all posts under those categories, but the problem is that I do not want to show the posts that have status=’draft’. I mean below: CATEG 1 Post 1 Post 2 Post 3 (should be hidden, because status=’draft’ not published). How can I solve that? Thank you! -
Django Migrations Problems
I am facing a migration issue in Django related to a model inheritance and field modification. Initially, I had a TaggedModel with a tags field, and a Book model inheriting from it with another tags field. I created a lot of instances of the Book model then I Realized the redundancy, then I decided to remove the tags field from the Book model and retain only the one from the TaggedModel. After making this change, I expected Django to generate a RemoveField migration, but instead, it generated an AlterField migration. Here's the relevant code: class TaggedModel(models.Model): tags = ArrayField( models.CharField(max_length=TAG_MAX_LENGTH, blank=True), blank=True, null=True, ) class Meta: abstract = True class Book(TaggedModel): category = models.ForeignKey("BookCategory", on_delete=CASCADE) tags = ArrayField( models.CharField(max_length=100, blank=True), blank=True, ) # Removed tags field from here And the migration file: import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('test', '0084_remove_inputs'), ] operations = [ migrations.AlterField( model_name='book', name='tags', field=django.contrib.postgres.fields.ArrayField( base_field=models.CharField( blank=True, max_length=100 ), blank=True, null=True, size=None ), ), ] I'm trying to understand why Django generated an AlterField migration instead of a RemoveField migration. Any insights or suggestions on how to address this issue would be greatly appreciated. -
Better way to access a nested foreign key field in django
Consider the following models class A(models.Model): id field1 field2 class B(models.Model): id field3 field_a (foreign_key to Class A) class C(models.model): id field4 field5 field_b (foreign_key to Class B) @property def nested_field(self): return self.field_b.field_a Now here that property in class C , would trigger additional sql querries to be fetched , Is there an optimized or better way to get nested foreign key fields ? I have Basically tried searching and finding regarding this and couldn't find a better solution, that addresses this problem.