Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Override Save to create multiple objects for range()
I want to override Django form save method to be able to create multiple objects at once. I have an AvailableHours model : class AvailableHours(models.Model): free_date = models.ForeignKey(AvailableDates,null=True, blank=True,on_delete=models.CASCADE,related_name='freedate') free_hours_from = models.IntegerField(null=True, blank=True) free_hours_to = models.IntegerField(null=True, blank=True,) status = models.BooleanField(null=True,default=True,) and I have a ModelForm for this class : class TimeGenerator(forms.ModelForm): class Meta: model = AvailableHours fields = ['free_date','free_hours_from','free_hours_to','status'] def save(self, commit=True): m = super(TimeGenerator, self).save(commit=False) self.free_hours_from = self.cleaned_data['free_hours_from'] self.free_hours_to = self.cleaned_data['free_hours_from'] +1 m.save() for hour in range(self.cleaned_data['free_hours_from'],self.cleaned_data['free_hours_to']+1): self.free_hours_from = self.cleaned_data['free_hours_from']+hour self.free_hours_to = self.cleaned_data['free_hours_from']+hour+1 print(hour) m.save() I want to create multiple AvailableHours object like this: if the form is set free_hours_from = 13 and free_hours_to=16 so the save method creates 13-14 , 14-15, 15-16 I wrote a code above in forms and overrided save() but its not working. anyone has a solution ? -
Django app making methods available to other apps written by third parties. How to define what is an 'external' api and what isn't?
We are creating a large Django program in which we expect other teams to write apps that will plug into and run within our Django program. We want our main app to provide some helper methods, type definitions etc that are freely available for other aps to utilize. So far that's easy, they just import our module and run whatever method they want. However we don't want all our methods to be treated as a public api available to other apps. Methods other apps use must be maintained for backwards compatibility, better documented etc after all. We want some methods to be used only internal to our app and would prefer end users not call them; or at the very least that they know we made no guarantee of not changing those methods in future releases. Now we could go around appending a _ in front of every method we don't want other apps using, but they aren't really private methods in my mind, since they are publicly available to other modules within our app. In addition well we already have allot of the app written and I don't want to go back and retroactively refactor half of our methods. … -
Websocket how to receive two request chatgpt at the sametime
I have a websocket (in Django) to receive request from client (reactjs). The request calls chatgpt api to stream its response to client. class GPTAPIConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def receive(self, text_data): data = json.loads(text_data) print('Start', data['requestID']) asyncio.create_task(self.streamToClient(data['requestID'])) async def streamToClient(self, requestID): completion = openai.ChatCompletion.create(...) content = '' for chunk in completion: if chunk['choices'][0].get('delta', {}).get('function_call'): chunkContent = chunk['choices'][0]['delta']['function_call']['arguments'] if chunkContent is not None: content += chunkContent await self.send(text_data=json.dumps({'text': content})) print('End', requestID) From client, I sent two messages with requestID 1 and 2. In server, the request 1 took about 10 seconds to finish so the log is: Start 1 End 1 Start 2 End 2 What I want is: Start 1 Start 2 End 1 or End 2 (depends which one ends first) Please help me! Thank you! -
Buy and sell products?
This app allows for bidding but I want someone who isn't logged in to not be able to bid and tell them they need to be logged in to be able to bid. Even though I wrote the code in the function and the person who entered the site can make an offer, but it gives this error. And how can I close the auction and introduce someone as a buyer? Are the codes I wrote suitable for this? error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/? next=/build/1/ Using the URLconf defined in commerce.urls, Django tried these URL patterns, in this order: admin/ [name='index'] login [name='login'] logout [name='logout'] register [name='register'] product_detail/<int:product_id>/ [name='product_detail'] watchlist/<str:username>/ [name='watchlist'] add/<int:productid>/ [name='add'] remove/<int:pid>/ [name='remove'] category/<str:name>/ [name='category'] category_2 [name='category_2'] create/ [name='create'] build/<int:product_id>/ [name='build'] accept/<int:product_id><int:bid_id>/ [name='accept'] ^media/(?P<path>.*)$ The current path, accounts/login/, didn’t match any of these. models.py: class List(models.Model): choice = ( ('d', 'Dark'), ('s', 'Sweet'), ) user = models.CharField(max_length=64) title = models.CharField(max_length=64) description = models.TextField() category = models.CharField(max_length=64) first_bid = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to="img/", null=True) image_url = models.CharField(max_length=228, default = None, blank = True, null = True) status = models.CharField(max_length=1, choices= choice) seller = models.ForeignKey(User, on_delete=models.CASCADE) winner = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, related_name='winner') … -
Django-haystack with AWS Opensearch
I am trying to implement a project which I have running locally but want to implement on AWS. I am running locally in a Docker container and I am running an instance of ElasticSearch for the project. In production I want to run AWS OpenSearch. When I run manage.py update_index using the docker container elastic search everything works. When I try and implement on AWS with OpenSearch I get the following. GET https://opensearch-instance.eu-west-2.es.amazonaws.com:443/haystack-local/_mapping [status:401 request:0.151s] Undecodable raw error response from server: Expecting value: line 1 column 1 (char 0) PUT https://opensearch-instance.eu-west-2.es.amazonaws.com:443/haystack-local [status:401 request:0.087s] Undecodable raw error response from server: Expecting value: line 1 column 1 (char 0) POST https://opensearch-instance.eu-west-2.es.amazonaws.com:443/haystack-local/modelresult/_bulk [status:400 request:0.061s] POST https://opensearch-instance.eu-west-2.es.amazonaws.com:443/haystack-local/modelresult/_bulk [status:400 request:0.060s] POST https://opensearch-instance.eu-west-2.es.amazonaws.com:443/haystack-local/modelresult/_bulk [status:400 request:0.058s] POST https://opensearch-instance.eu-west-2.es.amazonaws.com:443/haystack-local/modelresult/_bulk [status:400 request:0.058s] POST https://opensearch-instance.eu-west-2.es.amazonaws.com:443/haystack-local/modelresult/_bulk [status:400 request:0.058s] --- Logging error --- Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/haystack/management/commands/update_index.py", line 119, in do_update backend.update(index, current_qs, commit=commit) File "/usr/local/lib/python3.11/site-packages/haystack/backends/elasticsearch_backend.py", line 239, in update bulk( File "/usr/local/lib/python3.11/site-packages/elasticsearch/helpers/__init__.py", line 257, in bulk for ok, item in streaming_bulk(client, actions, **kwargs): File "/usr/local/lib/python3.11/site-packages/elasticsearch/helpers/__init__.py", line 188, in streaming_bulk for data, (ok, info) in zip( File "/usr/local/lib/python3.11/site-packages/elasticsearch/helpers/__init__.py", line 99, in _process_bulk_chunk raise e File "/usr/local/lib/python3.11/site-packages/elasticsearch/helpers/__init__.py", line 95, in _process_bulk_chunk resp = client.bulk('\n'.join(bulk_actions) + '\n', **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/elasticsearch/client/utils.py", … -
Django optional, non-capturing string in URLs
I am trying to add prefix parameter to our api url's for our application implemented in Python Django. It is currently like this urlpatterns= [ path("api/", include( [ path("books/", include(books.urls)), path("events/", include(events.urls)), path("meetings/<str:group_id>/", handle_meetings) ]) ) ] Now what I want to do is make this api a non-capturing and optional parameter. By non-capturing I mean I want the parameter to be in the URL but not go to the views and handlers. I don't want to add it as a parameter to my views and handlers because I won't use it for now. And I want it to be optional. I will now show what I want to achieve in examples /api/books - should work /api_v1/books - should work /books - should work This being non-capturing is not the most meaningful function because the user can basically enter anything. But it is just a temporary solution and this is how we decided to go. Is this even possible? If this is not possible, I am okay with giving up on making it non-capturing as well. I still couldn't fix it. So in that case you can think of it as this. path("books/", include(books.urls)), path("events/", include(events.urls)), path("meetings/<str:group_id>/", handle_meetings) I have … -
Django query with Q filter _lte on DateField (tz=True) doesn't work
I got an Invoice model as models.DateTimeField() with a few records containing several dates: With an HTML form, I want to filter by dates <input name="start" class="form-control me-3" type="date" value="{{ min_date|date:'Y-n-d' }}" /> I got the same field for end date and when I print them in my view, they seem to be in the correct format 2023-11-12 -> 2023-11-17. In my view, I check if the two fields contain values and if yes, I filter my Invoice queryset: I tried lotsa combinations for queryset filtering and every time, the __lte clause seems not to work correctly and results don't include my end date. __lt is applied instead of __lte. Among those combinations I tried : if request.method == 'GET': # limit records number if no filter invoices = Invoice.objects.all()[:100] else: start = request.POST.get('startDate') end = request.POST.get('endDate') invoices = Invoice.objects.all() if start: invoices = invoices.filter(created_at__gte=start) if end: invoices = invoices.filter(created_at__lt=end) also tried : [...] else: start = request.POST.get('start') end = request.POST.get('end') if start and end: invoices = invoices.filter( Q(created_at__gte=start) & Q(created_at__lte=end)) if end and not start: invoices = invoices.filter(Q(created_at__lte=end)) if not end and start: invoices = invoices.filter(Q(created_at__gte=start)) First, I thought it was due to the warning about ("DateTimeField %s received … -
python-docx-template and {%tr for a loop and if condition error
I'm using the python package python-docx-template in a django project. I'm trying to build a table with a condition to display some rows. I'm trying to nest a '{%tr' of an if statement in a 'for' loop one : This lead to an error : emplateSyntaxError at /reports/employee/73/2/ Encountered unknown tag 'tr'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'. 1/ If I remove the 'tr' of the 'if' statement, all works great, but it print empty rows (those of the 'if' and 'endif'). 2/ If I remove the 'tr' of the 'for' loop (so keep the one of the 'if'), I've got the error : Encountered unknown tag 'tr'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'. I can not modify datas send to render the template. How can I conditionally print those rows? -
during client authentication in Keycloak. null value returned by getAuthenticationSession()
I attempted to obtain a token from the Keycloak server using the password grant. However, after changing the user password and making some modifications to the authentication process, I encountered the following error: I made an attempt to resolve the issue by restarting the Keycloak server, as well as restarting and modifying the grant, but unfortunately, the problem persists 2023-11-21 16:43:52,510 WARN [org.keycloak.events] (executor-thread-37) type=LOGIN_ERROR, realmId=7ffc23bd-250e-429e-8026-14cff8c6bdef, clientId=Print_login_protect, userId=null, ipAddress=172.20.67.92, error=invalid_user_credentials, auth_method=openid-connect, auth_type=code, response_type=code, redirect_uri=http://localhost:9000/home, code_id=40bf3e47-17b9-44f4-837b-508490fd71c9, response_mode=query 2023-11-21 16:45:41,979 ERROR [org.keycloak.services] (executor-thread-36) KC-SERVICES0015: Unexpected error when authenticating client: java.lang.NullPointerException: Cannot invoke "org.keycloak.sessions.AuthenticationSessionModel.getExecutionStatus()" because the return value of "org.keycloak.authentication.AuthenticationProcessor.getAuthenticationSession()" is null at org.keycloak.authentication.DefaultAuthenticationFlow.isProcessed(DefaultAuthenticationFlow.java:68) at org.keycloak.authentication.DefaultAuthenticationFlow.isProcessed(DefaultAuthenticationFlow.java:63) at org.keycloak.authentication.DefaultAuthenticationFlow.processSingleFlowExecutionModel(DefaultAuthenticationFlow.java:373) at org.keycloak.authentication.DefaultAuthenticationFlow.processFlow(DefaultAuthenticationFlow.java:249) at org.keycloak.authentication.AuthenticationProcessor.authenticateClient(AuthenticationProcessor.java:897) at org.keycloak.protocol.oidc.utils.AuthorizeClientUtil.authorizeClient(AuthorizeClientUtil.java:50) at org.keycloak.protocol.oidc.endpoints.TokenEndpoint.checkClient(TokenEndpoint.java:269) at org.keycloak.protocol.oidc.endpoints.TokenEndpoint.processGrantRequestInternal(TokenEndpoint.java:217) at org.keycloak.protocol.oidc.endpoints.TokenEndpoint.processGrantRequest(TokenEndpoint.java:190) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:154) at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:118) at org.jboss.resteasy.core.ResourceMethodInvoker.internalInvokeOnTarget(ResourceMethodInvoker.java:560) at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTargetAfterFilter(ResourceMethodInvoker.java:452) at org.jboss.resteasy.core.ResourceMethodInvoker.lambda$invokeOnTarget$2(ResourceMethodInvoker.java:413) at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:321) at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:415) at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:378) at org.jboss.resteasy.core.ResourceLocatorInvoker.invokeOnTargetObject(ResourceLocatorInvoker.java:174) at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:142) at org.jboss.resteasy.core.ResourceLocatorInvoker.invokeOnTargetObject(ResourceLocatorInvoker.java:168) at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:131) at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:33) at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:429) at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:240) at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:154) at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:321) at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:157) -
multiply in aggregation of django
Our View get a JSON like this : { "cart":{ "pizza": 2, "burger": 3 } } In cart is the foods name, and count of the food . My food model: class Food(models.Model): name = models.CharField(verbose_name=_('name'), max_length=100, unique=True, blank=False, editable=True) price = models.IntegerField(verbose_name=_("maximum price"), null=False, blank=False, editable=True) discount = models.PositiveIntegerField(validators=[MaxValueValidator(100)], null=False, blank=False, default=0) created_at = models.DateTimeField(verbose_name=_("created time"), auto_now_add=True, editable=False) I want to calculate the total price how I can do that with aggregation and annotate in Django ? NOTE: every food has a price that should be multiplied on count of that food. i have done this in a for loop : class OrderView(APIView): def post(self, request): srz_data = CartSerializer(data=request.data) if srz_data.is_valid(): cart_order = srz_data.data['cart'] foods = Food.objects.filter(name__in=cart_order) total_price = 0 for i,n in cart_order.items(): total_price += foods.get(name=i).price * n and done some experiment on aggregation : class OrderView(APIView): def post(self, request): srz_data = CartSerializer(data=request.data) if srz_data.is_valid(): order = srz_data.data['cart'] f = Food.objects.filter(name__in=order).aggregate(Sum('max_price')) But after a day i couldn't find a answer for this, if someone can help i will very appreciate it. thanks -
Create view that shows all objects relating to current user's department
I have the following Django model: from django.conf import settings from django.db import models class Appeal(models.Model): DEPARTMENTS = [ ("a", "DeptA"), ("b", "DeptB"), ("c", "DeptC"), # long list of departments here ] title = models.CharField(max_length=400) department = models.CharField(choices=DEPARTMENTS) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="appeals" ) And a view like this: from django.shortcuts import get_list_or_404, render def appeal_list_view(request): visible_appeals = get_list_or_404(Appeal, author=request.user) return render(request, "appeals/index.html", {"appeals": visible_appeals}) This shows only the appeals by the current user. I would like to change this code so that: each user is associated with a department, a user is shown all appeals from their own department (regardless of whether or not they or another user from the same department submitted it). What would be the best way to achieve this? I considered creating a group per department, which would solve the first requirement but then I'm not sure how to approach the second one. -
DJango WOPI server error when submit iframe
I'm implementing a custom wopi server to communicate a custom documenty library with office 365. The implementation is based on a django server which implements all wopi endpoints. That server communicates a cloud document library server with wopi. The problem is that when I submit the iframe to open a document with the office 365 I get the following error in javascript: [![enter image description here][1]][1] I searched for that error on the web, but all the solutions implies modify office 365 code. The index.html that I'm using is the following: <!DOCTYPE html> <html lang="en"> <head> <title>vvwopi</title> <link rel="stylesheet" href="../static/css/bootstrap.min.css"> <script src="../static/js/jquery-3.6.1.min.js"></script> <script src="../static/js/bootstrap.min.js"></script> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"> <link rel="shortcut icon" href="https://c1-word-view-15.cdn.office.net/wv/resources/1033/FavIcon_Word.ico" /> <style> body { margin: 0; padding: 0; overflow: hidden; -ms-content-zooming: none; } #office_frame { width: 80%; height: 80%; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: 0; border: none; display: block; } </style> </head> <body> <div id="wopiTest"> <h1>VisualVault WOPI Test</h1> <p> Use this page to demo the WOPI host implementation </p> <p> Discovery file: https://ffc-onenote.officeapps.live.com/hosting/discovery </p> <button class="wopi_editDoc_button" id="vwWopiTest" onclick="formSubmit('office_wopiTest_form')">Wopi Test Document</button> <form id="office_form" name="office_form" target="office_frame" action="" method="post"> <input name="access_token" value="" type="hidden" /> <input name="access_token_ttl" value="" type="hidden" /> … -
How do I run two different webservers from my django project with gunicorn?
My django project has a webserver, which I run with gunicorn. Now, I have also developed a gRPC-server, which I also need to deploy, preferrably also with gunicorn. The gRPC server has a different entrypoint, e.g. within myapp.management.grpc_downloader there's the class GRPCDownloader and that has a method run_server()`. I somehow need to hand this method to gunicorn, in such a way that I can run this as a separate service in systemd, or in Docker once I containerize this. How do I achieve this? Do I just write a second wsgi.py file, e.g. wsgi_grpc.py? And what should I write in there? The current one was automatically generated. -
im facing problem with rendering the profile picture in django
TemplateSyntaxError at /profile/1 Invalid block tag on line 14: 'static', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/profile/1 Django Version: 4.1.13 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 14: 'static', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? Exception Location: C:\Users\hrush\anaconda3\envs\djangopython\Lib\site-packages\django\template\base.py, line 558, in invalid_block_tag Raised during: main.views.user_page Python Executable: C:\Users\hrush\anaconda3\envs\djangopython\python.exe Python Version: 3.11.5 Python Path: ['C:\Users\hrush\OneDrive\Desktop\eventapp\core', 'C:\Users\hrush\anaconda3\envs\djangopython\python311.zip', 'C:\Users\hrush\anaconda3\envs\djangopython\DLLs', 'C:\Users\hrush\anaconda3\envs\djangopython\Lib', 'C:\Users\hrush\anaconda3\envs\djangopython', 'C:\Users\hrush\anaconda3\envs\djangopython\Lib\site-packages'] Server time: Mon, 20 Nov 2023 23:30:41 +0530 Error during template rendering In template C:\Users\hrush\OneDrive\Desktop\eventapp\core\templates\profile.html, error at line 14 -
Problem with event listening on Select2 element - Django
Initializes the Select2 element by creating a widget and plugging it into the form. [forms.py] class S2SelectWidget(s2forms.Select2Widget): search_fields = ( 'name__icontains', ) class MyForm(forms.ModelForm): class Meta: model = MyModel fields = ('field1', 'field2', 'field') widgets = { 'field1': S2SelectWidget(), } [html] $(document).ready(function() { myField = $('#id_field1'); console.log(myField); myField.on('change', function() { console.log('ok') }) }); I don't receive a message in the console that an item has changed. When I use the click method and click on the label, the message is displayed. What technique do I need to use to listen to my element using the change method? Thanks. -
How to share the django app in the Network?
We can share the Flask app in network by passing host='0.0.0.0' as argument in app.run(). Example: app.run(host='0.0.0.0') And the flask gives links for both localhost (127.0.0.1:5000) and for the network (ip_address:5000). How can I achieve same for the Django? I've tried passing '0.0.0.0' and the 'ip_address' in ALLOWED_HOST list in settings.py but did'nt worked. I know about command: python manage.py runserver ip_address:8000 but then app is not accessed by localhost:8000 :(. I want to access django app by both localhost as well as ip_address of device. How can I do it? -
combine foreign key with fsm field in django-fsm
import datetime from django.db import models from django_fsm import FSMField, transition class WorkFlowState(models.Model): name = models.CharField(max_length=64, unique=True) preceding = models.ForeignKey( 'self', on_delete=models.CASCADE, blank=True, null=True) # postAction = models.CharField(max_length=64, null=True, blank=True) default_warn1 = models.DurationField( blank=False, null=False, default=datetime.timedelta(hours=12)) default_warn2 = models.DurationField( blank=False, null=False, default=datetime.timedelta(days=1)) default_duration = models.DurationField( blank=False, null=False, default=datetime.timedelta(days=1)) def __str__(self): return self.name class Transition(models.Model): name = models.CharField(max_length=64) source_state = models.ForeignKey(WorkFlowState, on_delete=models.CASCADE, related_name='transitions_from') target_state = models.ForeignKey(WorkFlowState, on_delete=models.CASCADE, related_name='transitions_to') def __str__(self): return self.name class Task(models.Model): name = models.CharField(max_length=100) assigned_on = models.DateTimeField(auto_now=True) created_on = models.DateTimeField(auto_now_add=True) task_state = FSMField(models.ForeignKey(WorkFlowState, on_delete=models.PROTECT), protected=True) def __str__(self): return self.task_state def perform_transition(self, transition_name): try: transition = Transition.objects.get(name=transition_name, source_state=self.task_state) setattr(self, 'assigned_to', transition.target_state) self.save() return True except Transition.DoesNotExist: return False I want to have a workflow state the that is a foriegn key to worlflowstate. first i create a transition model that can define states for fsm transition andi tried to define it as you see but it doent work. it store task status like a string -
Database migration from MySQL to Postgres Schema
I'm currently working on migrating a Django project that was initially using MySQL to PostgreSQL. The project involves multi-tenancy with separate schemas managed by django-tenants. I'd like some guidance on the best practices for migrating the database while ensuring compatibility with django-tenants. Are there specific steps or considerations I should be aware of to successfully transition from MySQL to PostgreSQL in this scenario? Any advice or examples related to migrating databases with django-tenants and multi-tenancy would be greatly appreciated. Thanks in advance! -
How to save Many to many field in Django?
I'm writing a function for a put request in Django. I have a many to many field and I have a problem updating this field. Here is my function @method_permission_classes([IsAdministratorManyToMany]) def update(self, request, *args, **kwargs): instance = self.get_object() request_data=request.data for field in ["services"]: if field in request_data: request_data[field] = request_data[field].split(",") serializer = self.get_serializer(data=request_data) print(serializer) serializer.is_valid(raise_exception=True) if serializer.validated_data.get("avatar"): try: if instance.avatar: instance.avatar.delete() except Exception as error: return Response( f'Error when update Institution avatar. {error}', status=status.HTTP_400_BAD_REQUEST, ) serializer.save() return Response(serializer.data) def perform_update(self, serializer): instance = serializer.instance instance = self.get_object() if serializer.validated_data.get("avatar"): try: if instance.avatar: instance.avatar.delete() except Exception as error: return Response( f'Error when update Institution avatar. {error}', status=status.HTTP_400_BAD_REQUEST, ) serializer.save() My serializer: class InstitutionSerializer(serializers.ModelSerializer): class Meta: model = Institution fields = ( "id", "avatar", "name", "working_hours", "services", "address", "location_lon", "location_lat", "email", "is_call_to_home", "is_emergency_call", "document", "status", "comments", "administrators", "managers", ) read_only_fields = ('status','administrators','managers') My model: class Institution(models.Model): """ Pet's parasite treatment """ avatar = models.ImageField( verbose_name=_("Avatar"), upload_to=upload_avatar, blank=True, ) name = models.CharField( verbose_name=_("Name"), max_length=256, ) working_hours = models.JSONField( verbose_name="Working schedule", ) services = models.ManyToManyField( to=InstitutionServices, verbose_name="Перелік послуг" ) address = models.CharField(max_length=256, verbose_name="Institution addres") location_lon = models.FloatField(null=True, blank=True, verbose_name="longitude") location_lat = models.FloatField(null=True, blank=True, verbose_name="latitude") email = models.EmailField(verbose_name="E-mail") is_call_to_home = models.BooleanField(default=False, verbose_name="Виклик до дому") is_emergency_call … -
How do I test ExportActionMixin in Django?
I'd like to test files produced on the admin website by import_export.admin.ExportActionMixin in Django. In particular I'd like to test the admin command by looking into the file (which I download on the admin website) and test the files contents. But I don't quite understand how to do it. My admin model: @admin.register(MyModel) class MyModelAdmin(ExportActionMixin, admin.ModelAdmin): resource_class = MyResource My resource class: class MyResource(resources.ModelResource): class Meta: model = MyModel headers = ('User ID', 'name') fields = ('user__id', 'user__name') def get_export_order(self): return self.Meta.fields def get_export_headers(self): return self.Meta.headers def get_queryset(self): queryset = super(MyModel, self).get_queryset() return queryset.select_related('user') My test: class MyTestCase(TestCase): def setUp(self): self.client = Client() user = User.objects.create(login="admin", email="admin@example.com", password="password") user.is_staff = True user.is_superuser = True user.save() self.client.login(username="admin", password="password") def test_import(self): url = reverse('/admin/project/mymodel') data = {'action': 'export_admin_action', 'file_format': 0, '_selected_action': 1} response = self.client.post(url, data=data, follow=True) self.assertEqual(200, response.status_code) self.assertEqual('text/csv', response['Content-Type']) self.assertTrue(response.has_header('Content-Disposition')) My test returns status code 200 (I assume the post request is successful) but the second assertion fails: AssertionError: 'text/csv' != 'text/html; charset=utf-8'. But I need to get the requested file and then test its contents. How can I do that? -
How can I use Azure AppInsights with OpenTelemetry in Django
Hi I have a Django app and I wanted to connect my traditional logs with Azure AppInsights. I'm using logging lib for my logs and this piece of code occurs in 100 times in the project. import logging logger = logging.getLogger(__name__) When I checked the open telemetry Azure docs I found the following example but to use this one I have to change all the logger instances because we need to add handler for open telemetry and an exporter for Azure. Is there any way to do it without changing all the logger occurrences? logger_provider = LoggerProvider() set_logger_provider(logger_provider) exporter = AzureMonitorLogExporter.from_connection_string( os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] ) get_logger_provider().add_log_record_processor(BatchLogRecordProcessor(exporter, schedule_delay_millis=60000)) # Attach LoggingHandler to namespaced logger handler = LoggingHandler() logger = logging.getLogger(__name__) logger.addHandler(handler) logger.setLevel(logging.INFO) -
fcm-django add extra params
I use drf and fcm-django for pushing notifications to user devices (android/ios) (with firebase) My Notification model: class Notification(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, max_length=128) user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) message_type = models.CharField(choices=NotificationType.CHOICES, blank=True, null=True, max_length=32) link = models.URLField(null=True, blank=True) title = models.CharField(max_length=100) body = models.TextField() unread = models.BooleanField(default=True, blank=False,) I need to add extra params "message_type" and "link", something like this: devicesGCM.send_message(body, title=title, type=message_type, link=link) How can I add extra param to notification message. -
How to show dataTable.Buttons in django app
I utilized dataTable.view to show particular data in my Django app and I'd like to show buttons such as csv and excel. I add buttons in options but when I want to construct them (according to the document), this error: $.fn.dataTable.Buttons is not a constructor appears. I also added buttons.dataTables.min.js , buttons.html5.min.js, buttons.foundation.min.js in the UI. var options = { ..... buttons: [ 'excel', 'csv' ], sDom: 'Bfrtip' }//end of defaultDataTableOptions var datatable = datatableview.initialize($('.datatable'), options); var table = $('#DataTables_Table_0').DataTable(); new $.fn.dataTable.Buttons( table, { buttons: [ 'copy', 'excel' ] } ); table.buttons().container().appendTo( $('#buttons', table.table().container() ) ); $.fn.dataTable.Buttons is not a constructor -
Image from django database showing as path
I am trying to display images from my Django database. But this is what I'm getting. enter image description here I have the images saved here: enter image description here and this is my code: Html: {% for image in images %} <div class="img"> {{ image.photo }} <img class="cardImg2" src=" {{ image.photo.url }} " alt=""> </div> {% endfor %} Views.py: def detail(request, product_id): product = get_object_or_404(Product, pk=product_id) images = Photo.objects.filter(product=product) return render(request, "kin/detail.html", { "product": product, "images": images }) I want the images to display as actual images and not stringed paths. How do I achieve this? -
Celery task result persistent strategy
I have a web server, a rabbitMQ server and two task processing servers in the system. Using Celery to manage the tasks. The web server needs to query the status of the tasks. Based on Celery's doc, I can choose database as result backend. In this case, should I set a database for the web server and another database for each task processing server or use one database for all these 3 servers? I also tried to use RPC as the backend, but each time the web server restarts, the status of tasks are "PENDING" after querying from AsyncResult. This is my configuration of Celery. CELERY_RESULT_BACKEND = 'rpc://' CELERY_RESULT_PERSISTENT = True CELERY_TRACK_STARTED = True CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_RESULT_EXPIRES = None Anyone can help? Thanks!