Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Helm on Minikube showing an NGINX frontpage instead of a Django application
When I type minikube svc announcements-helm --url I get a URL that points me to a default NGINX page. I'm not sure why it is not showing me the actual Django application that is supposed to be there. I used kubectl exec to ls the pod, and it shows the application is inside the pod. I have the code for the Helm setup at this github repository: https://github.com/UCF/UCF-Announcements-Django/tree/helm/helm I'm fairly new to helm and kubernetes so any advice would be very appreciated -
Django, stripe and webhook : {"error": "Missing stripe signature"}
I need your help. I'm trying to set up a striped payment system in the django app. However, I can't seem to connect the webhook to my logic. In addition, the handle_checkout_session function which should send a message after the success of each payment does not send any message. def stripe_config(request): if request.method == 'GET': stripe_config = {'publicKey': settings.STRIPE_PUBLIC_KEY} return JsonResponse(stripe_config, safe=False) login_required(login_url="login") def stripe_payment(request): if request.method == 'GET': domain_url = getattr(settings, 'DOMAIN_URL') success_url = domain_url + reverse('stripe_success') + '?session_id={CHECKOUT_SESSION_ID}' cancel_url = domain_url + reverse('stripe_cancel') stripe.api_key = settings.STRIPE_SECRET_KEY order_id = request.GET.get('order_id') try: order = Order.objects.get(user=request.user, is_ordered=False, order_number=order_id) checkout_session = stripe.checkout.Session.create( client_reference_id=request.user.id if request.user.is_authenticated else None, success_url=success_url, cancel_url=cancel_url, payment_method_types=['card'], mode='payment', line_items=[ { 'price_data': { 'currency': 'eur', 'unit_amount': int(order.order_total * 100), 'product_data': { 'name': "Buy now", }, }, 'quantity': 1, } ] ) return JsonResponse({ 'sessionId': checkout_session['id'] }) except Order.DoesNotExist: return JsonResponse({ 'error': 'Order does not exist or has already been processed.' }, status=404) except stripe.error.StripeError as e: return JsonResponse({ 'error': str(e) }, status=500) return JsonResponse({'error': 'Invalid request method.'}, status=400) @csrf_exempt def stripe_webhook(request): stripe.api_key = settings.STRIPE_SECRET_KEY endpoint_secret = settings.STRIPE_WEBHOOK_SECRET payload = request.body sig_header = request.META.get('HTTP_STRIPE_SIGNATURE') print(sig_header) if sig_header is None: return JsonResponse({'error': 'Missing stripe signature'}, status=400) try: event = stripe.Webhook.construct_event( payload, sig_header, … -
cookies are not being set on browser Django
I'm making a webapp in Django and Electron using websockets and I wanted to insert one of the socket responses into the user's cookies, but unfortunately I don't know why but they are not being inserted, here is an example of what I am doing: in the response.cookies printout something like this appears: Cookies defined in the response: Set-Cookie: image_data="pls work"; expires=Tue, 21 May 2024 16:22:33 GMT; Max-Age=3600; Path=/ here is my code if you have any ideas or need any part of the code I will provide it, thank you. code: @csrf_exempt def process_screenshot(request): call = identificador_unico(request) print("call:", call) if request.method == 'POST': image_content = request.POST.get('image_content') if image_content: print("String em base64 recebida com sucesso.") try: # Decodifica a string em base64 para obter os dados binários da imagem image_data = base64.b64decode(image_content) print("base64", image_data[:20]) # Salva os dados binários da imagem em um arquivo file_path = 'frames/screenshot.jpg' with open(file_path, 'wb') as f: f.write(image_data) image_content = "pls work" # Salva image_data nos cookies response = JsonResponse({'message': 'Imagem processada com sucesso'}) response.set_cookie('image_data', image_content, max_age=3600,secure=False,samesite=None) # Expira em 1 hora print("Cookies definidos na resposta:", response.cookies) return response except Exception as e: # Se ocorrer algum erro ao decodificar a string em base64 ou … -
Value Error while storing data into models in Django
This is my "models.py": class PostData(models.Model): #image = models.ImageField(upload_to="") title_name = models.CharField(max_length=255) description = models.CharField(max_length=10000) author = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) This is my "views.py": def createPost(request): if request.method == "POST": form = PostForm(request.POST) print(form.is_valid()) if form.is_valid(): # To extarct data from web page title = form.cleaned_data['title_name'] description = form.cleaned_data['description'] # To get username which is stored in session author = request.session.get("username") print(author) print(title) # To store Data PostData.objects.create(title_name=title, description=description, author=author) And I am getting the following error: ValueError at /create/ Cannot assign "'dhruv123'": "PostData.author" must be a "User" instance. So how to solve this error? -
You are not authorized to view this object, Django + Cloudflare R2
im trying to use CloudFlare R2 to server static files from my django project, but im having "This object could not be viewed". I added custom domains, and allowed public view. I cant understand what is wrong. Any help? Thank you! -
assertRedirects in django view test not working
I have created a test case to test my custom login_required decorator. This is my decorator: def login_required(view_func): @wraps(view_func) def wrapped_view(request, *args, **kwargs): # Check if the user is logged in if request.user.is_authenticated: return view_func(request, *args, **kwargs) else: return redirect('/auth/login') return wrapped_view This is my test case: class RegisterViewTests(TestCase): def setUp(self): self.client = Client() def test_register_view_get_not_authenticated(self): response = self.client.get(reverse('register')) print(response.url) self.assertRedirects(response, '/auth/login') Here when I print response.url I get '/auth/login' but when I use the same to check the redirect I get this error: FAIL: test_register_view_get_not_authenticated (authentication.tests.test_views.RegisterViewTests.test_register_view_get_not_authenticated) Traceback (most recent call last): File "F:\Ayush\CODE\DJANGO\final\project\CBBB Group 1\final_repo\authentication\tests\test_views.py", line 61, in test_register_view_get_not_authenticated self.assertRedirects(response, reverse('login_view')) File "F:\Ayush\CODE\DJANGO\final\project\CBBB Group 1\final_repo\venv\Lib\site-packages\django\test\testcases.py", line 432, in assertRedirects self.assertEqual( AssertionError: 301 != 200 : Couldn't retrieve redirection page '/auth/login': response code was 301 (expected 200) Ran 1 test in 0.033s FAILED (failures=1) I tried using reverse('login') inside the assertRedirects but it still gave the same error. -
Django Internationalization - Translation from Javascript handled pop up not picked up
I am using Django Internationalization in my django project. On one of my page I have some text, which gets translated just fine, and a pop up window which stubornly does not seem to pick up the translation proposed in the po file. However the translation is present in the po. Because this pop up window has created problems in the past, I am assuming this is because of the javascript that manages the window to open and close. I started following this post How to solve the translation/localisation of JavaScript external files since Django does not allow built-it tags in other files?, but I think I am missing something: how do I connect my locale file to the javascript catalog? project: mysite app: main url (project level) urlpatterns += i18n_patterns( path('', include("main.urls")), #add for i18n translation for javascript content path("jsi18n/", JavaScriptCatalog.as_view(), name="javascript-catalog"), ) base.html <script src="{% url 'javascript-catalog' %}"></script> template (app level) with script <div class="form-popup" id="myForm{{ model.id }}"> <form action="{% url 'url' %}" class="show-venue-popup-container" method="post"> {% csrf_token %} <h5 class="show-venue-popup-title">{% translate 'text to be translated_0!' %}</h5> <p class="show-venue-popup-text">{% translate 'text to be translated_1' %}</p> <button type="submit" class="btn">{% translate 'text to be translated_2' %}</button> <button type="button" class="btn cancel" onclick="closeForm('{{ … -
Django hosting as begginer
Free Django hosting platforms do not support the latest Python versions. My Django app is made with Python 3.12.2. What should I do? Should I downgrade my project version to match the hosting platforms? Will this ruin my project? I am a beginner, and this is my first time doing all of this. I tried Heroku which is now paid, pythonanywhere is upto python 3.10 -
Django stripe and stripe webhook error : {"error": "Missing stripe signature"}
please, I need your help. I'm trying to set up a striped payment system in the django app. However, I can't seem to connect the webhook to my logic. In addition, the handle_checkout_session function which should send a message after the success of each payment does not send any message. However, when I make a payment it works fine. But, Webhook and handle_checkout_session doesn't work. Your help will be welcome... Here is my code. def stripe_config(request): if request.method == 'GET': stripe_config = {'publicKey': settings.STRIPE_PUBLIC_KEY} return JsonResponse(stripe_config, safe=False) login_required(login_url="login") def stripe_payment(request): if request.method == 'GET': domain_url = getattr(settings, 'DOMAIN_URL') success_url = domain_url + reverse('stripe_success') + '?session_id={CHECKOUT_SESSION_ID}' cancel_url = domain_url + reverse('stripe_cancel') stripe.api_key = settings.STRIPE_SECRET_KEY order_id = request.GET.get('order_id') try: order = Order.objects.get(user=request.user, is_ordered=False, order_number=order_id) checkout_session = stripe.checkout.Session.create( client_reference_id=request.user.id if request.user.is_authenticated else None, success_url=success_url, cancel_url=cancel_url, payment_method_types=['card'], mode='payment', line_items=[ { 'price_data': { 'currency': 'eur', 'unit_amount': int(order.order_total * 100), 'product_data': { 'name': "Buy now", }, }, 'quantity': 1, } ] ) return JsonResponse({ 'sessionId': checkout_session['id'] }) except Order.DoesNotExist: return JsonResponse({ 'error': 'Order does not exist or has already been processed.' }, status=404) except stripe.error.StripeError as e: return JsonResponse({ 'error': str(e) }, status=500) return JsonResponse({'error': 'Invalid request method.'}, status=400) @csrf_exempt def stripe_webhook(request): stripe.api_key = settings.STRIPE_SECRET_KEY endpoint_secret … -
Reverse for 'service' not found . template base.html, error at line 0 why i am getting this error?
i have created services.html in templates and also defined a view for it and url in urls.py but then i decided to simply remove it because i don't need it i deleted my template services.html and also view and url from urls.py but i am getting this error even i don't have any veiw name services or url in my urls.py but still i am getting this error during template rendering error at line 0. This is views.py: from django.shortcuts import render def home(request): return render(request,'webapp/home.html') urls.py from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home'), ] urls.py Project from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('webapp.urls')), ] project structure: -
I have completed the registration process in Django user login, but I want the login process to check and match the tokens. How can I do this
I created a user login with Django. I used tokens during the registration process, and I want the user to be redirected to the homepage if the tokens match when they enter their password during login. I want to implement user login with tokens in my Django project -
How to edit field how an embedded model in django
I have following models : ModelA --> with fields flda1, flda2, fld3 and id ModelB --> with fields fldb1, fldb2, id and a_obj = foreign-key-to-ModelA Now I have to write view to update flda1 and flda2 of ModelA and fldb1 of ModelB resources having foreign-key-to-same(ModelA) [some (not all) -- i.e., not all b_objs need to be modified ] The update data must be sent as follows : data = { 'flda1' : 'PRADEEP 2 title CHANGED', 'flda2' : 'medium CHANGED again...', "b_objs" : [ {'fldb1':'TB', 'modela':99, 'id':184}, {'fldb1':'STF', 'modela':99, 'id':185} ] } And the query parameter contains id for ModelA The problem is that the view and the serializer are working properly for flda1 and flda2. But when I add b_objs, I get errors. Here is my view : class ViewA(RetrieveUpdateDestroyAPIView): queryset = ModelA.objects.all().prefetch_related('b_objs') serializer_class = ModelASerializer def update(self, request, *args, **kwargs): modela_id = = request.query_params['id'] modela_ins = queryset.filter(pk=modela_id).first() serializer = self.get_serializer(project, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() And serializers are : class ModelBSerializer(serializers.ModelSerializer): class Meta : model = ModelB fields = '__all__' class ModelASerializer(serializers.ModelSerializer): obj_bs = ModelBSerializer(many=True) def validate(self, data) : # validation code return data def update(self, instance, validated_data): print(validated_data) for field, value in validated_data.items(): setattr(instance, field, value) instance.save() # … -
AWS Beanstalk - FileNotFoundError: [Errno 2] No such file or directory: '/var/app/staging/'
I am using Elastic Beanstalk without container, just the EC2 instance. Sometimes it fails without any reason when it create a new instance. I found some weird logs May 20 20:32:48 ip-172-31-14-242 audit[10978]: AVC avc: denied { open } for pid=10978 comm="nginx" path="/var/log/nginx/error.log" dev="nvme0n1p1" ino=3682049 scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:cloud_log_t:s0 tclass=file permissive=1 [2024-05-20T20:21:47.035Z] Sending signal 0 to CFN wait condition https://cloudformation-waitcondition-us-east-1.s3.amazonaws.com/arn%3Aaws%3Acloudformation%3Aus-east-1%3A576017513047%3Astack/awseb-e-xcvkczyzt5-stack/3804c910-892f-11ee-abd9-0a6f02a2186d/AWSEBInstanceLaunchWaitHandle?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20231122T120405Z&X-Amz-SignedHeaders=host&X-Amz-Expires=86399&X-Amz-Credential=AKIA6L7Q4OWT3JRXU3BZ%2F20231122%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=abf31ed864bec2be68aa61889b6b2a836c610de7ba3bed93dce80c1ee7589faa Error signaling CloudFormation: [Errno 403] HTTP Error 403 : <?xml version="1.0" encoding="UTF-8"?> <Error><Code>AccessDenied</Code><Message>Request has expired</Message><X-Amz-Expires>86399</X-Amz-Expires><Expires>2023-11-23T12:04:04Z</Expires><ServerTime>2024-05-20T20:21:47Z</ServerTime><RequestId>9SRZ3MVWKVAR7FJ2</RequestId><HostId>B16Ow5bF0aibCFU52u+lnnMOBI6Rijz9KV/Y+UGKWkgHz4E+QtXAbYDp48ZnLK5wAsOHgblLZOk=</HostId></Error> 2024-05-20 19:44:47,211 [ERROR] -----------------------BUILD FAILED!------------------------ 2024-05-20 19:44:47,212 [ERROR] Unhandled exception during build: [Errno 2] No such file or directory: '/var/app/staging/' Traceback (most recent call last): File "/opt/aws/bin/cfn-init", line 181, in <module> worklog.build(metadata, configSets, strict_mode) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 137, in build Contractor(metadata, strict_mode).build(configSets, self) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 567, in build self.run_config(config, worklog) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 579, in run_config CloudFormationCarpenter(config, self._auth_config, self.strict_mode).build(worklog) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 277, in build changes['commands'] = CommandTool().apply( File "/usr/lib/python3.9/site-packages/cfnbootstrap/command_tool.py", line 116, in apply commandResult = LoggingProcessHelper( File "/usr/lib/python3.9/site-packages/cfnbootstrap/util.py", line 619, in call results = self.process_helper.call() File "/usr/lib/python3.9/site-packages/cfnbootstrap/util.py", line 591, in call process = subprocess.Popen( File "/usr/lib64/python3.9/subprocess.py", line 951, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/usr/lib64/python3.9/subprocess.py", line 1821, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: '/var/app/staging/' I know … -
Use a DB backend function on the result of an aggreate in Django
Is it possible to have a DB function executed on the result of an aggregate? In my case, I have this aggregate: geom = SomeModel.objects.filter(otherModel=xxx).aggregate(geom=Union("geom")) Let's say I would like to run another DB function on the output of the aggregate (like Reverse for instance. How can I achieve this? -
Cookie does not get set
I have a Django REST API that sends with session authentication. And the problem is the csrftoken cookie that I get in request does not get set. Here's a part of my SETTINGS.py file # CORS and CSRF CORS_ALLOWED_ORIGINS = [ 'https://123.client' ] CORS_ALLOW_CREDENTIALS = True CORS_EXPOSE_HEADERS = [ 'Set-Cookie' ] CSRF_TRUSTED_ORIGINS = [ 'https://123.client' ] CSRF_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = False SESSION_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SECURE = True Here are the response headers: HTTP/1.1 202 Accepted Date: Tue, 21 May 2024 12:31:31 GMT Content-Length: 0 Connection: keep-alive Vary: Accept, Cookie, origin Allow: POST, OPTIONS X-Frame-Options: DENY X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin access-control-allow-origin: https://123.client access-control-allow-credentials: true access-control-expose-headers: Set-Cookie Set-Cookie: csrftoken=...; expires=Tue, 20 May 2025 12:31:31 GMT; Max-Age=31449600; Path=/; SameSite=None; Secure sessionid=...; expires=Tue, 04 Jun 2024 12:31:31 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=None; Secure Server: ... And when I try to read the csrftoken cookie to set the X-CSRFToken header, I can't get it and it's not showing neither in browser nor when I try to access it in https://123.client through document.cookie. On what side is the problem here? Am I just not reading the cookie correctly or is there something needs to be done server-side? -
Can't get two elements to update while using Django and HTMX
I'm trying to create a car pool where I use HTMX in my Django project to make it work. The CarPool model consist of two FK. One FK is "City", and the other is "Car". I have it somewhat working. So within my two tables (one table with all the cars that have no city attached, and the other table displaying all the cars attached to the city that has been clicked), I'm able to use hx-post to add the car, and same to remove the car with the clicked city. But I don't get the lists to update after they are clicked. I have tried different ways of using hx-oob-swap but since I'm fairly new with both Django and HTMX I'm not sure where to exactly use it. See attached pictures. So picture "notclicked", the left table shows all cars with no city, and the right table displays cars with "Chicago" as a FK. notclicked Picture "clicked" I have now clicked on the car MMW 331 from the left table, and it adds it to the right table which is good, but then when I click on it, I want it also to be removed from the left table … -
Stripe promocode: how to verify that user have redeemed the promocode before or not
I have a Django project configured with Stripe for payments. I have created promocodes for discounts, which can only be redeemed once per customer. The problem is that I want to validate whether a given customer has already redeemed a specific promocode. If they haven't redeemed it, I want to proceed to the next step; otherwise, I want to stop the customer at that point. I have retrieve the promocode but it returns the following values: { "active": true, "code": "test10", "coupon": { "amount_off": null, "created": 1716289929, "currency": "usd", "duration": "once", "duration_in_months": null, "id": "test10", "livemode": false, "max_redemptions": null, "metadata": {}, "name": null, "object": "coupon", "percent_off": 10.0, "redeem_by": null, "times_redeemed": 1, "valid": true }, "created": 1716289930, "customer": null, "expires_at": 1716595200, "id": "promo_1PIqc2B67hjAZnF4umv6pZCP", "livemode": false, "max_redemptions": null, "metadata": {}, "object": "promotion_code", "restrictions": { "first_time_transaction": true, "minimum_amount": null, "minimum_amount_currency": null }, "times_redeemed": 1 } I am not able to find an API that validates whether a customer has already redeemed a given promocode. I'm expecting a method or API endpoint in Stripe that allows me to check if a specific customer (customer ID) has redeemed a specific promocode. I have created The promocode which is only be redeemed once per customer. -
"This field may not be blank." Django DRF
I am new to DRF, I am working on the the registraion API My MOdel from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, email, user_type, password=None, **extra_fields): email = self.normalize_email(email) user = self.model(email=email, user_type=user_type, **extra_fields) user.set_password(password) user.save(using=self._db) return user class CustomUser(AbstractBaseUser): USER_TYPE_CHOICES = ( ('seller', 'Seller'), ('user', 'User'), ) username = models.CharField(unique=True, max_length=20, null=True, blank=True,) email = models.EmailField(unique=True, blank=True,) first_name = models.CharField(max_length=256 , blank=True,) last_name = models.CharField(max_length=256, blank=True,) user_type = models.CharField(max_length=10, choices=USER_TYPE_CHOICES , blank=True,) email_otp = models.CharField(max_length=10, blank=True,) phone_otp = models.CharField(max_length=10, blank=True,) email_verified = models.BooleanField(default=False, blank=True,) create_at = models.DateTimeField(auto_now_add=True, blank=True,) update_at = models.DateTimeField(auto_now=True, blank=True,) is_active = models.BooleanField(default=True, blank=True,) is_staff = models.BooleanField(default=False, blank=True,) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_type'] class SellerProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) address_1 = models.CharField(max_length=255, blank=True,) address_2 = models.CharField(max_length=255, default="Null", blank=True,) address_3 = models.CharField(max_length=255, default="Null", blank=True,) state = models.CharField(max_length=100, blank=True,) phone_number = models.CharField(max_length=15, blank=True,) zip_code = models.CharField(max_length=10, blank=True,) class UserProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE , blank=True,) profile_pic = models.ImageField(upload_to='profile_pics', blank=True, null=True) bio = models.TextField(blank=True,) dob = models.DateField(blank=True,) phone_number = models.CharField(max_length=15, blank=True,) My serializer class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('profile_pic', 'bio', 'dob', 'phone_number') class SellerProfileSerializer(serializers.ModelSerializer): class Meta: model = SellerProfile fields = ('address_1', 'address_2', 'address_3', 'state', 'phone_number', … -
upgrade from 4.2.6 to 5.0.6 destroyed my forms
I am using an ImageForm to upload images to my database and I store them in base64 (user's icons, only some pixels). But the update destroyed the functionality: class CustomImageFile(AdminFileWidget): def render(self, name, value, attrs=None, renderer=None): output = [super().render(name, value)] try: output.append(self.form_instance.instance.show_picture()) except: pass return "".join([x for x in output]) class PersonAdminForm(forms.ModelForm): image_file = forms.ImageField(widget=CustomImageFile, required=False, label="picture") def __init__(self, *args, **kwargs): """ to add self.form_instance to widget """ super().__init__(*args, **kwargs) self.fields["image_file"].widget.form_instance = self class Meta: model = Person fields = ["name", ..., "image_file"] @admin.register(Person) class PersonAdmin(admin.ModelAdmin): list_display = ["get_name", "get_picture"] @admin.display(description="...") def get_picture(self, obj): try: return obj.show_picture except: return "... " class Person(models.Model): name = models.CharField("name", max_length=128, blank=True, null=True) picture = models.TextField("asb64", blank=True) @property def show_picture(self): try: return format_html(f"""<img src="{self.picture}">""") except: return "" I tested this with Django 4.2.6 & 4.2.13 which yields: After an upgrade to 5.0.6: Where there changes to ImageField? I have not yet found something in the patchnotes I could use, but would be glad for a solution. -
how to get distinct record based on specific fields in django orm?
def get_queryset(self): # current_date = datetime(2024, 9, 2, 12, 56, 54, 324893).today() current_date = datetime.today() # get the booking data from the current date --------- requested_datetime is when the patient has scheduled the booking for booking_data = PatientBooking.objects.annotate( admission_datetime=F('requested_admission_datetime'), delivery_datetime=F('estimated_due_date'), fully_dilation_datetime=ExpressionWrapper( F('estimated_due_date') - timedelta(days=(1)), output_field=DateTimeField() ), source=Value('booking', output_field=CharField()) ).filter(status="ACCEPTED", admission_datetime__date=current_date ) # get the patient data from the current date ---- based on when the patient record is created_at patient_data = PatientDetails.objects.annotate( admission_datetime=F('created_at'), delivery_datetime=F('estimated_due_date'), fully_dilation_datetime=F('patient_fully_dilated'), source=Value('patient', output_field=CharField()) ).filter(status="ACTIVE", admission_datetime__date=current_date ) # combine the record in one queryset using union on the required fields only combined_queryset = booking_data.values('first_name', 'last_name', 'delivery_type', 'date_of_birth', 'admission_datetime', 'delivery_datetime', 'fully_dilation_datetime', 'source' ).union( patient_data.values('first_name', 'last_name', 'delivery_type', 'date_of_birth', 'admission_datetime', 'delivery_datetime', 'fully_dilation_datetime', 'source' ) ).order_by('first_name', 'last_name', 'date_of_birth') # if records in both the model matches---- then consider it as same patient and consider the record where the source=patient combined_queryset = combined_queryset.distinct( 'first_name', 'last_name', 'date_of_birth' ) return combined_queryset This is my queryset. I have two models PatientDetails and PatientBooking both models have different numbers of fields and names I want to get a single queryset with specific fields from both tables. So I first annotate the field name and then perform union to it. To get a single queryset with field … -
How to start Celery Beat and Worker in production environment(cpanel)
please I developed a django app that automatically generates invoice and sends an email to client at certain hours. This app works perfectly in the development environment but not in production. I need help on how to work with redis and celery beat in production(cpanel) When I tried starting celery beat on cpanel, i was getting an error regarding Redis -
retrieve query params in django
I created a redirect endpoint on my django app. I normally am able to get query params from the url path but when this redirect happens, it appends the value # to the url. this stops me from being able to get the query params. how do i retrieve access_token as a query params from this url? /redirect/#access_token=ya29.a0AXooCgvXSv2-9x-4i6V I tried using request.GET.get('access_token') but it did not work. I also printed request.META but access_token is not in it -
Use IntegerChoices instead of Model for rest framework
I have field like this, models.py from django.db import models as m class Faculty(m.IntegerChoices): Arts = 1, 'Arts', Scienece = 2, 'Sceience' Other = 3 ,'Other' and it is used as reference in other models. Howeber, now I want to get the list by API rest framework. For example if it is not IntegerChoices but Model I can use the rest framework with view and serializer class MyModelViewSet(viewsets.ModelViewSet): queryset = sm.Faculty.objects.all() serializer_class = s.FormSelectorSerializer class MyModleSerializer(ModelSerializer): detail = serializers.JSONField() class Meta: model = sm.MyModel fields = ('id') I can use the rest framework like this , However for IntegerChoices, How can I do the equivalent to this thing? Or is it possible? -
Django extra actions need to add additional parameter but not working
I have a extra action in Django. I need to provide additional query param to it, shown below: class MyViewSet: .... ... @action(detail=True, method=["get"], url_path=r"abc/(?P<name>[A-Za-z\.]+)") def abc_op(self, request, pk, name): .... The above is not working when I call the API like: http://localhost:8000/employee/1/abc/xy.z, but if I append / at the end I get the result: http://localhost:8000/employee/1/abc/xy.z/ with request http://localhost:8000/employee/1/abc/xy.z I get: { "detail": "Not found." } But when I make request http://localhost:8000/employee/1/abc/xy.z/ (appending / at the end) I get: { "result": True, "data": [] } Please let me help understand what is wrong here. This should work without appending any / at the end. -
DatabaseError at /admin/shop/item/add/
here pic of error another pic debug log DatabaseError at /admin/shop/item/add/ No exception message supplied Request Method:POSTRequest URL:http://127.0.0.1:8000/admin/shop/item/add/Django Version:4.1.13Exception Type:DatabaseErrorException Location:C:\Users\MSI\Desktop\A Project_Django_thanhduc\my_venv\Lib\site-packages\djongo\cursor.py, line 81, in fetchoneRaised during:django.contrib.admin.options.add_viewPython Executable:C:\Users\MSI\Desktop\A Project_Django_thanhduc\my_venv\Scripts\python.exePython Version:3.11.9Python Path:['C:\\Users\\MSI\\Desktop\\A Project_Django_thanhduc\\my_app', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\\python311.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\\Lib', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0', 'C:\\Users\\MSI\\Desktop\\A Project_Django_thanhduc\\my_venv', 'C:\\Users\\MSI\\Desktop\\A ' 'Project_Django_thanhduc\\my_venv\\Lib\\site-packages']Server time:Tue, 21 May 2024 08:33:44 +0000 This is my setting.py database DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'onlineshop', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'localhost', 'port': 27017, 'authSource': 'admin', # Đảm bảo rằng authSource là đúng }, 'LOGGING': { 'version': 1, 'loggers': { 'djongo': { 'level': 'DEBUG', 'propagate': False, } }, }, } } Model.py : from django.db import models from django.contrib.auth.models import User class Topic(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Item(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=100) price = models.DecimalField(max_digits=20, decimal_places=2) image = models.ImageField(upload_to='items/', null=True, blank=True) description = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return f"{self.name} - {self.host.username if self.host else 'No Host'}" I'm start a project with django and mongodb(with djongo eninge). When I create user in my template(html) i can create item, update, delete, even with superuser. But when I go to adminstrations(with …