Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error when im trying to install psycopg2 :(
note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for psycopg2 Failed to build psycopg2 ERROR: Could not build wheels for psycopg2, which is required to install pyproject.toml-based projects Python 3.12 requirements.txt: asgiref==3.2.10 Django==3.1 pytils==0.4.1 pytz==2022.7.1 sqlparse==0.4.3 I have read all the other articles on this topic. Installed vs build tools c++ -
How to implement Django's ConditionalGetMiddleware to compare `If-Modified-Since` in the req. headers with `Last-Modified` in the res. headers?
I'm trying to implement conditional caching using django.middleware.http.CondtionalGetMiddleware. I'm able to correctly return 304/200 if I provide an If-None-Match with ETag value in the request headers. However, I'm unable to do so when I provide If-Modified-Since in the request headers. I believe it is because my response does not contain a header called Last-Modified, which ConditionalGetMiddleware seems to be requiring, as follows: class ConditionalGetMiddleware(MiddlewareMixin): """ Handle conditional GET operations. If the response has an ETag or Last-Modified header and the request has If-None-Match or If-Modified-Since, replace the response with HttpNotModified. Add an ETag header if needed. """ def process_response(self, request, response): # It's too late to prevent an unsafe request with a 412 response, and # for a HEAD request, the response body is always empty so computing # an accurate ETag isn't possible. if request.method != "GET": return response if self.needs_etag(response) and not response.has_header("ETag"): set_response_etag(response) etag = response.get("ETag") last_modified = response.get("Last-Modified") last_modified = last_modified and parse_http_date_safe(last_modified) if etag or last_modified: return get_conditional_response( request, etag=etag, last_modified=last_modified, response=response, ) return response def needs_etag(self, response): """Return True if an ETag header should be added to response.""" ... Ideally, I would like Last-Modified to have a value similar to ConcernedModel.objects.latest("updated_at"). One way that … -
Django Custom User model AbstractBaseUser and Proxy models. Password is not hashed or set properly
When user is registered with a form or in admin the password is not hashed, as with the superuser. Any help appreciated. I cannot seem to figure this out. Oh, I am not able to login either. Exept from superuser. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'theapp', 'rest_framework', 'userapp', ] . . . AUTH_USER_MODEL = "userapp.UserAccount" model.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserAccountManager(BaseUserManager): def create_user(self, email, password=None): if not email or len(email) <= 0: raise ValueError("Email field is required !") if not password: raise ValueError("Password is must !") user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), password=password ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser): class Types(models.TextChoices): STUDENT = "STUDENT", "student" TEACHER = "TEACHER", "teacher" type = models.CharField( max_length=8, choices=Types.choices, default=Types.TEACHER) email = models.EmailField(max_length=200, unique=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) phone_no = models.CharField(max_length=10) # special permission which define that # the new user is teacher or student is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) USERNAME_FIELD = "email" # defining the manager for the UserAccount model objects = UserAccountManager() def … -
testing Profile creation after user registration with uninttest
i use signals for create profile after user register, Manually the test and def test__create_profile is correct, but def test_profile_created_automate is false. this is my test: class Testprofile(APITestCase): def setUp(self): self.client = APIClient() self.user = User.objects.create_user(email='hosein@gmail.com', username='hosein', password='admin') def test__create_profile(self): response = self.client.post(reverse('users-front:create_profile'), data={ "user": 1, 'age': 10, "first_name": "string", "last_name": "string", "phon_number": "9182133038", "birthday": "2023-11-21", "bio": "string", "address": "string", "gender": "M" }) self.assertEquals(response.status_code, 201) def test_profile_created_automate(self): user = User.objects.get(username='hosein') self.assertTrue(Profile.objects.filter(user=user).exists()) -
Error when try to add data to db in djnago app
i have djnago application (emergency notification system) and i see error when i try to add data to this is my views py from django.shortcuts import render, redirect from django.views.generic import TemplateView from django.contrib.messages.views import SuccessMessageMixin from django.views.generic.edit import CreateView from django.urls import reverse_lazy from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib import messages from .models import Contact #################################################### class Main(TemplateView): template_name = 'emnosys/main.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['css_file'] = 'styles.css' return context ################################################### def Registration(request): if request.method == "POST": username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] myuser = User.objects.create_user(username, email, password1) myuser.save() return redirect('signin') return render(request, "emnosys/registration.html") ############################################### def Signin(request): if request.method == 'POST': username = request.POST['username'] password1 = request.POST['pass1'] user = authenticate(username=username, password=password1) if user is not None: login(request, user) return render(request, "emnosys/main.html") else: return redirect('signin') return render(request, "emnosys/signin.html") ################################################ def Signout(request): logout(request) return redirect('home') ###################################################### class PersonalPage(TemplateView): template_name = 'emnosys/personalpage.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['css_file'] = 'styles.css' return context #################################################### def add_contact(request): if request.method == 'POST': username = request.POST.get('about--username') message = request.POST.get('about--message') email = request.POST.get('about--email') Contact.objects.create(username=username, message=message, email=email) return render(request, 'emnosys/addcontacts.html') this is my models py from django.db import … -
How to resolve error running pipdeptree with Python 3.11
I'm following the instructions here for upgrading Django: Django Upgrade Video And I get a big error when trying to run the first command for deriving dependencies: pipdeptree -f --warn silence | grep -E '^[a-zA-Z0-9\-]+' The following is the error stack trace Traceback (most recent call last): File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/bin/pipdeptree", line 8, in <module> sys.exit(main()) ^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/__main__.py", line 44, in main render(options, tree) File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_render/__init__.py", line 27, in render render_text( File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_render/text.py", line 34, in render_text _render_text_with_unicode(tree, nodes, max_depth, frozen) File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_render/text.py", line 107, in _render_text_with_unicode lines = chain.from_iterable([aux(p) for p in nodes]) ^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_render/text.py", line 107, in <listcomp> lines = chain.from_iterable([aux(p) for p in nodes]) ^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_render/text.py", line 59, in aux node_str = node.render(parent, frozen=frozen) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_models/package.py", line 53, in render return render(frozen=frozen) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_models/package.py", line 114, in render_as_root return self.as_frozen_repr(self._obj) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pipdeptree/_models/package.py", line 79, in as_frozen_repr fr = FrozenRequirement.from_dist(our_dist) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pip/_internal/operations/freeze.py", line 244, in from_dist req, editable, comments = get_requirement_info(dist) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pip/_internal/operations/freeze.py", line 174, in get_requirement_info if not dist_is_editable(dist): ^^^^^^^^^^^^^^^^^^^^^^ File "/Users/john.xxx/Documents/workspace/employee-maestro/venv_3_11/lib/python3.11/site-packages/pip/_internal/utils/misc.py", line 384, in dist_is_editable egg_link = os.path.join(path_item, dist.project_name + ".egg-link") ^^^^^^^^^^^^^^^^^ AttributeError: 'Distribution' object has no attribute 'project_name' I'm new to Django and Python. I do not know how … -
Adding filter to inline raw_id_field in django admin
I have a data model as below: class School(models.Model): name = models.CharField() class Candidate(models.Model): name = models.CharField() school = models.ForeignKey(School) class Skill(models.Model): name = models.CharField() school = models.ForeignKey(School) class CandidateSkill(models.Model): candidate = models.ForeignKey(Candidate) skill = models.ForeignKey(Skill, related_name='candidate_skills') And in the admin I have: class CandidateSkillInline(admin.TabularInline): model = CandidateSkill form = CandidateSkillInlineForm fields = ('skill', ) raw_id_fields = ('skill',) class CandidateAdmin(admin.ModelAdmin): model = Candidate fields = ('name', 'school') inlines = [CandidateSkillInline] What I am trying to achieve is when I click the skill raw_id_field from the CandidateAdmin I want to list only the skills that belong to the school of the candidate. I had tried this solution https://stackoverflow.com/a/66429352/16891729 but in case of inlines I am getting the instance as None. So I can't access the candidate's school from the instances. This solution is working if we are filtering based on static value. How can I achieve this? -
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!