Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM: Case When not working when output is a Subquery producing a list of Ids?
I've been spending an incredible amount of time today on something I don't understand at all. Let me explain: I have a code similar to this one: puzzle_sequence__puzzles = <a subquery> puzzle_sequence__puzzles_3d = <another subquery> MyModel.objects.add_only_3d_puzzle_sequence().exclude(puzzle__in=Case( When(Q(only_3d_puzzle_sequence=True), then=Subquery(puzzle_sequence__puzzles_3d)), default=Subquery(puzzle_sequence__puzzles) )) which throws an error sqlite3.OperationalError: near "CASE": syntax error django.db.utils.OperationalError: near "CASE": syntax error or django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CASE WHEN CASE WHEN (`games_play`.`puzzle_sequence_id` IS NOT NULL AND CASE W...' at line 1") depending if I'm on sqlite3 or MariaDB server I've been toying with it for some while now, and it seems that's it's really the Case When statement which raised the issue as both the following statements work well: MyModel.objects.add_only_3d_puzzle_sequence().exclude(puzzle__in=Subquery(puzzle_sequence__puzzles_3d)) MyModel.objects.add_only_3d_puzzle_sequence().exclude(puzzle__in=Subquery(puzzle_sequence__puzzles)) I however don't understand at all why my Case When statement would fail Is there a specific issue if the output_field of a Case When statement should be a list of objects or list of object ids ? PS: as you can see, I'm not using Postgres, so I guess I cannot force output_field=ArrayAgg Thanks in advance -
QUALIFY on a non-window field
As stated here, from 4.2 Django supports fIltering against a window function. I've tried it and Django successfully creates a QUALIFY clause when using a window field in the filter clause. However, if using, let's say, a model field, the predicate is assigned to the WHERE clause. That arises the next problem: qs.annotate( position=Window( expression=RowNumber(), order_by=order_by ) ) obj = qs.get(id=obj.id) # obj.position will always be 1, as WHERE is run before QUALIFY -
This Customer doesn't have any saved payment details
def checkout_payment(request): if request.method == "POST": user = request.user cart_items = Cart.objects.filter(user=user, is_ordered=False) cart_total = sum(float(item.product.discounted_price()) * item.quantity for item in cart_items) # Convert cart_total to the smallest currency unit and then to integer total = int(cart_total * 100) stripe.api_key = settings.STRIPE_SECRET_KEY try: customer = stripe.Customer.create( email=request.user.email, name=request.user.first_name, description='Example charge', ) # payment_intent = stripe.PaymentIntent.create( # ) # creating charge charge = stripe.Charge.create( customer=customer, amount=total, currency="PKR", description='Payment has been charged successfully', source=request.POST.get('stripeToken') ) print(charge) messages.info(request, 'Payment has been successfully') return redirect('checkout_complete') except Exception as e: print(e) return render(request, 'checkout_payment.html') this is my code and why i am getting this error This Customer doesn't have any saved payment details. Attach a legacy Token, Card, Bank Account, or Source to this Customer and then try this request again, or use Payment Intents and Payment Methods instead. -
KeyError in django when i try to migrate
everytime i try to migrate i get KeyError: ('komaki', 'msg') Traceback (most recent call last): File "C:\Users\EXO\Downloads\Compressed\mathematics-main_2\mathematics-main\maths\manage.py", line 22, in <module> main() File "C:\Users\EXO\Downloads\Compressed\mathematics-main_2\mathematics-main\maths\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 106, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\commands\makemigrations.py", line 211, in handle loader.project_state(), ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\loader.py", line 361, in project_state return self.graph.make_state( ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\graph.py", line 329, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\migration.py", line 91, in mutate_state operation.state_forwards(self.app_label, new_state) File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\operations\models.py", line 384, in state_forwards state.remove_model(app_label, self.name_lower) File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\state.py", line 128, in remove_model del self.models[model_key] ~~~~~~~~~~~^^^^^^^^^^^ KeyError: ('komaki', 'msg') why is thi happening -
Django annotate and filter
This is a follow up to a previous question but I will include all the detail here. I'm creating a game where one of the elements is that players vote for each other. Here are the models I've set up (relevant fields only) #models.py class Game(models.Model): gamecode = ShortUUIDField(length=4, max_length=4, unique=True) phasenumber = models.IntegerField(default=1) isActive = models.BooleanField(default=True) class Player(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) isPlaying = models.BooleanField(default=True) class PlayerVote(models.Model): byplayer = models.ForeignKey(Player, on_delete=models.CASCADE) forplayer = models.ForeignKey(Player, on_delete=models.CASCADE, related_name="voteforplayer") gamephasenumber = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=True) When a user joins a game, they get an entry in the "Player" model. When they cast a vote for another player, an entry is added to the "PlayerVote" model showing which player voted (byplayer), who they voted for (forplayer), and the phase that the game is in (gamephasenumber) (this is just an integer that increases each phase of the game) What I'd like to do is create a QuerySet which contains each player and how many votes they got in this phase of the game. I can do the below to get the votes they've received for all phases playerswithvotes = Player.objects.select_related('game').filter(game = activegame.game, game__phasenumber = activegame.game.phasenumber, isPlaying = True).annotate(votesreceived=Count('voteforplayer')).order_by('-votesreceived') But how … -
Converting to SQLAlchemy from Django ORM in Django Rest Framework
I have a DRF application. I have it written in Django Rest Framework. For database handling, I have used Django's Builtin ORM. Let me explain my project structure. I have a django project named TourReview. Inside TourReview I have an app named review. Here are my key files: review/models.py : from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator # Create your models here. class PlaceInfoModel(models.Model): TYPE_CHOICES = [ ('Beach', 'Beach'), ('Hill', 'Hill'), ('Fountain', 'Fountain'), ('Landmark', 'Landmark') ] owner = models.ForeignKey('auth.User', related_name='review', on_delete=models.CASCADE, default=1) name = models.CharField(max_length=60) address = models.CharField(max_length=300) rating = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(5)]) type = models.CharField(max_length=20, choices=TYPE_CHOICES) image = models.ImageField(upload_to='uploads/') review/serializers.py: from .models import PlaceInfoModel from rest_framework import serializers class PlaceInfoSerializer(serializers.ModelSerializer): class Meta: model = PlaceInfoModel fields = ['id', 'name', 'address', 'rating', 'type', 'image'] read_only_fields = ['owner'] reviews/views.py: from django.shortcuts import render from .serializers import * from .models import * from rest_framework.decorators import APIView from rest_framework import viewsets from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication from rest_framework.permissions import IsAuthenticatedOrReadOnly from .custom_permission import IsPermittedForAction from django.contrib.auth.views import LogoutView from .serializers import * from rest_framework.pagination import LimitOffsetPagination from rest_framework.filters import OrderingFilter class PlaceModelViewSet(viewsets.ModelViewSet): queryset = PlaceInfoModel.objects.all() serializer_class = PlaceInfoSerializer authentication_classes = [SessionAuthentication] permission_classes = [IsPermittedForAction,IsAuthenticatedOrReadOnly] pagination_class = LimitOffsetPagination filter_backends = … -
website not able to become responsive in django
body, html { height: 100vh; margin: 0; padding: 0; } .part1 { position: relative; width: 100%; height: 100%; background-color: black; display: flex; justify-content: space-between; } .tt { margin-top: 20px; margin-left: 20px; width: fit-content; height: fit-content; animation: slideInLeftTt 1s ease forwards; /* Animation for tt */ } @keyframes slideInLeftTt { 0% { transform: translateX(-100%); opacity: 0; } 100% { transform: translateX(0); opacity: 1; } } .txt2 { font-size: 35px; animation: slideInUpTxt2 1s ease forwards; /* Animation for txt2 */ } @keyframes slideInUpTxt2 { 0% { transform: translateY(100%); opacity: 0; } 100% { transform: translateY(0); opacity: 1; } } .txt { font-size: 64px; animation: slideInUpTxt 1s ease forwards; /* Animation for txt */ } @keyframes slideInUpTxt { 0% { transform: translateY(100%); opacity: 0; } 100% { transform: translateY(0); opacity: 1; } } .txt1 { font-size: 25px; animation: slideInUpTxt1 1s ease forwards; /* Animation for txt1 */ } @keyframes slideInUpTxt1 { 0% { transform: translateY(100%); opacity: 0; } 100% { transform: translateY(0); opacity: 1; } } .A1 { height: 100%; width: fit-content; color: white; display: flex; flex-direction: column; font-family: 'Baskerville Old Face', serif; } .pv { margin-top: 140px; margin-left: 200px; height: fit-content; width: fit-content; } .image { max-width: 100%; max-height: 100%; } .logo-container … -
Django Admin "Export selected" button not showing in Admin
I'm trying to enable the "Export selected" button in the Django admin for users to download data as an Excel sheet. I'm using django-import-export but the button isn't appearing. Here's what I've done: Installed django-import-export (pip install django-import-export). Trial 1: class UserAdmin(ImportExportModelAdmin): list_display = ('username', 'email'....) admin.site.unregister(User) admin.site.register(User, ImportExportModelAdmin) Trial 2: class UserAdmin(ExportMixin, admin.ModelAdmin): list_display = ('username', 'email'.....) admin.site.unregister(User) admin.site.register(User, UserAdmin) Restarted the development server. the django-import-export is in INSTALLED_APPS in settings.py Expected behavior: The "Export selected" button should appear in the Django admin user list view. Actual behavior: The button is not displayed. My Question: Why the button is not showing and how can I fix it. Any suggestions or insights into why the button might not be showing would be greatly appreciated. -
Django, Settings module not found on YouStable hostings
I have been deploying django websites on a shared hosting platform (YouStable). With my latest attempt I get a 500 server error page, because it can’t find the settings file. Background I did previously manage to deploy a site that worked. I deleted that when I had problems because I had chosen app names that conflict with reserved words and I also discovered I could pip install the Bootstrap web framework (although I need to sort this issue first). I have since had problems creating a new site. I reported a problem when the hosting server was trying to run code from a virtual environment connected to a previous site ( the site and venv have been deleted). The hosting support techies have fixed that. What I did. The procedure for deployment involves creating a Python ‘app’ in CPanel's ‘Setup Python app’ by; selecting a Python version (I chose 3.11), choosing a name (‘myapp’), selecting the domain name and saving the app. This creates a virtual environment (or venv) using my username (‘username’), the app name and the Python version. For me: /home/username/virtualenv/appname/3.11/ CPanel then displays the code to select and activate this venv for use in the terminal section … -
slider input ranges in html with min and max values inside a table and a for loop
I'm a newbie and battling my first issues with Django, html, js and so on.. I wonder if anyone can help me out here. I have a page where you must enter a series of ranges of attendances and prices for a movie center. If you purchase entrances to a movie if you go to the movies once you pay 8, if you plan to go from 2 to 5 times you pay 20 but if you plan to go 6 to 10 times you pay 30. what I'm getting is this The thing is that the list will grow every time you make a new range of prices. I can forsee someone adding another range from 11 to 20 times and paying 35$. ` #visit range <th scope="col">Precio</th> <th></th> </tr> </thead> <tbody> {% for cuota in cuotas %} <tr> <td><input name="range" id="range" min="0" max="100" value="0" type="range"></div> <td><a class="price">{{ cuota.price }}</a></td> <td style="text-align: right"> <button type="button" class="btn btn-secondary btn-xs text-align-right"><i class="fas fa-edit"></i></button> <button type="button" class="btn btn-secondary btn-xs"><i class="fas fa-trash-alt"></i></button> </td> </tr> {% endfor %} </tbody> </table> </div> </div>` The thing here is that the list will grow and I should have an unique ID for each slider and so on. … -
type object 'Project' has no attribute 'objects'
I use django version 5.0.3. And got this error : type object 'Project' has no attribute 'objects'. from django.db import models from account.models import User import uuid # # Create your models here. class Project(): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) description = models.TextField(blank=True,null=True)#not required created_by = models.ForeignKey(User,related_name = 'projects',on_delete=models.CASCADE)#pass in User object def __str__(self): return self.name from django.contrib.auth.decorators import login_required from django.shortcuts import render,redirect from .models import Project # Create your views here. @login_required def projects(request): projects = Project.objects.filter(created_by=request.user) return render(request,'project/projects.html',{ 'projects':projects }) when I "make migrations project" I got this message No changes detected in app 'project' and when I "python manage.py migrate" I got this message Operations to perform: Apply all migrations: account, admin, auth, contenttypes, sessions Running migrations: No migrations to apply. Not sure what happened here -
error with if else in html in django application
Good afternoon, i have django application where i have issue on main page there is header in base html, there is 1 button, but with 2 different values as link {% if roleworker %} <li><a href="/addservice/">Add</a></li> {% else %} <li><a href="/addpage/">Add</a></li> {% endif %} roleworker is value in database, here is model for it class Role(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='Пользователь') roleworker = models.BooleanField(default=False) when user opens index.html it equals True, when user opens indexworker.html(here is posts from worker) it equal false, i checked that functionality of value in db for user, it works good when user open some other page it must remember his value, for that there is that django model this is function that check value of roleworker for user def rolecheck(request, render): user = request.user role = Role.objects.get(user=user) roleworker = role.roleworker if roleworker == True: print('True') elif roleworker == False: print('False') return render(request, 'base.html', {'roleworker': roleworker}) but on html there is always "{% if roleworker %}" (it means == True) even when in django admin it equal False {% if roleworker %} <li><a href="/addservice/">Добавить (услуга)</a></li> {% else %} <li><a href="/addpage/">Добавить (статья)</a></li> {% endif %} Maybe someone know how to fix it, i will be very grateful … -
Python django paginator not displaying items correctly
I developed a simple web app. I have added the paginate_by property to the view. I'm able to show only the first 10 records retrived from the database. If i change the paginate_by property to 20 I always see 10 records in the list page of my models. Note that the number or records change in the top bottom left of the screenshot but I always see 10 records. Here the code: views.py: class DeviceList(LoginRequiredMixin, FilterView): model = models.Device filterset_class = filters.DeviceFilter context_object_name = "devices" paginate_by = 10 template_name = "device_list.html" def get_context_data(self, **kwargs): context = super(DeviceList, self).get_context_data(**kwargs) context["hist_devices"] = (models.Device.objects.filter(history_type=0)).count() context["active_devices"] = ( models.Device.objects.filter(history_type=1) ).count() context["available_devices"] = (models.Device.objects.filter(status=0)).count() context["unavailable_devices"] = ( models.Device.objects.filter(status=1) ).count() return context device_list.html: {% extends 'base.html' %} {% load crispy_forms_tags %} {% load pagination_tags %} <link rel="stylesheet" href="/static/css/style.css"> {% block title %} Device list {% endblock %} {% block content %} <h2>Device list</h2> <div class="row row-no-gutters"> <div class="col-md-6"> <div class="accordion accordion" id="accordionFlushExample"> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseOne" aria-expanded="false" aria-controls="flush-collapseOne"> <h5>Filters</h5> </button> </h2> <div id="flush-collapseOne" class="accordion-collapse collapse" data-bs-parent="#accordionFlushExample"> <div class="accordion-body"> <form method="get"> {{ filter.form.as_p }} <button class="btn btn-primary" type="submit">Search</button> </form> </div> </div> </div> </div> </div> <div class="col-md-6"> <div class="card card-body"> <h5><i class="bi … -
Change record title in a StackedInline in Django
I am trying to either change or remove the title for each record in an inline, but have not been able to find a way to do it in the docs or by override get_formset. Specifically, I want to change or remove the title highlighted in the attached image. Any ideas how to do it please? Preferably without overriding CSS etc. -
drop box small files upload slowly
I have a free dropbox subscription and use it in conjunction with django. def upload_image(request): if request.method == 'POST': dbx = dropbox.Dropbox('') file_from = request.FILES['file'] file_to = '/chat/' + file_from.name # Upload the file dbx.files_upload(file_from.read(), file_to) # Create a shared link for the uploaded file shared_link_metadata = dbx.sharing_create_shared_link_with_settings(file_to) url = shared_link_metadata.url # Replace ?dl=0 with ?raw=1 in the URL url = url.replace('&dl=0', '&raw=1') # Create a new Image instance with the shared link new_image = Image(image_url=url) new_image.save() return HttpResponse("Image uploaded and saved successfully!") else: return HttpResponse("Method not allowed", status=405) I have read a lot that uploading large files can be slow however my current upload speed for a file for example ~2MB takes ~3 seconds. From what I've learnt dropbox has no speed settings and tries to upload as fast as possible. However maybe I am still missing something in the app settings? -
Django async acount takes forever to execute
Consider a django rest framework application which calls an async function like; class SomeViewSet(ListUpdateViewSet): @action( methods=["GET"], url_path=r"count-async", detail=False ) def get_count_async(self, request, *args, **kwargs): print('starting') t = asyncio.run(self.aget_count_async(request, *args, **kwargs)) print('ending') return Response(data={ }) async def aget_count_async(self, request, *args, **kwargs): print('before getting count') my_count = await User.objects.filter(id="1").acount() print('after getting count') return my_count However whenever I run the endpoint I notice the logs show "before getting count", yet minutes later it is still running and no "after getting count" is being shown. How can I debug this and what could possibly be the cause? -
Optimizing Complex Django ORM Queries Across Polymorphic Models with High Volume Data
I'm working on a Django 3.2 project with a PostgreSQL backend that involves a complex data model with polymorphic relationships managed by django-polymorphic. The project serves as a backend for a web application that displays a large set of interconnected data points to the users, requiring highly optimized queries for performance. Despite leveraging Django's ORM capabilities and PostgreSQL's indexing features, I'm encountering significant challenges in optimizing the query performance for one of the core functionalities of the application. Models Overview: BaseItem (polymorphic parent model) SubItem1, SubItem2, SubItem3 (child models of BaseItem, each with unique fields and large datasets) RelatedModel (has a ForeignKey to BaseItem) The application features a complex filtering interface that allows users to dynamically filter BaseItem records based on fields from SubItem1, SubItem2, SubItem3, and RelatedModel. The challenge arises when applying filters across these models, as the ORM generates suboptimal queries that result in full table scans or inefficient use of indexes. The Specific Challenge: Efficiently Filter Across Polymorphic Models: How can we structure queries or models in Django to efficiently filter BaseItem records by criteria that span across the polymorphic child models and related models? Avoid Full Table Scans: Given the volume of data, full table scans … -
I'm having trouble sending emails on Django using SMTP. Even after trying various tutorials and checking the documentation, nothing seems to work
Here are the possible things that may cause my problem. using django's live server instead of a domain. I know in gmail you can't no longer use less secure apps. I enabled two factor authentication and created an app with a unique password. This is what i used for the EMAIL_HOST_PASSWORD. For gmail I used this in my settings.py file DEBUG = True EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = "my email address" EMAIL_HOST_PASSWORD = "my app password" DEFAULT_FROM_EMAIL = "my email address" Then tried outlook with the same config except for EMAIL_HOST = "smtp-mail.outlook.com" EMAIL_HOST_USER = "outlook email address" EMAIL_HOST_PASSWORD = "outlook email address password" DEFAULT_FROM_EMAIL = "outlook email address" i never had a single success with any of them as I couldn't send out a single mail. Checked my spam folder, inbox folder and all mail folder of the mail recipient. -
Django 1.7 workaround to use drf-spectacular
I am trying to use drf-spectacular for annotating my existing python api, but i am currently using django-1.7 in my application, and this tool has a dependency of django-2.2 what can be done as quick solution or any suggetion?? -
After renaming my table in Django, items from the old table were not moved or deleted
My old table called Quiz was renamed to CarQuizz, the problem is that all items in the table with the old name were neither moved to the new name nor were they deleted. Here is the following log from my application: Log Models.py from django.db import models class CarQuizz(models.Model): name = models.CharField(max_length=255) url_image = models.URLField(default=None) name_quiz = models.CharField(max_length=255,default='Cars') def __str__(self): return f'{self.name} foi adicionado ao quizz' Urls.py from django.urls import path from . import views urlpatterns = [ path('quiz/solo', views.Quiz, name='quiz'), ] I've already restarted the Django server and also deleted the record of migrations made, but nothing has resolved it. Except when I rename it back to Quiz, the program works normally. -
Dynamic data in single send | Twilio SendGrid
I am creating a monthly digest for release logs with wagtail CMS as backend, essentially whenever a new post gets created in cms, it will trigger signals.py which inturn should create a mail in single send. Now the problem is i want to pass the data to dynamic templates. As per my knowledge marketing/single send api's doesn't support dynamic data api-docs dynamic_template_data = { "somevariable" :"John", } data = { "name": name, "send_to": {"list_ids": [list_id]}, "email_config": { "suppression_group_id": unsubscribe_suppression_group, "sender_id": sender_id, # "design_id": "d-14a0041239f34f5688c5f192c869b766", "design_id" : "758d5b87-8b6f-49d7-ba1f-4dad111b5197", "dynamic_template_data": dynamic_template_data, "editor": "code", } } return self.sgClient.client.marketing.singlesends.post(request_body=data) <!DOCTYPE html> <html> <head> <title>Your Order Details</title> </head> <body> <p>Hello {{somevariable}},</p> </body> </html> This is the payload passing, initially i tried to pass the dynamic template id which isn't supported, so i passed the design id. Also i used handlebars for html template Is there any other way to pass dynamic data for singlesend api? -
django custom datetime format not working with form fields
I'm working on a Django project where I wanted to add a date format for local usage. As per the documentation, I have updated the settings to use local date time format : Link Settings are as below: DATE_INPUT_FORMATS = [ "%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%b %d %Y", "%b %d, %Y", "%d %b %Y", "%d %b, %Y", "%B %d %Y", "%B %d, %Y", "%d %B %Y", "%d %B, %Y", '%d-%m-%Y', '%d/%m/%Y' ] DATETIME_INPUT_FORMATS = [ "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M", "%m/%d/%Y %H:%M:%S", "%m/%d/%Y %H:%M:%S.%f", "%m/%d/%Y %H:%M", "%m/%d/%y %H:%M:%S", "%m/%d/%y %H:%M:%S.%f", "%m/%d/%y %H:%M", '%d-%m-%Y %H:%M:%S', '%d/%m/%Y %H:%M:%S' ] But for the form fields, it's still using the default date time formats and not taking the date time formats added in the settings file > <project>/env/lib/python3.9/site-packages/django/forms/fields.py(384)to_python() -> for format in self.input_formats: (Pdb) self.input_formats ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M:%S.%f', '%m/%d/%Y %H:%M', '%m/%d/%Y', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M:%S.%f', '%m/%d/%y %H:%M', '%m/%d/%y'] (Pdb) self <django.forms.fields.DateTimeField object at 0x128049c10> (Pdb) value '19-03-2024 17:25:17' (Pdb) Looking forward to suggestions or feedback. -
How to test exception handling in Django REST Framework action method when unable to trigger an Exception during testing?
I'm working on a Django REST Framework (DRF) viewset that includes exception handling to deal with unexpected errors. The viewset has an action method that retrieves pricing information for servers from a third-party API. Here's a simplified version of the code: from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import status from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt import logging logger = logging.getLogger(__name__) class MyViewSet(viewsets.ViewSet): @action(detail=False, methods=["get"], url_path="pricing", authentication_classes=[]) @method_decorator(csrf_exempt) # For testing purposes only def pricing(self, request, pk=None): """ List all pricing or a specific server """ try: server_type = request.query_params.get("server_type") location = request.query_params.get("location") # Case 1: returns the pricing list if not server_type or not location: pricing = self.hapi.pricing() return Response(pricing, status=status.HTTP_200_OK) # Case 2: returns the pricing of the provided server info prices = self.hapi.calculate_price(server_type, location) return Response(prices, status=status.HTTP_200_OK) except Exception as error: logger.critical(f"Error fetching server pricing: {error}", exc_info=True) return Response({"message": "Error fetching server pricing", "error": str(error)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) I'm trying to test the except Exception part of the code, but I'm having trouble triggering the exception during testing. Since the code path leading to the exception is challenging to reproduce in a controlled testing environment, I'm not sure how to effectively test the exception … -
Status code was: 1 Service /usr/bin/chromedriver unexpectedly exited
i was using selenium , chrmoedriver to make screen short of the provided url in my django app. def take_url_screenshot(url): # Ensure the "screenshot" folder exists or create it if not available screenshot_folder = "screenshot" if not os.path.exists(f"{settings.MEDIA_ROOT}/{screenshot_folder}"): print(f"{settings.MEDIA_ROOT}/{screenshot_folder}") os.makedirs(f"{settings.MEDIA_ROOT}/{screenshot_folder}") # Create Chrome options chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--window-size=1920,1080") chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--ignore-ssl-errors=yes") chrome_options.add_argument("--ignore-certificate-errors") # Create an instance of Chrome webdriver with the headless option service = ChromiumService(executable_path=r"/usr/bin/chromedriver") driver = webdriver.ChromiumEdge(service=service, options=chrome_options) driver.get(url) time.sleep(5) # Take a screenshot and save it in the "screenshot" folder image_name = re.sub(r"[^\w\s]", "", url) screenshot_path = os.path.join( f"{settings.MEDIA_ROOT}/{screenshot_folder}/{image_name}.png" ) driver.save_screenshot(screenshot_path) # Close the browser driver.quit() return f"{screenshot_folder}/{image_name}.png" this is working fine in localhost, but when i deployed my django application this make exception : Service /usr/bin/chromedriver unexpectedly exited. Status code was: 1 version details: os : ubuntu 22.04 chromium-browser : 1:85.0.4183.83-0ubuntu0.20.04.3 chromedriver: ChromeDriver 122.0.6261.128 selenium: 4.12.0 i have checked ./chromedriver which is returning: Starting ChromeDriver 122.0.6261.128 (f18a44fedeb29764b2b5336c120fdd90ef1a3f5c-refs/branch-heads/6261@{#1057}) on port 9515 Only local connections are allowed. Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe. ChromeDriver was started successfully. i have tried in my localhost which is working fine. but the problem comes from the server -
Not getting Social Token when using SignIn with Slack
I am using django-allauth==0.61.1. I have added settings for Slack. I can successfully Signup/Login on my webapp using the SignIn with Slack. I get the email, slack_user_id, username from slack. But I don't get any social_token for that user. The user will be using my slack app with some commands. I need the token with expiry date to determine if the user is logged or logged out. I have checked the Oauth Scopes. I have the following User Token Scopes: email openid profile