Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to use django default login
I'm trying to use django's default admin login function. This works for logging out, i.e. putting in html: <a href="{% url "log_out" %}"> and in urls.py: from django.contrib.auth.views import LoginView, LogoutView path("log_in/", LoginView.as_view(), name="log_in"), path("log_out/", LogoutView.as_view(), name="log_out"), clicking on the logout link takes the user to the django logout page and works correctly. But trying to do the equivalent to log in, i.e.: <a href="{% url "log_in" %}"> causes a TemplateDoesNotExist error. I would like to use django's default login page rather than creating my own template - how can i do this? -
How can I put the search by at the end ? django, bootstrap5
I'm making a simple website using django and bootstrap5. I've tried the class="de-flex justify-content-end" to put my search by at the end but it doesn't work. this is what it looks like: Here is the code: <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container"> <a class="navbar-brand" href="{% url 'my_websites:home' %}"> my website </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'my_websites:about_me' %}"> About Me </a> </li> <li class="nav-item"> <a class="nav-link" href="{%url 'my_websites:blog' %}"> Blog </a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'my_websites:contact' %}"> Contact </a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false"> More </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <li><a class="dropdown-item" href="#">Join our club!</a></li> <li><a class="dropdown-item" href="#">Membership</a></li> <li><a class="dropdown-item" href="#">Be Ullie's friends!</a></li> </ul> </ul> <form class="d-flex justify-content-end"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> </nav> How do i put the search bar at the end? thank you very much for your response in advance! -
SMTPConnectError at [url] : (421, b'Server busy, too many connections') - Django email
I have a simple method (send_activation_email) called from a view which handles user registration by extending default django user auth. It sends an activation email. Now I get the error: SMTPConnectError at /accounts/register/ - (421, b'Server busy, too many connections') the method implementation: def send_activation_email(user, request): current_site = get_current_site(request) subject = 'Activate your membership Account' message = render_to_string('accounts/account_activation_email.html',{ 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) html_message = get_template('accounts/account_activation_html_email.html').render({ 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) send_mail(subject=subject, message=message, from_email= None, recipient_list=[user.email], html_message= html_message #,fail_silently=False ) I have never come across this issue before and have not found any useful answers searching on here. Clearly, this has to do with SMTP and but the thing is I have had the same error trying different providers: sengrid, zoho, outlook. And definitely, the email goes through on console. The logs: Internal Server Error: /accounts/register/ Traceback (most recent call last): File "C:\Users\[**]\membership\myEnv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\[**]\membership\myEnv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\[**]\membership\accounts\views.py", line 70, in register send_activation_email(user, request) File "C:\Users\[**]\membership\accounts\views.py", line 217, in send_activation_email send_mail(subject=subject, File "C:\Users\[**]\membership\myEnv\lib\site-packages\django\core\mail\__init__.py", line 61, in send_mail return mail.send() File "C:\Users\[**]\membership\myEnv\lib\site-packages\django\core\mail\message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) … -
Save a csv like string into Django model
I need to save an amazon response in to mysql db (Django) Here is the example response id purchase-date last-updated-date status 305-0847312-2761164 2022-04-11T22:23:27+00:00 2022-04-11T22:23:31+00:00 Pending 028-3270261-2897162 2022-04-11T22:17:27+00:00 2022-04-11T22:17:30+00:00 Pending 028-8245400-1649940 2022-04-11T22:15:29+00:00 2022-04-11T22:15:32+00:00 Pending 028-2661715-2120359 2022-04-11T21:57:24+00:00 2022-04-11T21:57:28+00:00 Pending 303-9076983-4225163 2022-04-11T21:53:52+00:00 2022-04-11T21:53:55+00:00 Pending 304-7440363-0208337 2022-04-11T21:49:14+00:00 2022-04-11T21:49:17+00:00 Pending 302-2070657-8345128 2022-04-11T21:30:12+00:00 2022-04-12T01:32:20+00:00 Shipped Each header( id, purchase-date, last-updated-date, status ) represents a field in a table, I tried the following code reader = csv.DictReader(res.payload.get("document")) for row in reader: Mytable.Objects.create(field_id=id, **row) Any Idea to achieve this? Regards -
Recommend chatbots similar to CakeChat by LukaLabs
I am currently working on a project to make a Django application that recommends songs based on the tone of the conversation between the user and the chatbot. I had initially planned to use CakeChat, but the project seems to be archived and will not run. I have looked into other options like GPT-3 by OpenAI but am unsure how it will work for my purpose and how to use it. Please recommend options that I can use. I will submit this as my final year graded project in 2 weeks. -
Which Database should I use for developing a Cloud Accounting System like FreshBooks?
I would like to develop a cloud based accounting system with Django. I am planning to use a microservice based architecture. The app will have All-In-One functinalities like: Invoicing Accounting Payments Project Management Client Management etc I understand SQL based databases are best for storing data that are highly relational. But for scalability NOSQL is best. Could you help me decide which one to go for? Thanks. Basically I am looking to make a clone of Freshbooks but with microservice architecture for educational puroposes. -
Django Celery task is showing me "attribute error"?
Hi i build django web application that fetch data from microsoft graph api and inside my django view.py i am calling my task 'add_api_data' from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from datetime import datetime, timedelta from dateutil import tz, parser from tutorial.auth_helper import get_sign_in_flow, get_token_from_code, store_user, remove_user_and_token, get_token from tutorial.graph_helper import * from celery import shared_task import time from tutorial import task import pandas as pd from tutorial.models import demo,assignment_details def education(request): add_api_data = task.add_api_data.delay() api_list = assignment_details.objects.all().values() return render(request, 'tutorial/education.html', {'api_list':api_list,}) def home1(request): context = initialize_context(request) add_data = task.add_csv_data.delay() title1 = demo.objects.all().values() return render(request, 'tutorial/demo1.html',{'title1':title1,'context':context}) my auth_helper.py # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # <FirstCodeSnippet> import yaml import msal import os import time # Load the oauth_settings.yml file stream = open('oauth_settings.yml', 'r') settings = yaml.load(stream, yaml.SafeLoader) def load_cache(request): # Check for a token cache in the session cache = msal.SerializableTokenCache() if request.session.get('token_cache'): cache.deserialize(request.session['token_cache']) return cache def save_cache(request, cache): # If cache has changed, persist back to session if cache.has_state_changed: request.session['token_cache'] = cache.serialize() def get_msal_app(cache=None): # Initialize the MSAL confidential client auth_app = msal.ConfidentialClientApplication( settings['app_id'], authority=settings['authority'], client_credential=settings['app_secret'], token_cache=cache) return auth_app # Method to generate a sign-in flow def … -
Django Rest Framework: How to make relative URLs clickable?
By passing an empty request to the context of ViewSet, it's possible to have the instance URLs rendered as relative URLs instead of absolute (i.e. the host is omitted). However, when https:// is missing from the URL DRF does not render the string as a clickable URL which makes jumping from one resource to the other rather difficult. -
Internet SPEED TEST using python
I have built a code where I can find out the downloading speed, uploading speed, etc in python. Now I want to give it a shape of a web application.What will be the approach I will take and how to do that any suggestions. -
Change BASE_DIR in django settings to up a directory
I am working on django project in which I tried to setup multiple settings files and now I am getting database migrations error/notification .I dont want to create new db and use the previous one . Previous dir Structure |myproject |-myproject |--settings.py |-db and in my base.py BASE_DIR = Path(__file__).resolve().parent.parent Current Dir |myproject |-myproject |--db(new db after running sever) |--settings |---base.py |---development.py |-db(old db) I dont how base_dir thing works .I want to use my old db and all other stuff .I tried google but I dont understand anything there.so how to I up one dir my BASE_DIR path . Thanks in advance any advice will be helpful. -
Django template tag returns HTML in hex
I created a custom templatetag to make a list, but upon use within a IMG tag, it returns the HTML in HEX. Templatetag from django import template register = template.Library() # use @register.assignment_tag # only when you're working with django version lower than 1.9 @register.simple_tag() def make_list(*args): return args HTML template {% make_list "hyperion_v2" "atomic_api" "full_history" "api_node" as logo_list %} {% for i in logo_list %} {{ i }} <img src="{% static 'images/{{ i }}.png' %}" class="{% if result.{{ i }} == True %}logoGreen{% else %}logoRed{% endif %} servicelogos card-img-top rounded" style="width: 50px; height: 50px;"> {% endfor %} HTML Response: hyperion_v2 <img src="/static/images/%7B%7B%20i%20%7D%7D.png" class="logoRed servicelogos card-img-top rounded" style="width: 50px; height: 50px;"> atomic_api <img src="/static/images/%7B%7B%20i%20%7D%7D.png" class="logoRed servicelogos card-img-top rounded" style="width: 50px; height: 50px;"> full_history <img src="/static/images/%7B%7B%20i%20%7D%7D.png" class="logoRed servicelogos card-img-top rounded" style="width: 50px; height: 50px;"> api_node <img src="/static/images/%7B%7B%20i%20%7D%7D.png" class="logoRed servicelogos card-img-top rounded" style="width: 50px; height: 50px;"> -
Speed up Django bulk_create with unique fields
I have a database with thousands of entries. Each entry has a unique field that I called unique_id and it's calculated on some other fields: class ModelA(models.Model): name = models.CharField(max_length=256, help_text="Type a name") created_at = models.DateTimeField(auto_now_add=True) unique_id = models.CharField(max_length=256, unique=True, editable=False, default=calculate_my_unique_id) This is the algorithm I'm using to prevent duplicates (omitting a bit of code): objectsToAdd = [] items_dict = ModelA.objects.in_bulk(field_name='unique_id') unique_id = generate_unique_id() if unique_id not in items_dict.keys(): objectsToAdd.append( ModelA( name=item_name, unique_id=unique_id ) ) if objectsToAdd: ModelA.objects.bulk_create(objs=objectsToAdd) The problem is that when table items grow, will grow also item_dict list and consequently the check time. Is there a more efficient way to simply skip duplicates from bulk insert? -
django-tinymce working with django-admin but not working in form template
in django admin django-tinymce is working but in template tinymce widget is not working. Please provide a solution django model my model.py class Question(models.Model): nameuser = models.ForeignKey(Profile,on_delete=models.CASCADE) title = models.CharField(max_length=200,blank=True,null=True) timestamp = models.DateTimeField(auto_now_add=True) contents = tinymce.HTMLField(blank=True,null=True) tags = models.ManyToManyField(Tags) id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True,editable=False) form.py class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ('title','contents','tags') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['title'].widget.attrs.update({'class': 'form-control','placeholder':'Enter Title'}) self.fields['tags'].widget.attrs.update({'class': 'form-control'}) in temlate it show only blank form-control template view -
Django admin: how to increase field label width in admin change form view?
I want to customize Django admin change_form.html template for some of my model. I would like to increase field label size and try by ovverriding change_form.html template. But it dosen't work. My own change_form.html is displayed but css style is not applied . When I open debug, an error is raised for change_form.js: django is not defined change_form.html {% extends "admin/change_form.html" %} {% load static %} {% block extrahead %} <!-- Custom --> <link rel="stylesheet" href="{% static 'ecrf/css/custom_change_form.css' %}"> {% endblock %} custom_change_form.css // pat is one of my field .column-pat { color: red !important; min-width: 200px; } admin.py class VisiteAdmin(SimpleHistoryAdmin): list_display = ('pat','vis_dat',timing_visit,'sai_log','sai_dat','ver','ver_usr','ver_dat') change_form_template = 'ecrf/admin/change_form.html' -
flutter web with django on diffrent host make error minifield:b6
hi guys i have one host my flutter web run on it and another one for django to send data to my flutter web after go to my website my site not show parametr just show this error minifield:b6 and in offline all works...like this: what can i do to solve this issue Doctor summary (to see all details, run flutter doctor -v): [√] Flutter (Channel beta, 2.9.0-0.1.pre, on Microsoft Windows [Version 10.0.19044.1586], locale en-US) [√] Android toolchain - develop for Android devices (Android SDK version 32.0.0) [√] Chrome - develop for the web [√] Android Studio (version 2020.3) [√] Connected device (2 available) • No issues found! [enter image description here][1] [1]: https://i.stack.imgur.com/Og2MG.jpg -
run django project without databasei,removed this code find some errors like this," settings.DATABASES is improperly configured."
DATABASES{ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'xys', 'USER': 'postgres', 'PASSWORD': 'xyz', 'HOST': 'localhost', 'PORT': '5432', } No need of this code in django settings. My requirement in my project no need database in django settings