Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
checkbox in list view in django template , retrieve all checked box objects in each pagination to view of Django (server)
I have checkbox in list view and contains pagination in html template. I want to retrieve the all checked box objects in each pagination to server (view part of Django) . Example in page 1 , if i checked 4 objects , page2 checked 3 objects , page 3 checked 4 objects then finally when i clicked then i will get all 11 checked objects into the server. I tried , But i am getting only selected objects in current page . When i navigate to next page then first selected object deleted . I don't know how to retrieve all objects together in each page . -
Django django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I have an app for surveys. I am trying to import my model in views.py and its giving an error. My code is: settings.py: INSTALLED_APPS = [ 'survey.apps.SurveyConfig', 'survey.urls', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('survey/', include('survey.urls')), ] survey/urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.list_surveys, name='list-surveys'), path('create/', views.create_survey, name='list-surveys'), ] survey/views.py: from django.shortcuts import render from .models import MultipleChoiceQuestion surveys = [ { "id": "S001", "questions": [ ["How much do you like Userfacet?", 1], ["How much do you like frontend?", 0], ["How much do you like backend?", 2], ["How much do you like fullstack?", 0], ["How much do you like Userfacet?", 3], ["How much do you like frontend?", 0], ["How much do you like backend?", 4], ["How much do you like fullstack?", 0], ["How much do you like Userfacet?", 5], ["How much do you like frontend?", 0], ["How much do you like backend?", 6], ["How much do you like fullstack?", 0], ["How much do you like Userfacet?", 7], ["How much do you like frontend?", 0], ["How much do you like backend?", 8], ["How much do you like … -
How to solve CreateAPI 400 error in this DjangoRestFramework in Serializer Create Method?
I have a model, Doctor, that has a Foreign key relation to the user model. I'm handling the creation of Doctor instances through the serializer of the Doctor Model. The flow I'm going for is simply to check if a user with the given username exists. If it exists, then create a new Doctor Instance with the existing user, if it doesn't, then first create a new user, and then create a Doctor Instance with that new user. Here is my Doctor Serializer :-> class StaffSerializer(serializers.ModelSerializer): """ Serializer for viewing entries Doctor model """ departments_display = DepartmentSerializer( many=True, source="departments", read_only=True ) appointment_types_display = AppointmentTypeSerializer( many=True, source="appointment_types", read_only=True ) user = UserSerializer() permissions = PermissionSerializer(many=True) doc_image = serializers.SerializerMethodField() class Meta: model = Doctor exclude = ("hospitals",) extra_kwargs = { "departments": {"write_only": True}, "appointment_types": {"required": False}, } def get_doc_image(self,obj): return obj.doctor_image def create(self, validated_data): """ Create and return a new `Doctor` instance, given the validated data. """ # try: with transaction.atomic(): user_data = validated_data.pop("user") try: user = User.objects.get(username = user_data["username"]) validated_data["user"] = user except ObjectDoesNotExist: serializer = UserSerializer(data = user_data) if serializer.is_valid(): serializer.save() validated_data["user"] = serializer.instance permmissions = validated_data.pop("permissions") permissions_to_insert = [] for permission_entry in permmissions: uiserializer = UIElementSerializer(data = permission_entry["ui_element"]) uiserializer.is_valid() … -
is there an option to display a selenium session in website
Is it possible to display a Python selenium session (which run a flow in some website) on my website so that the user can see the session that is running? I'm using the Django library. -
Check constraint referencing fields of database object
Let's say I have a Django object like this: class X(models.Model): start_main = models.DateField("start X") And another like this: class Y(models.Model): x = models.ForeignKey(X, on_delete = models.CASCADE) start_sub = models.DateField("start Y") I want to add a CheckConstraint to Y that always ensures that Y.start_sub >= Y.x.start_main. Is this possible? I've looked into django.core.validators.MinValueValidator for example but that only takes concrete values as parameter. I've also looked into the check = models.Q(...) syntax but am unable to get syntactically correct constraint. -
conditions on django generic detailview
I'm trying to show a post detail view only when post.status=='pub'. I did it in list view with overriding get_queryset method but how can i do the same with detail view? I want the detail view to return 404 when post.status=='drf' models.py class Post(models.Model): STATUS_CHOICES = ( ('pub', 'عمومی'), ('drf', 'پیش نویس') ) title = models.CharField(max_length=60, null=False, blank=False, verbose_name='عنوان') description = models.TextField(max_length=200, verbose_name='توضیحات') body = RichTextField(verbose_name='بدنه') author = models.ForeignKey(get_user_model(), models.CASCADE, verbose_name='نویسنده') datetime_created = models.DateTimeField(auto_now_add=True, verbose_name='زمان ایجاد') datetime_modified = models.DateTimeField(auto_now=True, verbose_name='آخرین ویرایش') status = models.CharField(choices=STATUS_CHOICES, max_length=3, verbose_name='حالت انتشار') class Meta: verbose_name = 'پست' PostListView and PostDetailView class PostListView(generic.ListView): model = models.Post context_object_name = 'posts' template_name = 'pages/post_list.html' def get_queryset(self): queryset = super(PostListView, self).get_queryset() return queryset.filter(status='pub') class PostDetailView(generic.DetailView): model = models.Post context_object_name = 'post' template_name = 'pages/post_detail.html' -
django URL in a TextField with HTML
In my Django e-commerce project, I have an obvious Product model with an expected description field: description = models.TextField(...) I have the following url configured: path("product/slug:slug", views.product_detail, name="product_detail"), which, obviously, serves URLs like this: http://localhost:8000/product/foo and when a product foo is a part of a set with product bar, I want to add respective links to the description field on such products, like "you might want to buy bar together with this". However, adding a link to bar to the description of foo proved tricky. The whole description field (imported from a legacy ecomm app) can contain arbitrary HTML, and since it's not a user input, I render it like this in the template: {% autoescape off %} {{ product.description }} {% endautoescape %} When I add this to the (TextField) description: > This item together with <a href="product/bar">Bar</a> (sold separately) , the URL produced in the template is wrong: http://localhost:8000/product/product/bar/ , but if I don't use this '/product' in the description's url: > This item together with <a href="/bar">Bar</a> (sold separately) make > a matching set. , the URL is also wrong: http://localhost:8000/bar/ I'll admit, I don't understand how Django constructed the first or second URL. So it's ironic … -
How to aggregate an array of JSON Objects in Django with Postgres?
In Django 4.0+, I have an array of JSON objects that look like this: [{'type': 'ORG', 'data': "USA", "mentions": 8}, {'type': 'ORG', 'data': "CA", "mentions": 15}, {'type': 'PERSON', 'data': "Mahmoud", "mentions": 12}] So, in each row, I will have similar data like that in an object field called entities. What I am trying to achieve is to aggregate based on type with data and the total count of mentions of the same type and data and type in ALL rows. In my queryset, I have tried the following code to get the total mentions aggergate (unsuccessfully): def get_named_entities(self): named_entities = self.exclude(entities__exact={}).exclude(entities__isnull=True).values('entities__type', 'entities__data', 'entities').annotate( mentions=RawSQL("CAST(JSONB_AGG(entities->>'mentions') AS INTEGER)", ()) ).order_by('-mentions') Unfortunately, this doesn't work at all. -
Django Celery shared_task can does not have password suplied
When running a task that trys to read or save to django model it is unable to connect due to not having the password django.db.utils.OperationalError: connection to server at "db" (172.21.0.2), port 5432 failed: fe_sendauth: no password supplied I followed the set up from the celery website: https://docs.celeryq.dev/en/latest/django/first-steps-with-django.html#using-celery-with-django Was there anything I missed or need to change that is undocumented? I am using config for the backend 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('POSTGRES_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': 'db', 'PORT': 5432, } } CELERY_BROKER_URL = 'amqp://guest:guest@rabbitmq//' CELERY_RESULT_BACKEND = 'rpc://' SESSION_ENGINE = 'django.contrib.sessions.backends.cache' celery.py from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'irsystem.settings') app = Celery('irsystem') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks() @app.task(bind=True, ignore_result=True) def debug_task(self): print(f'Request: {self.request!r}') -
Heroku deploy errors python setup.py egg_info did not run successfully
I have a few problems and errors deploying heroku website. I have used django to create the website and want to deploy the website that I have gotten so far. I have all of the required packages installed in my local and in my virtual environment as well. However, When I try deploying the website, I get the following errors: × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [83 lines of output] /app/.heroku/python/lib/python3.11/site-packages/setuptools/__init__.py:84: _DeprecatedInstaller: setuptools.installer and fetch_build_eggs are deprecated. !! ******************************************************************************** Requirements should be satisfied by a PEP 517 installer. If you are using pip, you can try `pip install --use-pep517`. !! dist.fetch_build_eggs(dist.setup_requires) error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [17 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 14, in <module> File "/tmp/pip-wheel-2xd7j5kf/distribute_1efc1e9757504aed986ff8beb549bcab/setuptools/__init__.py", line 2, in <module> from setuptools.extension import Extension, Library File "/tmp/pip-wheel-2xd7j5kf/distribute_1efc1e9757504aed986ff8beb549bcab/setuptools/extension.py", line 5, in <module> from setuptools.dist import _get_unpatched File "/tmp/pip-wheel-2xd7j5kf/distribute_1efc1e9757504aed986ff8beb549bcab/setuptools/dist.py", line 7, in <module> from setuptools.command.install import install File "/tmp/pip-wheel-2xd7j5kf/distribute_1efc1e9757504aed986ff8beb549bcab/setuptools/command/__init__.py", line 8, in <module> from setuptools.command import install_scripts File "/tmp/pip-wheel-2xd7j5kf/distribute_1efc1e9757504aed986ff8beb549bcab/setuptools/command/install_scripts.py", line 3, in <module> from pkg_resources import Distribution, PathMetadata, ensure_directory File "/tmp/pip-wheel-2xd7j5kf/distribute_1efc1e9757504aed986ff8beb549bcab/pkg_resources.py", line … -
How to set a custom URL for Password Reset email that is sent using Django Dj-Rest-Auth, Django Allauth
so I have dj-rest-auth end points working but I am trying to customize the URL that is generated in the email to point to my front end. How would I do this? right now it sends the email with a url from the django server. http://server-ip:8000/api/password/reset/confirm/{the id}/{token} however id like to make it so http://myflutterapp.com/passwordreset/{id}/{token} thanks, I tried following this tutorial https://medium.com/@etentuk/django-rest-framework-how-to-edit-reset-password-link-in-dj-rest-auth-with-dj-allauth-installed-c54bae36504e but it didn't work. -
Can a Django query filter with a relationship reference a parent's field value?
I have a Training and TrainingAssignment table in my django app. Users sign into the app and complete a Training which creates a TrainingAssignment record. The Training table has a field, days_valid which is used to determine whether or not a user has to re-take a training. I want an admin to be able to change days_valid on the fly to "invalidate" previously completed trainings. (e.g. changing a training thats good for a year to only good for one month.). I don't want the admin's changing of days_valid to go out and change the expiration date of thr TrainingAssignment record...I want those records to remain untouched for audit purposes. Instead, my code creates a new assignment if the employee is due. models.py class Training(models.Model): title = models.CharField(max_length=200) days_valid = models.IntegerField() class TrainingAssignment(models.Model): training = models.ForeignKey( Training, on_delete=models.CASCADE, related_name='training_assignments', blank=True, null=True ) date_started = models.DateTimeField(null=True,blank=True) date_completed = models.DateTimeField(null=True, blank=True) date_expires = models.DateTimeField(null=True, blank=True) In a query, I need to be able to get all Trainings where TrainingAssignment's date_completed + the Training's days_valid <= today. (ie. user completes a TrainingAssignment on 6/1/23 and it's Training record is valid for 45 days, so when they log in on 6/15/23 the queryset should be … -
How to link a frontend flutter app with django, Mongodb backend?
I'm new to app development and have been creating a app with flutter UI and creating a backend with django and Mongodb.. How to link this with each other.. I don't know which file should i write the link code. I opened flutter app with dependencies with flutter create newapp and django app. -
Django-cms Type error at admin/cms/page/add-plugin?
I have set up an s3 bucket for the media and static files. Now when I go to edit a page, I can add images, files etc. But when I try to add text I get the following error: TypeError at /admin/cms/page/add-plugin/ unsupported operand type(s) for +: 'NoneType' and 'str' Request Method: GET Request URL: http://my-url.us-west-2.elasticbeanstalk.com/admin/cms/page/add-plugin/?delete-on-cancel&placeholder_id=23&plugin_type=TextPlugin&cms_path=%2Fblog%2Ftest%2F%3Fedit&language=en&plugin_language=en&plugin=46 Django Version: 4.2.3 Exception Type: TypeError Exception Value: unsupported operand type(s) for +: 'NoneType' and 'str' Exception Location: /var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/ djangocms_text_ckeditor/widgets.py, line 106, in get_ckeditor_settings Raised during: cms.admin.placeholderadmin.add_plugin Python Executable: /var/app/venv/staging-LQM1lest/bin/python3.8 Python Version: 3.8.16 Python Path: ['/var/app/current', '/var/app/venv/staging-LQM1lest/bin', '/var/app/venv/staging-LQM1lest/bin', '/usr/lib64/python38.zip', '/usr/lib64/python3.8', '/usr/lib64/python3.8/lib-dynload', '/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages', '/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages'] Error during template rendering In template /var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 20 unsupported operand type(s) for +: 'NoneType' and 'str' Line 20: {{ field.field }} I am not being able to think of any reason for the error other than the storage. Not sure how to proceed. -
Supabase Spotify API request
I'm trying to create a Django app that uses Supabase to authenticate and log into spotify. i do so using the view: def spotify_auth(request): # Redirect the user to Supabase's OAuth authentication endpoint data = supabase_client.auth.sign_in_with_oauth({ "provider": 'spotify', "redirectTo": "http://127.0.0.1:8000//callback/", }) auth_url = data.url return redirect (auth_url) this redirects me to a url like: http://127.0.0.1:8000/callback/#access_token= which is my home page. From my home page i want to be able to redirect to /top-tracks whilst maintaining the access token so i save it to session like so: // Get the fragment URL from the current URL const fragmentUrl = window.location.hash; // Parse the fragment URL to extract key-value pairs const urlParams = new URLSearchParams(fragmentUrl.substring(1)); // Extract and save each piece of data const access_token = urlParams.get('access_token'); // Save the extracted data to localStorage (or sessionStorage if needed) localStorage.setItem('access_token', access_token); I have a button to redirect to /top-tracks and in my top-tracks.html i have a script: <script> const access_token = localStorage.getItem('access_token'); console.log("access token:",access_token) const getTopTracks = async () => { const url = new URL('https://api.spotify.com/v1/me/top/tracks'); url.searchParams.append('time_range', 'short-term'); url.searchParams.append('limit', '20'); const response = await fetch(url,{ method:'GET', headers: { 'Authorization': 'Bearer ' + access_token }, }); const data = await response.json(); console.log(data) } getTopTracks(); … -
name 'my_class' is not defined
I recently started a django course and started a login interface with product registration. While using the functions within the same application, everything worked fine (in this case, I created everything within the users app). I created the products app and the inconsistencies started. views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.http import HttpResponse from django.contrib import messages from .import models @login_required def ListagemProdutos(request): ListaItens = classeproduto.objects.all() return render(request, 'baselist.html', {'produtos': ListaItens}) @login_required def produtoView(request, id): item = get_object_or_404(produto, pk=id) return render(request, 'produto.html', {'produto': item}) urls.py from django.urls import path from .import views urlpatterns = [ path('', views.ListagemProdutos, name='listagemprodutos'), path('produto/<int:id>', views.produtoView, name="produto-view"), ] and models.py from django.db import models class classeproduto(models.Model): STATUS = ( ('Ativo','Ativo'), ('Inativo','Inativo'), ) descricaoresumida = models.CharField(max_length=120) ativo = models.CharField( max_length=7, choices=STATUS, ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.descricaoresumida I already reviewed the code and didn't identify the error =/ Can you help me? NameError at /produtos/ name 'classeproduto' is not defined Request Method: GET Request URL: http://192.168.15.90:8000/produtos/ Django Version: 4.2.4 Exception Type: NameError Exception Value: name 'classeproduto' is not defined Exception Location: C:\Users\Elinton\Desktop\projeto-gestao\gestao\produtos\views.py, line 10, in ListagemProdutos Raised during: produtos.views.ListagemProdutos Python Executable: C:\Users\Elinton\AppData\Local\Programs\Python\Python311\python.exe … -
How to send ajax post request for a video file in Django?
I would like to send an AJAX POST request to a Django view in order to handle a video file. I am developing a basic webpage where users can record video and audio using their camera. Once the user stops recording, the recorded video file will be automatically sent to a backend view where it will be saved to the database. Below is my current JavaScript code. <script> window.onload = function () { const parts = []; let mediaRecorder; navigator.mediaDevices.getUserMedia({ audio: true, video: true}).then(stream => { document.getElementById("video").srcObject = stream; document.getElementById("btn").onclick = function () { mediaRecorder = new MediaRecorder(stream); mediaRecorder.start(1000); mediaRecorder.ondataavailable = function(e) { parts.push(e.data); } } }); document.getElementById("stopbtn").onclick = function () { mediaRecorder.stop(); const blob = new Blob(parts, { type: "video/webm" }); // Create a FormData object to send the Blob const formData = new FormData(); formData.append("video_blob", blob); // Make the ajax call $.ajax({ url: '/save-video/', type: 'POST', success: function (res) { console.log("video uploaded successfully") }, data: formData, cache: false, contentType: false, processData: false }); } }; </script> This is the view I want to send it to where I will eventually save it to the database. def save_video(request): if request.method == "POST" and request.FILES.get("video_blob"): uploaded_blob = request.FILES["video_blob"] Models.objects.create(video_file = … -
Django form validation problem in clean method
I'm new to the Django. Here, whenever I submit the form, validation error didn't appear even though I made mistake in filling form and also validation error isn't visible on the front end. Seek help soon as possible views.py form.py Url.py -
401 Authentication issue with Django using DRF and Django Rest Knox with correct credentials
I'm getting the error 401 when I try to log into my Django application after I tried to implement Django Rest Knox's Token Authentication. I've only very slightly customized Django's Knox LoginView function, and am using a custom User model, which essentially uses organizations' emails in the "username" field. My objectives are: Multiple tokens per user (for multiple device support). Token removal upon logout (security best practice). Feature to remove all tokens (logout from all devices). Secure token storage (encryption/decryption). Token expiration. However, I'm stuck at the authentication at the moment. Django 4.2.3. Django Rest Framework 3.14.0. Django Rest Knox 4.2.0. It's still not deployed, so it's in DEBUG mode, and I'm running the server in WSL in the localhost while I develop it. It just doesn't make any sense. It says the credentials were not provided, but they quite clearly were there when I tested with Insomnia. Relevant sections from my settings.py: INSTALLED_APPS = [ 'accounts', 'knox', 'rest_framework', (..) ] # AUTH USER AUTH_USER_MODEL = 'accounts.CustomUser' # REST FRAMEWORK REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), } REST_KNOX = { 'SECURE_HASH_ALGORITHM':'cryptography.hazmat.primitives.hashes.SHA512', 'AUTH_TOKEN_CHARACTER_LENGTH': 64, # By default, it is set to 64 characters (this shouldn't need changing). 'TOKEN_TTL': timedelta(hours=8), # The default … -
How to solve "OperationalError: database is locked" with simultaneous /admin and management command sessions?
I'm using django with sqlite for a web application which executes a long-running management command to update the database (./manage.sh download_company_data). However, while it's running, I'm unable to create a new user in the Django admin interface. I've already increased the timeout option for the database to 20000: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', 'OPTIONS': { 'timeout': 20000 }, } } The operational errors are immediate, though, ignoring the configured timeout. They happen after clicking on the save button when trying to add a user to the database. I'm simultaneous running the database update process and a runserver process for the admin site. The individual updates are simple and fast, don't access the User table and I have also tried to disconnect from the database and sleep to give room for the server process: for line in c: line = preprocess(line, prefix) search = { unique: line[unique] } for i in range(10): try: Model.objects.update_or_create(**search, defaults=line) break except OperationalError as e: info('Operational error. Delayed retry...') sleep(0.02) connections.close_all() sleep(1) I don't understand why the admin site is repeatedly giving operational errors mentioning the database is locked, even when there's only 1 connection to the sqlite file most … -
The logic of the ORM request does not work
I wanted to make a request to store the winners of the category model in it. That is, there are several nominations in each category, and category_nomination is attached to MemberNomination (work of user). I have a function that looks for category_nomination winners and it kind of works. But I can't do the same with category. I have the sum of the result__score from each MemberNomination from different EventStaff, but I need to make sure that these result__scores from MemberNomination are summed up, find the member who has the highest score in a certain category! But my code gives me MemberNomination those with the highest scores of the sum result__score and belong to a certain category. For example, now he gives me: 1 place Alexey Volkov 22 points 2nd place Ghost Face 12 points 3rd place Ghost Face 11 points That is, if my code worked correctly, it would give: 1st place Ghost Face 23 points 2nd place Alexey Volkov 22 points 3rd place ??? ??? That is, the same member has several MemberNomination, but they need to be added together, since they belong to the same category My models.py: from django.db import models from django_resized import ResizedImageField class PlaceChoices(models.IntegerChoices): … -
Django IntegrityError with UniqueConstraint when switching field value between two entries
I'm trying to write a Model in Django to add emails with specific attributes/options to a contact. As there should only be one billing mail per contact, I added a UniqueConstraint. Adding, updating and deleting entries works fine. However when I want to change which email address is the billing email address I get an error, when I try to just switch the checkboxes between the two entries (disable one and enable the other at the same time/in one go). As a workaround I can first disable the checkbox and save, then enable the other one and save again. For example in this picture I want to make billing@abc.com my billing email, which currently is admin@abc.com. Now when I change the checkboxes as described I get the following error: Django Version: 4.2.5 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: account_email.contact_id, account_email.is_billing_email The model used for this does look like this: class Email(models.Model): contact = models.ForeignKey(Contact, on_delete=models.CASCADE, related_name="contact_emails") email = models.EmailField(max_length=254, db_index=True, null=False, blank=False) is_contact_email = models.BooleanField(_("contact email"), default=True) is_billing_email = models.BooleanField(_("billing email"), default=False) is_subscribed_to_status_notifications = models.BooleanField(_("status notifications"), default=True) is_subscribed_to_newsletter = models.BooleanField(_("newsletter"), default=True) class Meta: constraints = [ models.UniqueConstraint( fields=["contact", "email"], name="contact_and_email_unqiue" ), models.UniqueConstraint( fields=["contact", "is_billing_email"], name="one_billing_email_per_contact", condition=models.Q(is_billing_email=True) ) ] … -
Get the last record for each createdAt
i have this like models class Ticket(UpdateCreateDate): user = models.ForeignKey( User, null=True, on_delete=models.PROTECT, related_name="user" ) bus = models.ForeignKey( Bus, null=True, on_delete=models.PROTECT, related_name="bus_tickets" ) PDA= models.ForeignKey( Material, on_delete=models.PROTECT, related_name="terminal" ) geolocalisation = models.ForeignKey( Geolocalisation, on_delete=models.PROTECT, null=True, blank=True, related_name="geolocalisation", ) i whant to get that format { "today"[{ "itineraire":"Upn - Gare-centrale", "PDA":"PDA-13", "Bus":"TB200", "Driver":"Mr Landu", "date":"20/01/2023", "vente-par-cash":"30", "pu":"30", }], "yesterday"[{ "itineraire":"Upn - Gare-centrale", "PDA":"PDA-13", "Bus":"TB210", "Driver":"Mr Bob", "date":"20/01/2023", "vente-par-cash":"30", "pu":"30", }] } CAN you please help me -
paypal get data back from webhook
So I'm trying to get back my order id from my paypal webhook. I am able to create this paypal checkout page with this code. @csrf_exempt def create_payment(request, id): print(os.environ.get("PAYPAL_API_KEY")) print(id) item = Product() discount = Discount() order_data = get_order_data_func(id) items = [] price = 0 for product in order_data["products"]: product_info = item.get_by_id(product["product"]).to_dict() obj = { "name": product_info["name"], "sku": product_info["name"], "price": int(product_info["price"]), "currency": "EUR", "quantity": product["quantity"] } price += int(product_info["price"]) * product["quantity"] items.append(obj) if order_data["order"]["discount"] is not None: price = price - (price * discount.get_by_id(order_data["order"]["discount"]).percentage / 100) payment = paypalrestsdk.Payment({ "intent":"sale", "payer":{ "payment_method":"paypal" }, "redirect_urls":{ "return_url":"http://localhost:3000/order/success", "cancel_url":"http://localhost:3000/order/cancel" }, "transactions":[{ "item_list":{ "items":items }, "amount":{ "total":price, "currency":"EUR" }, "description":"This is the payment transaction description.", "custom_id": order_data["products"][0]['order'] }] }) if payment.create(): return JsonResponse({'status': 'success', "url": payment.links[1].href}) else: return JsonResponse({'status': 'error'}) I have a webhook running using ngrok I also get back a response but I have not found much online on how to decrypt the response body to see all the data. This is my current function which is called through the webhook. @csrf_exempt def check_paypal_status(request): print(json.loads(request.body)) return JsonResponse({'status': 'success'}) All help is greatly appreciated! -
Can't get Django Channels websockets to connect. Using Django, Daphne and Nginx on Ubuntu 22 with Supervisor
I have been working on getting this figured out for days and I feel like I am close to getting it but I have no idea what to try next. This is how my code is setup: I use Celery to pull data from 2 apis and upload them to my database. I have a post_save method that sends serialized data to my consumers.py I have a javascript script that reads the websocket and plots it. I have a webpage with 3 websockets and 2 of them work fine but one of them I can't get to work and I can't figure out how to troubleshoot it. models.py showing the Gex model which isn't working and the Breadth model which is working. import json from django.db import models from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from django.db.models.signals import post_save from django.dispatch import receiver class Notice(models.Model): date_posted = models.DateTimeField(auto_now_add=True) notice = models.TextField() def get_date_posted(self, obj): return obj.date_posted.strftime('%H:%M:%S') def __str__(self): return f'{self.date_posted} {self.notice}' class Gex(models.Model): timestamp = models.DateTimeField(auto_now_add=False, auto_now=False) ticker = models.CharField(max_length=20) expiration = models.CharField(max_length=10) ratio = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) spot = models.DecimalField(max_digits=8, decimal_places=2) zero_gamma = models.DecimalField(max_digits=8, decimal_places=2) major_pos_vol = models.DecimalField(max_digits=8, decimal_places=2) major_pos_oi = models.DecimalField(max_digits=8, decimal_places=2) major_neg_vol = models.DecimalField(max_digits=8, decimal_places=2) …