Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django {% inlcude %} throws Template Error
The problem: I have a file base.html, where I have a {% block content %}, for the page's content and a {% inlcude %}, for the navigation bar (bootstrap) of the base template. But the include does not find the Template (TemplateDoesNotExist) and I am sure I didn't spell it wrong. Do I have to provide anything for the template to be found or what? base.html important content: <body> {% include "navbar.html" %} <div> {% block content %} {% endblock %} </div> </body> Some important information: I downloaded bootstrap in the base.html file; base.html and navbar.html are in the same folder. -
Storing dynamic data in django
So, in my application I currently am receiving and storing some data,the structure currently is based around this: Each application has a number of devices Each device has incoming data from its sensors Each sensor has a type (e.g. temperature/humidity/etc) Initially, I had wanted to find a solution to store the data dynamically into one table for all data, with a model that might look like this: time = models.DateTimeField() sensor = models.ForeignKey(Sensor, on_delete=models.CASCADE) data = ??? Now, each sensor is connected in the models to all the details (including the application, the sensor hardware information and other API-related information for connecting to said sensors), however, for the data I looked up a number of options but I have yet to find one that feels sufficient, some of the options I explored are: Storing the data in a dictionary and storing that in a model as per the answers in Here Having separate tables and somehow calling the models later when storing data using the method here, in addition to some system with inheritance such as discussed here Something similar to this using dynamic fields I am currently using mySQL, and I saw some other solutions that might work using … -
Hosting a Spotify API app on Heroku error
Summary: We are running a local version of a Django rooms app where people can join together and listen to music at the same time on different devices. When we test it on localhost everything works but then when we deployed it on Heroku we get an error saying{see problem}. Does Heroku not support the spotify API ? Problem: Uncaught (in promise) EMEError: Platform does not support navigator.requestMediaKeySystemAccess at new e (https://sdk.scdn.co/embedded/index.js:119:253) at Function.e.fatal (https://sdk.scdn.co/embedded/index.js:119:516) at https://sdk.scdn.co/embedded/index.js:55:2946 at new Promise (<anonymous>) at Function.r.create (https://sdk.scdn.co/embedded/index.js:55:2867) at Function.t.create (https://sdk.scdn.co/embedded/index.js:79:6011) at https://sdk.scdn.co/embedded/index.js:137:2839 at new Promise (<anonymous>) at createPlayer (https://sdk.scdn.co/embedded/index.js:137:2217) at Object.createStreamerForClient (https://sdk.scdn.co/embedded/index.js:271:2104) -
Django User Generated Group or Communities
Is there any way in django whereby an authenticated user is able to generate a group or generate a community where they can add another user and share information to group members. They are also able to give other users permission to add other users(not the django admin authentication type of group). -
"detail": "Given token not valid for any token type" when using drf-social-oauth2
I have been using drf-social-oauth2 for google authentication. After using the following curl -X POST -d "grant_type=convert_token&client_id=<client_id>&client_secret=<client_secret>&backend=<backend>&token=<backend_token>" http://localhost:8000/auth/convert-token provides this output: { "access_token": "", "expires_in": 36000, "token_type": "Bearer", "scope": "read write", "refresh_token": "" } But whenever i try to access view using this token it throws an error: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } Even if the token is new. -
Foreign key mismatch error in Django python
I am new to Django and I am stuck on an error "Foreign key mismatch error" while migrating my project. I have the following models in my project: from django.db import models # Create your models here. class Product(models.Model): product_id=models.AutoField product_name=models.CharField(max_length=50) product_desc=models.CharField(max_length=50) product_date=models.DateField() product_image=models.ImageField(upload_to="shop/images",default="") def __str__(self): return self.product_name class User(models.Model): user_email=models.EmailField(primary_key=True) user_name=models.CharField(max_length=20) def __str__(self): return self.user_email class Student(models.Model): course=( ('MS','MS'), ('BS','BS') ) student_name=models.CharField(max_length=40) student_roll=models.IntegerField(primary_key=True) student_course=models.CharField(max_length=100,choices=course) class Order(models.Model): user=models.ForeignKey(Student, on_delete=models.CASCADE) id=models.IntegerField(primary_key=True) date=models.DateField() time=models.TimeField() price=models.FloatField() def __str__(self): return str(self.id) class Teacher(models.Model): user_email=models.EmailField(primary_key=True) user_name=models.CharField(max_length=20) def __str__(self): return self.user_email I also created two more tables; Person and Group but I deleted these two tables later. Now, when I migrate my project using python manage.py makemigrations and then python manage.py migrate I still get the error; django.db.utils.OperationalError: foreign key mismatch - "shop_membership" referencing "shop_person" So, what should I do now? -
error Object of type User is not JSON serializable
Hi Im trying to obtain a json response to pass into the template, the isssue come when I ask the owner attribute such is coming from User model. I received everything ok except message.owner. I tried to make User serializable object, first, but yet it don't work. Here my code Chat Model ''' class ChatView(LoginRequiredMixin, View): model = Chat template_name = 'chats/all_chats.html' def get(self, request): return render(request, 'chats/all_chats.html') def post(self, request): chat = Chat(text=request.POST['message'], owner=request.user) chat.save() return redirect(reverse('all_chat')) @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) class ChatMessagesView(LoginRequiredMixin, View): def get(self, request): User = get_user_model() messages = Chat.objects.all().order_by('created_at')[10:] results = [] for message in messages: result = [message.text, message.owner, naturaltime(message.created_at)] results.append(result) ''' -
How to filter a django queryset with multiple ManyToMany references
This is the shape of my models. class SomeModel(model): some_field = models.DateTimeField(blank=True, null=True) class OtherModel(Model): list_of_some_models = models.ManyToManyField(SomeModel) I have a dictionary like this, where each element in the list is the SomeModel pk: { "list_of_some_models": [1, 10, 12, 20] } I would like to check if there is already a record that has a relationship with SomeModel of id 1, 10, 12 and 20. is it possible? -
How to configure license on other ports besides 443 and 8080
I'm trying to run my django app on port 443 or 8080 but I'm getting winerror:10013. I guess this problem occours when these ports are being used by some other program. Can I configure the license to listen on other ports besides 8080 and 443. I have windows7 on my windows2008R server. -
Subtracting two quantities value from two different class model in Django
I am trying to do a subtraction after complete the payment. I have 2 models, the Item and the Order with 2 different quantities. I tried the function below to process it but it remains the same quantity. The function works fine, but the only problem is the quantity. I've tried 2 approaches for the said problem, but both are not working. Views.py 1st @login_required def paymentComplete(request): try: body = json.loads(request.body) order = Order.objects.get(id=body['orderID']) for order_item in order.items.all(): orderitem = order_item.item.item_quantity item = order_item.quantity order_item.item.item_quantity = int(orderitem) - int(item) order_item.ordered = True order_item.save() order.ordered = True order.total_price = body['total'] order.save() messages.success(request, "Order has been processed!") return JsonResponse('Payment Complete', safe=False) except: messages.warning(request, "Payment did not go throuh") return redirect('order-summary') Views.py 2nd @login_required def paymentComplete(request): try: body = json.loads(request.body) order = Order.objects.get(id=body['orderID']) for order_item in order.items.all(): order_item.item.item_quantity -= order_item.quantity order_item.ordered = True order_item.save() order.ordered = True order.total_price = body['total'] order.save() messages.success(request, "Order has been processed!") return JsonResponse('Payment Complete', safe=False) except: messages.warning(request, "Payment did not go throuh") return redirect('order-summary') Models.py class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField() price = models.FloatField() stored = models.DateTimeField(auto_now_add=True) item_quantity = models.IntegerField(default=1) img = models.ImageField(upload_to=get_upload_path) category = models.CharField(choices=CATEGORY_CHOICES, max_length=15) slug = models.SlugField() class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) … -
How to annotate only some rows
I have a data model which simplifies to following simple parent-child relationship (in reality there are couple of intermediate tables, and it is greatgrandparent-child relationship, but lets keep things simple): parent: parent_id: int parent_data: int important: bool child: child_id: int parent_id: int child_data: int Now i want get aggregated data (using Sum for simplicity here) per parent. Which could be done as: Parent.objects.values('parent_id', 'parent_data').annotate(Sum('children__child_data')) However due to high number of rows I would like to query this aggregated result only for the important parent (and for the rest only query the parent_data). There are some workarounds there. For example I can use two queries (where I filter only the important parents for one query and unimportant parents for the other) and use the annotate only on the first one. Then I can process the queries and combine them later in python -- however this feels clunky and also messes up the ordering. Is there an elegant way of doing this in single go? Essentially I want equivalent of raw SQL: SELECT "parent"."parent_id", "parent"."parent_data", SUM("child"."child_data") FROM "parent" LEFT OUTER JOIN "child" ON ("parent"."parent_id" = "child"."child_id" AND "parent"."important") GROUP BY "parent"."parent_id" -
How can I change the SQL database driver in Django from mysqlclient to PyMySQL?
For working with SQL database Django required/recommends mysqlclient. However I'd like to use PyMySQL as SQL driver instead of mysqlclient. I'm using django-environ to load config into django. In my local development setup I'm using docker-compose/skaffold to run the docker containers. It should be sufficient to adjust the following things: .env file, change the DATABASE_URL to include the MariDB default port: DATABASE_URL=postgres://<USER>:<PASSWORD>@<SERVICE-NAME>:3306/<DATABASE-NAME> <project>/__ini__.py file, import/declare pymysql as MySQLdb by adding import pymysql pymysql.install_as_MySQLdb() But I get the excception c_database | 2021-03-09 11:09:20 0 [Note] mysqld: ready for connections. c_database | Version: '10.5.9-MariaDB-1:10.5.9+maria~focal' socket: '/run/mysqld/mysqld.sock' port: 3306 mariadb.org binary distribution c_django | Traceback (most recent call last): c_django | File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 614, in connect c_django | (self.host, self.port), self.connect_timeout, **kwargs c_django | File "/usr/local/lib/python3.7/socket.py", line 707, in create_connection c_django | for res in getaddrinfo(host, port, 0, SOCK_STREAM): c_django | File "/usr/local/lib/python3.7/socket.py", line 752, in getaddrinfo c_django | for res in _socket.getaddrinfo(host, port, family, type, proto, flags): c_django | socket.gaierror: [Errno -5] No address associated with hostname -
How to retrieve data from Django model choices? [closed]
this is my models.py class Schedule(models.Model): # They won't ever change and will give us dropdown in Admin site DAY = [(i+1, calendar.day_name[i]) for i in range(0, 7)] SUBJECT = ( ('eng', "English"), ('hin', "Hindi"), ('mat', "Mathematics"), ('sci', "Science"), ('mab', "Mental Ability"), ) day = models.IntegerField(choices=DAY) section = models.ForeignKey(Section, on_delete=models.CASCADE) subject = models.CharField(max_length=3, choices=SUBJECT) class Meta: unique_together = (('day', 'section'),) def __str__(self): return f'{self.get_day_display()} - {self.section.name}' i want to access subject from SUBJECT choice field and display it on frontend, Help me with logic for views.py -
Django 3 Rest Framework - Auth0
I am looking for a solution to adapt Auth0 into my Django 3.x + djangorestframework 3.12.2 djangorestframework-simplejwt backend stack. It is possible? In the Auth0 documentation which is most up-to-date tutorial, django ~2 is supported. I do not want downgrade my tech stack. Is there any possible solution? -
Static files - Microsoft Azure
I am currently hosting a django application on Microsoft Azure and wish to collectstatic files to my azure static blob container My settings.py is configured as follows - DEFAULT_FILE_STORAGE = 'storages.backends.azure_storage.AzureStorage' STATICFILES_STORAGE = 'storages.backends.azure_storage.AzureStorage' STATIC_LOCATION = "static" MEDIA_LOCATION = "media" AZURE_ACCOUNT_NAME = "container-name" AZURE_CUSTOM_DOMAIN = "https://container-name.blob.core.windows.net/" STATIC_URL = f'https://appname/container-name.blob.core.windows.net/static/' MEDIA_URL = f'https://zapitapp2/container-name.blob.core.windows.net/media/' I then have a custom_storage folder and custom_azure.py file within with values - from storages.backends.azure_storage import AzureStorage class AzureMediaStorage(AzureStorage): account_name = 'storage_account_name' account_key = 'storage_account_key' azure_container = 'media' expiration_secs = None class AzureStaticStorage(AzureStorage): account_name = 'storage_account_name' account_key = 'storage_account_key' azure_container = 'static' expiration_secs = None I am currently receiving error when I migrate - File "C:\Users\karlt\AppData\Local\Programs\Python\Python39\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: fe_sendauth: no password supplied And the following error when I attempt to collect static - File "C:\Users\karlt\AppData\Local\Programs\Python\Python39\lib\site-packages\azure\storage\common\_error.py", line 130, in _validate_not_none raise ValueError(_ERROR_VALUE_NONE.format(param_name)) ValueError: container_name should not be None. -
Django Python websocket API [closed]
I am trying to develop a Django websocket API. I want this websocket api to be kind of generic which i mean to be connected from different programing languages like java etc. Please help me out if this can be done. -
Django REST framework is powerfull?
is Django REST framework good for big amount of request can use the Django REST framework for big API projects? and Django will not decrease the speed of the API? I'm using Swagger with Django, and there is another options to create API like Fast API which is not Dependent on Django. so the question Django REST framework is power full enough or i should use some other options? -
How to add punctuation in django email message body
I am building an app that allows users to send emails to preferred email addresses. I am having trouble adding punctuation marks to the message body and getting a ValueError Invalid address; only 'Glo' could be parsed from "Glo; Flo." when I try to send the email. views.py def emailView(request): if request.method == 'POST': form = ContactForm(request.POST, request.FILES) if form.is_valid(): form.save() name = form.cleaned_data['name'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] tagline_one = form.cleaned_data['tagline_one'] tagline_two = form.cleaned_data['tagline_two'] recipient = form.cleaned_data['recipient'] msg = loader.render_to_string( 'email_portal/email.html', { 'name': name, 'subject': subject, 'message': message, 'tagline_one': tagline_one, 'tagline_two': tagline_two, } ) try: #message = str(text) recipient_list = [recipient, ] send_mail(subject, name, message, recipient_list, auth_user=None, auth_password=None, fail_silently=True, html_message=msg,) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('/') else: form = ContactForm(request.POST, request.FILES) return render(request, "email_portal/index.html", {'form': form}) I don't know how to go about this any help will be appreciated -
django - filtering via ManyToMany field
Let's say I have models like this: class Pizza(models.Model): name = models.CharField(max_length=100) class Topping(models.Model): name = models.CharField(max_length=100) class Flavor(models.Model): name = models.CharField(max_length=100) of_topping = models.ForeignKey(Topping, on_delete=models.CASCADE) on_pizzas = models.ManyToManyField(Pizza) Then, I have topping "Salami" with flavors "spicy", "non-spicy" and "italian", a topping "Fungus" with flavors "Champignon", "Boletus" and "Fly agaric". A pizza is constrained such that it cannot contain two toppings of the same Topping class but with different flavors. (e.g. there is no Pizza with both italian and spicy salami). Now, let's say my pizzaria offers those pizzas: Margherita (no toppings) Salami (non-spicy salami) Funghi (Champignon) Yummy (italian salami and Champignon) Toxic (spicy salami and fly agaric) Special (italian salami and Boletus) Now, for a customer Bob, I know is constraints, e.g. he would eat Champignon and italian salami (but would also eat anything that has only a subset of those as toppings). For Bob, I would no like to find out, that I could offer him Margherita, Funghi or Yummy. For each customer, the list of constraints will only include (at most) one flavor per topping. So there would be no customer who says that she likes both spicy and non-spicy salami. How do I write a filter … -
how to setup microsoft visual studio c++ for misaka in vs code
I have installed microsoft visual c++ compiler for installing misaka but do I have to include it somewhere int the path because it is still showing error in installing. ERROR: Command errored out with exit status 1: command: 'c:\users\akanksha sharma\desktop\project 2\be_a_socialstar\be_a_socialstar\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\akanksha sharma\\AppData\\Local\\Temp\\pip-install-c9tjt7_3\\misaka_25def6025d584d6f8ac1394be9c2f041\\setup.py'"'"'; __file__='"'"'C:\\Users\\akanksha sharma\\AppData\\Local\\Temp\\pip-install-c9tjt7_3\\misaka_25def6025d584d6f8ac1394be9c2f041\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\akanksha sharma\AppData\Local\Temp\pip-record-9ogyd3l2\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\akanksha sharma\desktop\project 2\be_a_socialstar\be_a_socialstar\include\site\python3.8\misaka' cwd: C:\Users\akanksha sharma\AppData\Local\Temp\pip-install-c9tjt7_3\misaka_25def6025d584d6f8ac1394be9c2f041\ Complete output (17 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.8 creating build\lib.win-amd64-3.8\misaka copying misaka\api.py -> build\lib.win-amd64-3.8\misaka copying misaka\callbacks.py -> build\lib.win-amd64-3.8\misaka copying misaka\constants.py -> build\lib.win-amd64-3.8\misaka copying misaka\utils.py -> build\lib.win-amd64-3.8\misaka copying misaka\__init__.py -> build\lib.win-amd64-3.8\misaka running build_ext generating cffi module 'build\\temp.win-amd64-3.8\\Release\\misaka._hoedown.c' creating build\temp.win-amd64-3.8 creating build\temp.win-amd64-3.8\Release building 'misaka._hoedown' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\akanksha sharma\desktop\project 2\be_a_socialstar\be_a_socialstar\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\akanksha sharma\\AppData\\Local\\Temp\\pip-install-c9tjt7_3\\misaka_25def6025d584d6f8ac1394be9c2f041\\setup.py'"'"'; __file__='"'"'C:\\Users\\akanksha sharma\\AppData\\Local\\Temp\\pip-install-c9tjt7_3\\misaka_25def6025d584d6f8ac1394be9c2f041\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\akanksha sharma\AppData\Local\Temp\pip-record-9ogyd3l2\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\akanksha sharma\desktop\project 2\be_a_socialstar\be_a_socialstar\include\site\python3.8\misaka' Check the logs for full command output. please help me figuring out the error. -
Django Admin cannot access file outside Admin
in my django project when in Admin i have to connect to a MQTT broker and pass path related to certs. My main projects structs is: |manage.py |... |backend |____init__.py |_mqtt_manager.py |mqtt_site |__init__.py |_certs-mqtt |_client |_ca.crt |_... Well, from Django Admin, if user update a model i use signals for call my `mqtt_manager.py function that try to connect to a MQTT server using path for Crt: mqtt_ca_crt = os.getenv('MQTT_CA_CRT') or '/mqtt_site/certs-mqtt/client/ca.crt' mqtt_cli_crt = os.getenv('MQTT_CLI_CRT') or '/mqtt_site/certs-mqtt/client/client.crt' mqtt_cli_key = os.getenv('MQTT_CLI_KEY') or '/mqtt_site/certs-mqtt/client/client.key' but when my signals trigger i get FileNotFoundError at /admin/mqtt_site/device/MSU152423/change/ How can i ask Django about file location whithout admin path? So many thanks in advance -
Obtaing Max Allowed Value of PositiveSmallIntegerField Django Field
I have the following PositiveSmallIntegerField attached to a Model as follows: class Proficiency(models.Model): class Meta: verbose_name = 'Proficiency' verbose_name_plural = 'Proficiencies' ... ... rating = models.PositiveSmallIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(10)]) I have to do some complex calculations (*which can't be done within the ORM as far as I can see) on an endpoint which returns an average value: The calculation turns out to be: candidate['average'] = (candidate['total'] / count) * maximum_value_of_proficiency_rating_field i.e., maximum_value_of_rating_field is 10. Inspection of this field, and some digging into object attributes etc has lead me to find 10 dynamically as the following: proficiency._meta.get_field('rating')._validators[1].limit_value However, I was wondering if there was a simpler way to find the maximum value of a PositiveSmallIntegerField... i.e., either whatever value passed into the MaxValueValidator(10) i.e., "10" or if there is no MaxValueValidator, then 32767. I was thinking something like maybe a method would return this safely, or maybe an attribute on the field, i.e.,: proficiency.rating.get_maximum_value() or proficiency.rating.max_value Does anyone know if there is such a class method or attribute on the field to do this? -
Bootstrap dual list box POST Selected
I'm trying to post selected data from Bootstrap dual list (https://www.virtuosoft.eu/code/bootstrap-duallistbox/) do django. I'm using example code from https://codepen.io/jaredbell/pen/OejgMe. Problem occurs when i try to send selected items to view in django - i'm always getting one selected item instead of multiple selected items. Given example from https://codepen.io/jaredbell/pen/OejgMe showing selected items with js alert script works well but when I try to get selected items with django there is always one selected item instead of list of selected items. If you have any ideas i would be very appreciate. Regards django ( views.py ): if request.method=='POST': q=request.POST.get('duallistbox_demo1[]','') return HttpResponse(q) # always one item html: same code as https://codepen.io/jaredbell/pen/OejgMe -
Django - Why is the folder in html are not able to read?
I'm new to Django and just started to create an app and still learning. Right now, I'm actually in a part where I'm trying to call the HTML file. But I don't understand why if I put the line like this below. I get an error saying TemplateDoesNotExist:- views.py def index(request): return render(request, "hello/index.html") But if I put the line like this, it works like a charm:- views.py def index(request): return render(request, "index.html") but by the way, I create a new folder name templates under hello and another new folder hello under the templates and inside there is a file index.html was placed. The directory view:- lecture3/hello/templates/hellp/index.html Can anybody help me to understand why such an occurrence can happen? -
Is there any good tutorial for django leaflet which uses raster tiles? [closed]
I am creating a website using django leaflet. I want to create a world map and want to set colors of different regions according to my data by a region name. For this purpose, I am trying to use raster tiles, but I do not know how to do it. I am working on leaflet first time. I need some help. Thank you in advance.