Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Store datapoints persistently before writing to database
I have a Django app that receives sensor data. This data is then processed and written to influxDB using the influxdb-client-python library. I would like to write the data in an asynchronous manner and thus return a response to the producer of the data before it is actually written to the database. However, once I send this response I can no longer afford to lose this data. Since I can never be sure that the server will in fact be able to write the data to influxDB, I was thinking about first writing it to a file and returning a response after this is successful (similar to a WAL). This introduces new problems like making sure the WAL is actually written to a file and most importantly, making sure it is thread-safe since the server may be handling multiple requests concurrently. Is there any better way of doing this, maybe built-in in Django? -
Django for React Freamework setup
code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: ccalendar@0.1.0 npm ERR! Found: react@18.0.0 npm ERR! node_modules/react npm ERR! react@"^18.0.0" from the root project npm ERR! npm ERR! Could not resolve dependency: npm ERR! peer react@"<18.0.0" from @testing-library/react@12.1.5 npm ERR! node_modules/@testing-library/react npm ERR! @testing-library/react@"^12.0.0" from the root project npm ERR! npm ERR! Fix the upstream dependency conflict, or retry npm ERR! this command with --force, or --legacy-peer-deps npm ERR! to accept an incorrect (and potentially broken) dependency resolution. npm ERR! npm ERR! See /Users/sahin/.npm/eresolve-report.txt for a full report. npm ERR! A complete log of this run can be found in: npm ERR! /Users/sahin/.npm/_logs/2022-04-12T12_34_08_137Z-debug-0.log npm install --no-audit --save @testing-library/jest-dom@^5.14.1 @testing-library/react@^12.0.0 @testing-library/user-event@^13.2.1 web-vitals@^2.1.0 failed (env) sahin@Sahin-MacBook-Pro-2 CAlendar % npm create-react-app ccalendar Unknown command: "create-react-app" -
How to get event from client socket and sent to django channels
I need to get info from websocket wss://ws.binotel.com:9002 routing.py websocket_urlpatterns = [ re_path(r'wss://ws.binotel.com:9002', BinotelCallsConsumer.as_asgi()), ] asgi.py application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ), }) But it dosnt connect to this socket -
Django - showing cdn npm gantt chart in template
I'm using a npm package called svelte-gantt via this cdn here: npm cdn. However I can't for the life of me get the chart to show in the template, I can't find an example of it being used with django so I'm not sure if it's possible. What am I doing wrong here for it not to show up? How can I use the package & gantt chart in my django template? {% extends "home/base.html" %} {% block content %} <style> #example-gantt { flex-grow: 1; overflow: auto; height: 600px; width: 100px; } .container { display: flex; overflow: auto; flex: 1; } </style> <div class="container"> <div id="example-gantt"></div> </div> <script src="https://cdn.jsdelivr.net/npm/svelte-gantt@4.0.3-beta/index.min.js"></script> <script> var options = {}; var gantt = new SvelteGantt({ // target a DOM element target: document.getElementById('example-gantt'), // svelte-gantt options props: options }); </script> {% endblock content %} -
Add Multuple Field django In admin Panel
How can I add please icons in Admin panel for exemple when I click to add icons ,it duplicate model Field . the Field is not related to forgien table . enter image description here -
Confirm Action inside JS success call - cancel button also submitting form
When a user clicks on submit button, I want to show a confirm dialog with a count of records that would be affected. To get the count, I am calling the related url inside ajax and in success am trying to confirm from user. But, in the confirmation dialog box, when user clicks on cancel also, the form is getting submitted successfully. $(document).ready(function(){ $('form').submit(function(e) { // e.preventDefault(); const a= $(id_a).val(); const b = $(id_b).val(); const c = $(id_c).val(); const d = $(id_d).val() $.ajax({ type: "GET", url: "/myURL", data: { 'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(), 'a':a, 'b':b, 'c':c, 'd':d }, success: function (data) { if (confirm(`${data.result} records will get affected. Do you want to continue?`)){ $('form#id_save').submit(); } else { e.preventDefault() } }); }) }) -
How to get the count of fields that are either None ot empty in a row using ORM Django?
I have a model, class personal_profile(models.Model): custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) picture = models.ImageField(default='pro.png', upload_to='profile_image', blank=True) designation = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(max_length=255, blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) language = models.CharField(max_length=255, blank=True, null=True) linkedin_url = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return str(self.pk) I want to get the number of field's count which are either None or "". personal_profile.objects.get(custom_user=some_user_id) By the open query, I can get the queryset of that specific user. Now that is a way to get the count of empty or None fields in database. Thanks -
Django - tabularinline in a forms in template
I have an votes app (question and choice). In admin i can use TabularInline to see for every question the fiedls choice (default 3 fields) and in admin i can set the name of the question, poster and choice for that question and i can create question with choices and from template i can vote etc. But I don't know how to make a form with exact mechanism to use in template where to set the name, poster and most important the choices for that question with the mecanism to add another choice like in admin area. What i try in the form is this class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class creareSondajForm(ModelForm): class Meta: model = Question fields = [ 'question_text', 'poster' ] inlines = [ChoiceInline] but in template it show only the input for name of the question and poster not the input where to set the choice. Please help me. Thank you! Below my settings. models.py class Question(models.Model): question_text = models.CharField(max_length=200, verbose_name='Intrebare') poster = models.ImageField ( upload_to ='sondaj/', default='sondaj/poster_sondaj_pl.jpg', verbose_name='Poster (120px * 96px)') pub_date = models.DateTimeField('publicat la:') def __str__(self): return self.question_text #pentru a redimensiona rezolutia posterului incarcat def save(self, *args, **kawrgs): super().save(*args, **kawrgs) img = … -
Django: end_time = models.TimeField. Is there a way to subtract minutes from this field?
I am trying to automatically subtract 60s or 1 minute from an end_time input by the user. Is there a way to do this? I am using Django v3.2. model.py end_time = models.TimeField(auto_now_add=False, blank=True) views.py def post(self, request): booking_form = BookingForm(data=request.POST) if booking_form.is_valid(): booking = booking_form.save(commit=False) booking.user = request.user if Booking.objects.filter( table=booking.table, date=booking.date, start_time=booking.start_time, approved=booking.approved is True ).exists(): return render(request, '/',) else: booking.save() return render(request, '/',) -
django modeltranslate default language duplicate value
my model: class DoctorSpeciality(BaseModel): name = models.CharField(max_length=255, unique=True, db_index=True) class Meta: db_table = 'doctor_specialities' When i am trying to translate this model, django modeltranslation creates two fields name_de, name_en. But i also have name field, name and name_de have same value. Is it possible not to create default language column into database to prevent duplicated value ? -
How to display a generated image stored in memory with django?
I am a beginner with django. I am trying to display an image that is stored in a variable. (I am using PIL for the image generation). This variable is then passed to the html page concerned. However I can't display this image because Django expects a path for this image which is stored in memory and not saved in a file. Is there a way to display an image that is stored in memory? Here is an example of code def img_generator(parm1,parm2,parm3): ... #image generation stuff return generated_image #somewhere else in the code my_img = img_generator(8,4,8) The image is transmitted as follows: def results(request): return render(request, "html_page_to_display.html", context={'var1':var1, .#other vars .#other vars 'my_img':my_img, # my image I want to display }) And finally, the image is displayed via the following html tag: <img src=" {{ my_img }}" /> I am definitely doing it the wrong way. Could you help me to solve this problem ? Here are 2 logs describing the error : Not Found: /index/home/<PIL.Image.Image image mode=RGBA size=234x305 at 0x174792017B0> [12/Apr/2022 13:36:17] "GET /index/home/%3CPIL.Image.Image%20image%20mode=RGBA%20size=234x305%20at%200x174792017B0%3E HTTP/1.1" 404 4072 -
Django - how to pass objects instance data from one view to the next
so I'm making digital schoolregister as a portfolio project. Here I have one view: for the teacher, with list of students in a class and next to them are their grades. I wanted to make each grade as hyperlink so after clicking one - it can be edited, but my code doesn't pass this grade data to the next view. Here's my code: views.py @login_required def class_detail(request): school_class = get_object_or_404(SchoolClass, id=1) semesters = school_class.school_year.semester_set.all() students = school_class.students.all() grades_1_sem = [] grades_2_sem = [] subject = Subject.objects.get(id=1) for student in students: grades_1_sem.append(student.grade_set.filter(school_year=school_class.school_year, semester=Semester.objects.get(number=1))) grades_2_sem.append(student.grade_set.filter(school_year=school_class.school_year, semester=Semester.objects.get(number=2))) students_grades_1_sem = list(zip(students, grades_1_sem)) students_grades_2_sem = list(zip(students, grades_2_sem)) return render(request, 'schoolregister/nauczyciel/klasa.html', { 'school_class': school_class, 'students': students, 'grades': grades, 'subject': subject, 'students_grades_1_sem': students_grades_1_sem, 'students_grades_2_sem': students_grades_2_sem, }) def edit_grade(request): if request.method == 'POST': grade_to_edit = GradeToEdit(request.POST) if grade_to_edit.is_valid(): grade_to_edit.save() return HttpResponseRedirect('') else: return HttpResponse("Error.") else: grade_to_edit = GradeToEdit() return render(request, 'schoolregister/edit_grade.html', {'grade_to_edit': grade_to_edit,}) forms.py class GradeToEdit(forms.ModelForm): class Meta: model = Grade fields = ('grade', 'school_year', 'semester', 'subject', 'student', 'description') urls.py urlpatterns = [ path('nauczyciel/<int:school_class_id>/<int:subject_id>/', views.class_detail, name='class_detail'), path('edit_grade/', views.edit_grade, name='edit_grade'), ] Here's the code with a href tag that should go to next view, and pass data, but it doesn't pass data for Grade instance: klasa.html {% for semester … -
Can someone suggest me how to use React ,Django and GraphQL
I am a React.js developer, Learning Django as backend and GraphQL. Stuck with fetching data from the backend using Graphql -
OSError: cannot load library 'gobject-2.0-0' M1-Cheap
import weasyprint Traceback (most recent call last): File "", line 1, in File "/Applications/MAMP/htdocs/django/virtualenv/lib/python3.10/site-packages/weasyprint/init.py", line 325, in from .css import preprocess_stylesheet # noqa isort:skip File "/Applications/MAMP/htdocs/django/virtualenv/lib/python3.10/site-packages/weasyprint/css/init.py", line 27, in from . import computed_values, counters, media_queries File "/Applications/MAMP/htdocs/django/virtualenv/lib/python3.10/site-packages/weasyprint/css/computed_values.py", line 16, in from ..text.ffi import ffi, pango, units_to_double File "/Applications/MAMP/htdocs/django/virtualenv/lib/python3.10/site-packages/weasyprint/text/ffi.py", line 404, in gobject = _dlopen( File "/Applications/MAMP/htdocs/django/virtualenv/lib/python3.10/site-packages/weasyprint/text/ffi.py", line 391, in _dlopen return ffi.dlopen(names[0]) # pragma: no cover File "/Applications/MAMP/htdocs/django/virtualenv/lib/python3.10/site-packages/cffi/api.py", line 150, in dlopen lib, function_cache = _make_ffi_library(self, name, flags) File "/Applications/MAMP/htdocs/django/virtualenv/lib/python3.10/site-packages/cffi/api.py", line 832, in _make_ffi_library backendlib = _load_backend_lib(backend, libname, flags) File "/Applications/MAMP/htdocs/django/virtualenv/lib/python3.10/site-packages/cffi/api.py", line 827, in _load_backend_lib raise OSError(msg) OSError: cannot load library 'gobject-2.0-0': dlopen(gobject-2.0-0, 2): image not found. Additionally, ctypes.util.find_library() did not manage to locate a library called 'gobject-2.0-0' -
MultiValueDictKeyError when passing empty file
In my website uploading picture is not compulsory, Therefore when left empty I get MultiValueDictKeyError But if i pass an image is dont get an error. Am I missing some thing?? Thanks in advance.... views.py if request.method == "POST": FirstName = request.POST['FirstName'] LastName = request.POST['LastName'] image = request.FILES['image'] #This one age = request.POST['age'] gender = request.POST['gender'] address = request.POST['address'] PhoneNumber = request.POST['PhoneNumber'] EmailAddress = request.POST['EmailAddress'] Password = request.POST['Password'] RepeatPassword = request.POST['RepeatPassword'] BloodGroup = request.POST['BloodGroup'] try: if Password == RepeatPassword: Patient.objects.create(FirstName=FirstName, LastName=LastName, image=image, age=age, gender=gender, address=address, PhoneNumber=PhoneNumber, EmailAddress=EmailAddress, BloodGroup=BloodGroup) return redirect('login') else: messages.success( request, ("Passwords do not match. Please try again")) except Exception as e: messages.success( request, ("This email already exists. Try again with another email or recover your account")) return render(request, 'signup.html') HTML <div class="input-div one"> <div class="i"> <ion-icon name="image-sharp"></ion-icon> </div> <div class="div"> <h5>Photo</h5> <input type="file" class="input" name="image"> </div> </div> -
django display the records inside folders
So, here i have records on my django website where i list the records so all theses records belong to different categories currently i have my them displayed like this but i want them to be listed inside the folders named after categories that means the all the records should be grouped based on categories and should reside inside the folders that belongs that particular folder. views.py class RecordListAPIView(ListAPIView): serializer_class = "" permission_classes = "" queryset = Model.objects.all() ordering = "" ordering_param = "" ordering_fields = ( ) def get_total_queryset(self): if self.request.user: return Model.objects_with_cat.all() return Model.objects.all() -
how to keep count of each items in list - python
i was trying to keep count of each item in list in python and want to convert it into key-value pairs like json so i can able to iterate over it to present it on frontend using django. list = ["a" , "a", "c", "b", "c", "d"] here same i want this list into key value pairs with counting of each item in list list = [{ "name":"a" , "count":2 } , { "name":"c" , "count":2 , ......}] -
How to load 2 querysets with a single query in django
class Order(models.Model): ID = models.AutoField(primary_key=True) product = models.ForeignKey(Products, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) Items = models.ManyToManyField('OrderItems') def placeOrder(self): self.save() @staticmethod def get_orders_by_customer(customer_id): return Order.objects.filter(customer=customer_id).order_by('-date') def __str__(self): return self.product.name + ' / ' + self.customer.email class OrderItems(models.Model): ID = models.AutoField(primary_key=True) Item = models.ForeignKey(Products, on_delete=models.DO_NOTHING) Quantity = models.IntegerField('Quantity') Price = models.DecimalField('Price', max_digits=10, decimal_places=2) OrderNo = models.ForeignKey(Order, on_delete=models.DO_NOTHING) def __str__(self): return str(self.ID) How to load Orders along with its OrderItems in a single query -
Fetch queryset with maximum view counts books
I have a model class Book(models.Model): title = models.CharField(max_length=500, null=True, blank=True) description = RichTextField(null=True, blank=True) view_counts = models.IntegerField(null=True, blank=True, default=0) Each time a user views a book instance in detailed view the view_counts attribute is incremented by 1. Challenge: Writting a query that will filter for only two books with highest view counts. -
S3 returns 403 error when uploading image from html
I am testing python django program in local server. python manage.py runserver I try to uploading image file to S3 with s3direct from html form. https://github.com/bradleyg/django-s3direct[enter link description here]1 Now, I have two S3 in two different account. One S3 works(uploaded successful) and another one not, just showing 403 error initiate error: si2-vr-resource-51835-91/line-assets/images/a6de64235c70497a884c6600f53ac7c5/_origin.jpg AWS Code: AccessDenied, Message:Access Deniedstatus:403 Mysteriously, these two S3 is completely the same access permission. Block public access = off Same bucket policy ACL = on Same CORS Is there any other settings related setting with 403 error?? One Bucket policy { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::si2-vr-static-resource-v/*" }, { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::678100228133:role/cm-dev-resource-CustomS3AutoDeleteObjectsCustomRes-17JLK9FU5A4YR" }, "Action": [ "s3:GetBucket*", "s3:List*", "s3:DeleteObject*" ], "Resource": [ "arn:aws:s3:::si2-vr-static-resource-v", "arn:aws:s3:::si2-vr-static-resource-v/*" ] }, { "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": [ "arn:aws:s3:::si2-vr-static-resource-v/line-assets/images/*/240", "arn:aws:s3:::si2-vr-static-resource-v/line-assets/images/*/300", "arn:aws:s3:::si2-vr-static-resource-v/line-assets/images/*/460", "arn:aws:s3:::si2-vr-static-resource-v/line-assets/images/*/700", "arn:aws:s3:::si2-vr-static-resource-v/line-assets/images/*/1040" ] }, { "Effect": "Deny", "NotPrincipal": { "Service": "lambda.amazonaws.com" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::si2-vr-static-resource-v/line-assets/images/*/_origin.*" } ] } Another bucketpolicy { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::si2-vr-resource-51835-91/*" }, { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::665852216828:role/cm-stag-resource-CustomS3AutoDeleteObjectsCustomRe-1D9B0M28FPT97" }, "Action": [ "s3:GetBucket*", "s3:List*", "s3:DeleteObject*" ], "Resource": [ "arn:aws:s3:::si2-vr-resource-51835-91", … -
How to write a character in python html
I want "V" in html page when I add value in database <td>{{stud.MaxVolt}}</td> one way is I write V with database's value but I want it to be written automatically -
Serve media files from outside the Django-project-folder with Nginx
I'm trying to serve in production (not development) media files for my Django-project with a Nginx-server. The media-files are not located within the django-folder. The folder structure is like: |- django_user | |- media | |- Myproject | |- static | |- myproject | |- settings.py Nginx-Server: upstream websocket{ server 127.0.0.1:6379; } server { server_name myproject.com; client_max_body_size 5M; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/django_user/Myproject; } location /media/ { root /home/django_user/media; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/myproject.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/myproject.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot location /ws { proxy_pass http://websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-Proto $scheme; } } server { if ($host = myproject.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name myproject.com return 404; # managed by Certbot } Here is a part of my settings.py: # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: … -
TypeError: 'KitsProducts' instance expected, got <KitProducts: KitProducts object (496)>
I am trying to add manyomany objects via a script for the following model: class KitsProducts(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) class AllotmentFlow(models.Model): flow = models.ForeignKey(Flow, on_delete=models.CASCADE) kit = models.ForeignKey(Kit, on_delete=models.CASCADE) asked_quantity = models.IntegerField(default=0) alloted_quantity = models.IntegerField(default=0) items = models.ManyToManyField(KitsProducts) like the following: print("m", m) #create allotmentflow flow = Flow.objects.get(flow_name=m['flow_name'][0]) kit = Kit.objects.get(kit_name=m['kit_name'][0]) af_obj = AllotmentFlow.objects.create(flow=flow, kit=kit, asked_quantity=m['asked_quantity'][0], alloted_quantity=m['alloted_quantity'][0]) kitsproducts = [] for index, row in m.iterrows(): product = Product.objects.get(short_code=row['product']) quan = row['quantity'] kp_obj = KitProducts.objects.create(product=product, quantity=quan) kitsproducts.append(kp_obj) print("kitsproduct", kitsproducts) af_obj.items.set(kitsproducts) the following error occurs while trying to set the kitsproducts in AllotmentFlow object: TypeError: 'KitsProducts' instance expected, got <KitProducts: KitProducts object (496)> -
Annotate individually each item in a Django Queryset
I'm trying to get a queryset that tells me if a user is subscribed to a given mailing list and being able to access that bool using mailing_list.is_subbed So ideally we would have a queryset where each item has a annotated field "is_subbed" which is either True or False depending if the given user is subscribed to the mailing list or not. For context, this view is going to serve a form with checkboxes that are checked/unchecked depending on the status of the user. The page is accessible in incognito mode through a url that holds a token which contains 1) The email of the user and 2) The ID of the mail send record (which holds details like the mailing list it's been sent to, details below) In the current state, the is_subbed function is called only once on the first item, and the resulting bool is annotated to every item, I'd like it to run for each item in the queryset. How can I do that ? For now if the first item returns True once fed to is_subbed, every checkbox is marked because the annotated field is_subbed is set to True on each item. Here is my … -
What is the best way to handle DJANGO migration data with over 500k records for MYSQL
A migration handles creating two new fields action_duplicate and status_duplicate The second migration copies the data from the action and status fields, to the two newly created fields def remove_foreign_keys_from_user_request(apps, schema_editor): UserRequests = apps.get_model("users", "UserRequests") for request_initiated in UserRequests.objects.all().select_related("action", "status"): request_initiated.action_duplicate = request_initiated.action.name request_initiated.status_duplicate = request_initiated.status.name request_initiated.save() The third migration is suppose to remove/delete the old fields action and status The fourth migration should rename the new duplicate fields to the old deleted fields The solution here is to remove the dependency on the status and action, to avoid uneccesary data base query, since the status especially will only be pending and completed My question is for the second migration. The number of records are between 300k to 600k records so i need to know a more efficient way to do this so it doesn't take up all the memory available. Note: The Django Database is Mysql