Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why webSocket connection failed?
I've been trying to cerate a chat app using Django with webSocket,in console I got this, error WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/room/' failed: room/:20 I'm not using Redis for implementing Django channels, İt is just a simple chat app runs on local server host views.py def room(request, room_name): return render(request, "chatroom.html", {"room_name": room_name}) routing.py websocket_urlpatterns = [ re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatRoomConsumer.as_asgi()), ] consumer.py class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope["url_route"]["kwarges"]["room_name"] self.room_group_name = "chat_%s" % self.room_name await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() # to know which group we should send to await self.channel_layer.group_send( self.room_group_name, { "type": "tester_message", "tester": "hello world", }, ) async def tester_message(self, event): tester = event["tester"] await self.send(text_data=json.dumps({"tester": tester})) async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_group_name, self.channel_name) chatroom.html <div id="user-hello"> </div> <!-- convert an object into a JSON object --> {{room_name|json_script:"room-name"}} <script> // convert a JSON object in text format to js object that can be used const roomName=JSON.parse(document.getElementById('room-name').textContent); //create websocket connection script const chatSocket=new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); //receive a massege chatSocket.onmessage=function(e){ const data=JSON.parse(e.data) console.log(data); document.querySelector('#user-hello').innerHTML=(data.tester) } </script> settings.py INSTALLED_APPS = [ "channels", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "chat", ] DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" ASGI_APPLICATION = "core.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", … -
Uncaught DOMException: Failed to execute 'querySelector' on 'Element': 'td:nth-child(...)' is not a valid selector
Hi guys I am building a django app, and i am struggling with js function to sort a html table ( values in the desired column ) by clicking the column name. Below I provide a html template and another html file which extends this template, and of course the js file itself. Any help is appreciated, thank you in advance! TEMPLATE: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Report Result</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link type="text/css" href="{% static 'css/report.css' %}" rel="stylesheet" /> </head> <body> <h1>{{ info }}</h1> <p style="font-size: 30px;">The report was generated successfully. You can download the xlsx file using the button below:</p> <p style="font-size: 20px;">To sort values by column, click the name of the desired column</p> <table id="data-table"> <thead> <tr> {% for col in column_names %} <th data-col="{{ col }}">{{ col }}</th> {% endfor %} </tr> </thead> <tbody>{% block content %}{% endblock %}</tbody> </table> <script src="{% static 'js/sorting.js' %}"></script> </body> </html> HTML FILE THAT EXTENDS THE PREVIUOS ONE: {% extends 'base_report.html' %} {% block content %} {% for row_data in data_to_render %} <tr> {% for cell_data in row_data %} <td> {% if cell_data.link %} <a href="{{ cell_data.value }}"> {{ cell_data.value }} </a> {% … -
modify models instances and sent to another model in django
I have 2 models in django Model A and Model B in model A exist 2 fields start_hour = models.TimeField() end_hour = models.TimeField() and I want to send this instance to a function and return a list with a slot time of 1 hour. for an example: start_hour = '10:00' end_hour = '15:00' output : [ ( '10:00 – 11:00'), ( '11:12 – 12:00'), ( '12:00 – 13:00'), ( '13:00 – 14:00'), ( '14:00 – 15:00'), ] i wrote function and works well my question is : i want in model B show list of time slot to select not show start time and end time Model_A = models.ForeignKey(Model_A, on_delete=models.CASCADE) I wrote this code, but it shows the start time and end time! -
OAuth2 Authentification Django and MSexchange
I am building a Django App where users have to be able to send emails with their specific exchange mail address. I think I need OAuth2 for that. However MS support and all other resources I found state that I need to register my app in Azure AD. But I don't have an Azure AD. I do have access to the Microsoft 365 admin center. Do I have to register my App there or generate a specific token? -
How to fix django mfa for firefox and safari (Registeration Failed as NotAllowedError: CredentialContainer request is not allowed)
I use the mfa library (https://pypi.org/project/mfa/) within my django project. In Chrome, the user can register a second factor (fido) easily, but in firefox, i get the following error: Registeration Failed as NotAllowedError: CredentialContainer request is not allowed., try again or Go to Security Home Im googeling this since hours but cant find a solution, i already checked CSP Settings. Any help is really appreciated! -
Passing Parent PK to ModelForm in Class Based Create and Update View
I'm updating function based views to class based views and having issues re-establishing the link between campaign and books. My Book Model has a foreign key link to Campaigns. campaign = models.ForeignKey(Campaign, on_delete=models.DO_NOTHING) I have a ModelForm where I set the campaign_id and would like to get this from the CreateView. class BookForm(forms.ModelForm): def __init__(self, *args, **kwargs): author = kwargs.pop('author', None) campaign_id = kwargs.pop('campaign_id', None) super(BookForm, self).__init__(*args, **kwargs) if campaign_id: self.fields['campaign_id'].initial = campaign_id campaign_id = forms.CharField(widget=forms.HiddenInput()) I followed this using dispatch and get_form_kwargs and my CreateView looks like class BookCreateView(generic.CreateView): model = Book template_name = 'PromoManager/book_form.html' form_class = BookForm success_url = '/profile' campaign_id = None # Retrieves the campaign_id from url def dispatch(self, request, *args, **kwargs): self.campaign_id = kwargs.get("pk") return super().dispatch(request, *args, **kwargs) ## Sends building id to the form def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs(*args, **kwargs) kwargs["campaign_id"] = self.campaign_id return kwargs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['campaign'] = Campaign.objects.get(pk=self.campaign_id) context['title_label'] = "Create" return context def form_valid(self, form): instance = form.save(commit=False) instance.author = self.request.user instance.campaign = Campaign.objects.get(id=form.cleaned_data['campaign_id']) instance.save() form.save_m2m() return super().form_valid(form) But it breaks the UpdateView which relies on the same form as the PK passed on the update view URL is the book pk. My UpdateView looks … -
Odd results when running similar queries in Postgres
I am having this issue where my database is causing the CPU usage of our db server to hit 100% on a particular query. The query has two different where clauses and does not work, but when I delete either of the where clauses, the query returns quickly. The query i am trying to run is the following. This query references two tables in the database, asset_asset and asset_assetclassification. asset_asset has 1.8 million rows and asset_assetclassification has 7k rows. select count(1) from asset_asset INNER JOIN "asset_assetclassification" ON ("asset_asset"."classification_id" = "asset_assetclassification"."id") WHERE ("asset_assetclassification"."company_id" = 1 AND "asset_asset"."deleted_at" IS NULL); Here is a screenshot of the query plan for this query. And if i run this select count(1) from asset_asset INNER JOIN "asset_assetclassification" ON ("asset_asset"."classification_id" = "asset_assetclassification"."id") WHERE ("asset_assetclassification"."company_id" = 1); and here is a screenshot of the query plan for this query or this select count(1) from asset_asset INNER JOIN "asset_assetclassification" ON ("asset_asset"."classification_id" = "asset_assetclassification"."id") WHERE ("asset_asset"."deleted_at" IS NULL); the query works perfectly fine. Note: the original query was generated by Django. Any ideas about whats going on here? Thanks in advance! -
Send progressive data from django view to ajax
I have a django webapp. And I'm using jquery to send a POST. With that POST, I get multiple informations from the backend. But The page need to wait until all the informations are ready and then prin all of them. I would want, as an exemple, when the first one is finished, to be displayed, and then, when the second one is done, to be displayed and so on. That's my view: def home(request): context = {} if request.method == 'POST': is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' if is_ajax: context = {} # Update the expression if it's valid try: print('---------------------------------') print('POST[math-input]: {0}'.format(request.POST['math-input'])) print('POST[time]: {0}'.format(request.POST['time'])) data = request.POST['math-input'] core.max_time = int(request.POST['time']) print('---------------------------------') context = dispatch_expression(data) except Exception as exc: # exc_type, exc_obj, exc_tb = sys.exc_info() # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] # print(exc_type, fname, exc_tb.tb_lineno) # print("Exception: {0}".format(exc)) traceback.print_exc() context = {'result': 'Expresie invalidă!'} return JsonResponse(context, status=200) template = loader.get_template('home.html') return HttpResponse(template.render(context, request)) Basically, dispatch_expression(data) is doing all the algorithms. I can modify that function to work with yields, without any problem, but I have no idea how to send each step when it's done. I heard about async, but any example on the internet didn't help me. I tried StreamingHttpResponse, but … -
Updates made via admin to m2m Django field are not persisted in the database
I`m new to Django and completely stuck with this one. This pet project is a website for online school. The default flow would be: user signups and has the role Student by default, then if this user is a school teacher admin updates the role to Teacher. I have the following User model which has role field, I plan to use it to display correct content for the user on the website, since I dont want to use groups and permissions for this purpose, at least not yet. But I want to have groups in sync with User roles and use groups to manage permissions inside admin. class User(AbstractUser): username = None email = models.EmailField(max_length=255, unique=True, verbose_name="email address") first_name = models.CharField(_("first name"), max_length=150) last_name = models.CharField(_("last name"), max_length=150) updated_at = models.DateTimeField(_("last updated to user"), auto_now=True) email_verified = models.BooleanField(default=False) role = models.PositiveSmallIntegerField( choices=UserRolesChoices.choices, default=UserRolesChoices.STUDENT ) date_of_birth = models.DateTimeField(_("date of birth"), null=True, blank=True) profile_picture = models.ImageField(_("profile picture"), null=True, blank=True, upload_to=profile_pic_directory_path, storage=OverwriteStorage) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] def __str__(self): return self.email @property def is_staff(self): return (self.role in (UserRoles.TEACHER, UserRoles.ADMIN)) or self.is_superuser @property def is_teacher(self): return self.role == UserRoles.TEACHER def save(self, *args, **kwargs): is_new_user = not self.pk changed_fields = … -
RecursionError: maximum recursion depth exceeded while calling a Python object when updating choice field
model: StatusChoices = ( ("TODO", "todo"), ("DOING", "doing"), ("DONE", "done"), ) class Task(models.Model): status = models.CharField( choices=StatusChoices, default=StatusChoices[0], max_length=5, ) request body: { "id": 15, "content": "Updated Task Content", "creationDate": "2020-10-23", "user": 2 , "status": "DONE" } serialiser: class TaskUpdateSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ("status") view class TaskUpdateAPIView(APIView): def patch(self, request, pk): try: task = Task.objects.get(pk=pk) except Task.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = TaskUpdateSerializer(task, data=request.data, partial=True) if serializer.is_valid(): task.status = request.data.get("status", task.status) task.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) url: urlpatterns = [ path("task/update/<int:pk>", TaskUpdateAPIView.as_view(), name='update-task' ), ] New error: RecursionError: maximum recursion depth exceeded while calling a Python object What am I missing? -
Override error representation on import model page django
I'm working with a django application and don't wanted to show users the stack trace when there is any error occurred in production. For example, I've added validation to validate import action under before_import method, and when there is any issue in the validation it shows error message along with stack trace. Please refer screenshot below: Instead I wanted to just show the error message only. This is mainly for the security purpose as on production it will disclose my server directory structure to it's users. I tried couple of things, to override import.html under my templates directory, but it didn't worked. to override exception using LOGGING in settings.py It is great, if I can show list of errors for all affected rows in a CSV/XLSX file. -
How to Add 'rest_registration' URLs to Default Routers in Django REST Framework and Include Them in API Root?
I am using the 'rest_registration' package to handle user validation and registration in my Django REST API project. I would like to integrate the 'rest_registration' URLs with the default routers in Django REST Framework and have them included in the API root. Can someone please provide guidance on how to achieve this integration? Specifically, I want to know how to configure my project to include 'rest_registration' URLs in the default routers, and I'd like these URLs to be visible in the API root. from django.urls import path, include from rest_framework import routers from rest_framework import viewsets from rest_framework.response import Response class ServerStatusViewSet(viewsets.ViewSet): def list(self, request): return Response({'status': 'Server is running'}) router = routers.DefaultRouter() router.register(r'status', ServerStatusViewSet, basename='server-status') urlpatterns = [ path('', include(router.urls)), path('auth/', include('rest_registration.api.urls')), ] -
After making a reservation, the reserved time does not disappear from the list of available times
I am working on a project where you can arrange training with a trainer. And I have a problem with booking a training session, because after making a reservation, the time that was booked does not disappear from the available time. On the same day, another person can also book this hour. Models.py class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class WorkingHour(models.Model): time = models.CharField(max_length=10, unique=True, null=True) is_available = models.BooleanField(default=True) def reserve_hour(self): if self.is_available: self.is_available = False self.save() def __str__(self): return self.time class Trainer(BaseModel): trainer = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True) job = models.CharField(max_length=32, choices=type_job) working_hours = models.ManyToManyField(WorkingHour, related_name='trainers', null=True) def __str__(self): return f"{self.trainer.first_name} {self.trainer.last_name} - {self.job}" class TrainerServices(models.Model): name = models.CharField(max_length=64) price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name class Appointment(BaseModel): date = models.DateField() chosen_hour = models.ForeignKey(WorkingHour, on_delete=models.CASCADE, null=True) class TrainerAppointment(Appointment): trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE) services = models.ForeignKey(TrainerServices, on_delete=models.CASCADE) user = models.ForeignKey(MyUser, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return f"{self.user}-{self.services}" Forms.py class TrainerAppointmentForm(forms.ModelForm): chosen_hour = forms.ModelChoiceField( queryset=WorkingHour.objects.filter(is_available=True), empty_label=None, widget=forms.Select(attrs={"class": "form-select is_valid"}) ) class Meta: model = TrainerAppointment fields = "__all__" widgets = { "trainer": forms.Select(attrs={"class": "form-select is_valid"}), "date": forms.DateInput(attrs={"class": "form-control is_valid", "type": "date"}), "services": forms.Select(attrs={"class": "form-select is_valid"}), } def clean_date(self): date = self.cleaned_data.get('date') today = timezone.now().date() … -
Clean and Reusable Exception Handling in Django and DRF (Pythonic problem)
I'm working on a Django API project and I'm facing a challenge with exception handling. Specifically, I want to handle specific exceptions raised in my business logic and map them to corresponding Django REST framework (DRF) exceptions in a clean and reusable way. Here's a simplified version of my code: # My business logic class UserBusinessLogicLayer(Manager): """ This is the business logic layer for User management. """ def get_user_with_identifier(self, identifier: str, allow_username: bool = True) -> "User": # ... (omitting some code for brevity) user = self.filter(reduce(operator.or_, conditions)).first() if not user: raise self.model.DoesNotExist("User Does not exist.") if not user.is_active: logger.info( "The user with username/email/phone-number %s is not active", identifier, exc_info=True, ) raise DeactivatedUser( f"This account has been deactivated since {user.status_change}", user ) if not user.is_email_verified: logger.info( "The user %s hasn't verified the email", identifier, exc_info=True, ) raise NotVerifiedEmail("This account hasn't verified the its email") return user and this is how i use the code: try: user = User.bll.get_user_with_identifier(identifier, allow_username=False) except User.DoesNotExist as error: # this is how i normally handle the exceptions logger.info( "there is no user with username/email/phone-number %s", identifier, exc_info=True, ) raise exceptions.NotFound("Invalid input.") from error # this is api exception except Exception as error: # But I … -
arcpy.env.workspace not working in django. Its throwing this error AttributeError: ERROR 87934
class get_FeatureClassView(viewsets.ViewSet): def list(self, request, projectname): sgeometry = {} # Corrected variable name tgeometry = {} # Corrected variable name project_path = config.get('Paths', 'project_path') template_dir = config.get('Paths', 'template_dir') # project_path = r"D:\sreeraj\project\unbridge_backEnd" # Use a raw string or double backslashes project_path1 = os.path.join(project_path, projectname) print(project_path1) print(project_path) source_path = os.path.join(project_path1, "sourcegdb") # Use os.path.join for path concatenation print("----------", source_path) source_gdb = os.listdir(source_path)[0] print("source_gdb", source_gdb) source_gdb_path = os.path.join(source_path, source_gdb) print("sourceGDBPath", source_gdb_path) self.source_gdb_path = source_gdb_path target_path = os.path.join(project_path1, "targetgdb") # Use os.path.join for path concatenation target_gdb = os.listdir(target_path)[0] target_gdb_path = os.path.join(target_path, target_gdb) print("target_gdb_path", target_gdb_path) arcpy.env.workspace = source_gdb_path sourcefeature_classes = arcpy.ListFeatureClasses() #sourcefeature_classes.sort() print(sourcefeature_classes) for feature_class in sourcefeature_classes: desc = arcpy.Describe(feature_class) geometry_type = desc.shapeType sgeometry[feature_class] = geometry_type arcpy.env.workspace = os.path.join(target_gdb_path, "UtilityNetwork") # Use os.path.join for path concatenation targetfeature_classes = arcpy.ListFeatureClasses() #targetfeature_classes.sort() print(targetfeature_classes) for feature_class in targetfeature_classes: desc = arcpy.Describe(feature_class) geometry_type = desc.shapeType tgeometry[feature_class] = geometry_type featureclasslist = { "sourcefeature_classes": sgeometry, "targetfeature_classes": tgeometry } print(featureclasslist) return JsonResponse(featureclasslist) This throwing this error Traceback (most recent call last): File "C:\Users\sv67808\AppData\Local\miniconda3\envs\arcproenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\sv67808\AppData\Local\miniconda3\envs\arcproenv\lib\site-packages\django\core\handlers\base.py", line 197, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\sv67808\AppData\Local\miniconda3\envs\arcproenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\sv67808\AppData\Local\miniconda3\envs\arcproenv\lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File … -
How to upload media files to AWS S3 within Django app without getting a ClientError
I'm getting the following error when I try to upload images within the admin panel, 'An error occurred (AccessControlListNotSupported) when calling the PutObject operation: The bucket does not allow ACLs'. I've setup the settings.py file and AWS according to the django-storages docs, but still not working. All Static files are being imported in and can be read Also tried changing the AWS_DEFAULT_ACL to 'none' and 'public-read-write' but still not working. settings.py config: if USE_S3: # aws settings AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = public-read AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} #Additional settings AWS_S3_FILE_OVERWRITE = False AWS_QUERYSTRING_AUTH = False # s3 static settings AWS_STATIC_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_STATIC_LOCATION}/' STATICFILES_STORAGE = 'myproject.storages.StaticStore' # s3 media settings AWS_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'myproject.storages.MediaStore' else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) AWS Bucket Policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "Statement1", "Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::my-bucket/*" }, { "Sid": "Statement2", "Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::my-bucket/" } ] } -
Godaddy not sending emails throws SMTPAuthenticationError on Django
I have the following settings on my settings file in django EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_HOST_USER = 'email@website.com' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = "password" EMAIL_PORT = 587 EMAIL_USE_SSL = False EMAIL_USE_TLS = True and when I try and send an email it throws this error SMTPAuthenticationError at /contact-ajax (535, b'5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit https://aka.ms/smtp_auth_disabled for more information. [BYAPR02CA0052.namprd02.prod.outlook.com 2023-10-25T10:46:26.078Z 08DBD4986B1B4B4D]') ... Traceback: File "/home/sammy/webapp/envs/prestige/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/sammy/webapp/envs/prestige/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/sammy/webapp/envs/prestige/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/sammy/webapp/envs/prestige/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/home/sammy/webapp/prestige/prestige/views.py" in contact_ajax 130. msg.send() I know the logins are fine because I've just logged in with them to godaddy webmail I know there's no need for app password for this -
How to get InMemoryFileUpload video file's duration in django
I've searched about that in the SO, but there solutions with video file's path. I need to get file's duration by InMemoryFileUpload or BytesIO in django. How can do that? from moviepy.editor import VideoFileClip def video_skip_validator(data): video_file = data.get("video") video = VideoFileClip(video_file) print(video.duration) It raises 'InMemoryUploadedFile' object has no attribute 'endswith' error. -
API returns not found but the endpint is correct
I have a Django Rest Framework Endpoint urlpatterns_usersettings = [ path("usersettings/<int:pk>/", UpdateUserSettings.as_view()) ] and a view to deal with that endpoint: class UpdateUserSettings(generics.UpdateAPIView): permission_classes = [IsAuthenticated] serializer_class = UserSettingsSerializer def get_queryset(self): user = self.kwargs["pk"] return UserSettings.objects.all().filter(user=user) Here is the model: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class UserSettings(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_settings") # ACCOUNT SETTINGS gotodash = models.BooleanField(default=False) loginalert = models.BooleanField(default=False) # DISPLAY SETTINGS darkmode = models.BooleanField(default=False) button_color = models.CharField(max_length=10, null=True, blank=True) link_color = models.CharField(max_length=10, null=True, blank=True) heading_color = models.CharField(max_length=10, null=True, blank=True) title_color = models.CharField(max_length=10, null=True, blank=True) tab_color = models.CharField(max_length=10, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "user settings" verbose_name_plural = "users settings" db_table = "users_settings" def __str__(self): return f"{self.user}'s settings" and here is the serializer: from rest_framework import serializers from .models import UserSettings from django.contrib.auth import get_user_model User = get_user_model() class UserSettingsSerializer(serializers.ModelSerializer): class Meta: model = UserSettings fields = "__all__" If I call the endpoint I get a 404 error and in the response it says detail not found, but if I do a breakpoint and manually get the object then it works fine I can get the object, so why can the view … -
"Rollup" fields in OpenTelemetry to sum values from child spans
I'm currently in the process of migrating my Django application monitoring from beeline to OpenTelemetry. One feature of beeline was the add_rollup_field function which can specify a field to be summed in a trace's root span. For example, if we add a db.total_duration rollup field, we can use that to sum all of the db.duration values for a root span. What would be the best way to implement this in OpenTelemetry? Is there a good way to pass these values to parent spans and eventually to the root span? I've looked into Baggage but that appears to mainly be used to update a context for passing down the call stack, not up. -
How to get the name of the file that the user can download?
I have a django view that returns a FileResponse - return FileResponse(protected_pdf_file, as_attachment=True, filename='result.pdf') I am getting this response using ajax - function ajaxSend(url, data) { fetch(url, { method: 'POST', body: data, }) .then(response => { if (content_type === 'application/json') { return response.json(); } else { return response.blob(); } }) .then(data => { if (data instanceof Blob) { const url = URL.createObjectURL(data); download_link.href = url; // download_link.download = ... download_link.style.display = 'block'; } else { block_msg.textContent = data.message; } }) .catch(error => console.error(error)) } Where "download_link.download = ..." I need to substitute the file name. I tried to get the file name - const contentDisposition = response.headers.get('Content-Disposition');, but contentDisposition is null as a result. Please tell me how to get the name of the file returned from the server? -
I cannot connect pip to download any packages
I am new to programming, but my computer seems unable to utilise pip, here is an example of an error I got, I've also tried extending the duration of the connect (forcibly closed by connection host) and tried a tonne of different ways to ask it to install django even specific versions anything that requires connection through pip does not work, ive diabled ipv6 and completely turned off all my firewall safety's, jumbo packets arent a system setting I can change I feel like I'm running out of ideas here, I've been to about 150 different pages today, my goal was to get django working, which I have successfully created a virtual environment for and used git to put django into, but when I attempt to finish setting up django by installing that way in the environment, it needs to download dependencies from somewhere which again result in it getting stuck, can my computer not communicate properly with the websites? I can use curl to view the sources that were layed out and both curl and ping show a perfectly fine connection to these places, I am on a stable internet connection and have tried using a different internet connection … -
Modify Django "Select Form" Icon
I am making a Django app, and I am using Django's form.ChoiceFields to make a form! brand = forms.ChoiceField( label="Marca:", choices=[('', 'Selecionar marca')] + [(brand.id, brand.name) for brand in models.Brand.objects.all()], widget=forms.Select(attrs={'id': 'brand', 'onchange': 'filterModels()', 'class': 'select'}) ) So this is the form element that I get (with a background color), but I want to change the icon pointing up and down in the right but I cannot figure how to do it. I already tried to do it by adding an icon form FontAwesome but the problem is that when I do so, when I click on the icon the form does not open, so it can confuse the users :( I tried adding javascript codes by using implementing the click() function when clicking on the icon but it did not give me any results. So is there a way to do this by simply replacing Django's "Select Form" default arrow icon? Thanks in advance! -
How can I achieve filtering with multiple values for the same parameter in Django?
I am building a Django website that displays snowboards that will fit you based on some parameters. One of the parameters is gender and for example if the user specifies she is a girl, then I want to display Female as well as Unisex boards - and also then filter again by all the other parameters (height, style, level, etc). Same for the boys. I want to also display Male boards as well as Unisex boards. This is the code snippet in my TemplateView: def get(self, request, *arg, **kwargs): gender = request.GET.get('gender') skills = request.GET.get('skills') style = request.GET.get('style') rider_name = request.GET.get('rider_name').split("'")[1].split("'")[0] filter = process_queryset(gender, skills, style) queryset = Snowboard.objects.filter( gender=filter['gender'], style=filter['style'], level=filter['level'], ) return render(request, self.template_name, {'gender': gender, 'snowboards': queryset, 'rider_name': rider_name}) and I have this separate function for processing the filtering: def process_queryset(gender, skills, style): filter_dict = {'gender': 'Female' if gender == 'girl' else 'Male', 'level': 'Beginner' if 'rookie' in skills else 'Intermediate-Advanced'} if style == 'freestyle': filter_dict['style'] = 'Park' elif style == 'freeride': filter_dict['style'] = 'Free Ride' else: filter_dict['style'] = 'All mountain' return filter_dict So I first tried to filter by the gender and have them both (tried both with | and with &) and then nest the … -
Change the parent lookup kwarg in nested routes using Django REST Framework
In this project we use Django, Django REST Framework, DRF Nested Routers and DRF Spectacular. Let's say that we have the model classes Category and Product. We have a nested route: /categories/<category_pk>/products/<pk>/ In the Swagger UI (generated by DRF Spectacular) it is displayed as: /categories/{category_pk}/products/{id}/ I want to change the parent lookup keyword argument to be category_id, but I couldn't find a way to do it.