Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
start gunicorn when docker-compose is not in same folder
I am attempting to build an environment, using Docker, Django, gunicorn, postgres and nginx. In this environment Dockerfile and docker-compose sits one level above src folder My idea of folder structure is as follows: "NN Project" folder within my "Documents/repositories" └── / config (to place nginx settings within) └── / deployment (to place environment "secrets" within) └── / src (the Django project) ├── Dockerfile ├── docker-compose ├── license, readme ... ├── build_script.sh The reason I want to put Dockerfile and docker-compose at top-level and not under the sub-folder /src is because I want the ability to access env "secrets" when working in a container with Django and its relative import NON_VERSION_PATH = Path(__file__).resolve().parent.parent.parent with open(NON_VERSION_PATH / 'deployment/etc/application/.env_vars', 'r') as f: secrets = json.loads(f.read()) Problem I have is that I cannot get web (the "src" container) to start (it cannot find it). However, it works fine if I place Dockerfile and docker-compose within the /src folder but I would like to have the docker-compose one level up. I understand it is about relative import, however, I cannot figure out how to tell it to look in ./code my docker-compose looks like: version: "3.9" services: db: container_name: db image: postgres:alpine restart: always … -
How we can secure our videos in Django for Lms that no one can download
I am creating an LMS and wanted to secure my video content but don't want to use any third party to host my video like Vimeo etc. How can we do this is in Django. Is this even possible? -
How to catch a Django "GET" event in template using jquery?
In my Django project, I have a pdf download button that generates a report. When I push the button I would like a modal showing that the report is being processed. When the pdf is downloaded, I would like the modal to hide automatically. However, I am having some trouble with the last part. I know that Django sends a "GET" message in the backend, when the report is downloaded ("GET /download/140/...") How can I "catch" the ("GET /download/140/...") event in my template? Code: <a href="{% url 'report-download' object.id %}" class="btn btn-grey" id="pdf-button"></a> Show "processing" modal when download is initiated... <script type="text/javascript"> $("#pdf-button").on("click", function(){ $('#myPDFModal').modal('show'); }); </script> Attempt: Close "processing" modal when download is finished using Ajax... <script type="text/javascript"> $(document).on('click', '#pdf-button', function(event) { event.preventDefault(); $.ajax({ url: '{% url 'report-download' object.id %}', type: 'GET', }).done(function(result) { $('#myPDFModal').modal('hide'); }); }); </script> The above code seems to work at showing/hiding the modal at the right "GET" event, but the pdf is not downloaded.. -
How to call celery task with class based method?
I have the class: class Parser: def __init__(self): self.OM = Omni() # Creates an class object, which makes auth on the web site, for scrapping @app.task def foo(self, data): self.OM.parse(data) So how can I call task with foo method? Because when I try to do like this, I takes error : Missing argument data. I think it is because calling the method get data as self parameter prs = Parser() prs.foo.delay(data) How I can to resolve it? -
how to fix django.db.utils.ProgrammingError:relation "some_object" does not exist?
How to fix django.db.utils.ProgrammingError: relation "some_object" does not exist? I saw lots of topic on this platform to related this error, but won't able to fix it in my case. In my case means, I am working on django and I have the postgresql database and It's working well but whenever I took pull request from git(where other person is working) and run the migration then I am getting this error. below is some links that I had tried https://stackoverflow.com/a/33055243/11360069 I just try but not working https://stackoverflow.com/a/46697898/11360069 ./manage.py migrate --fake default https://stackoverflow.com/a/29672770/11360069 python manage.py migrate --run-syncdb and python manage.py migrate --fake appname python manage.py migrate --fake, python manage.py migrate --fake--initial, python manage.py migrate Only one way is working for me when I had create a new database and applying migration. But I am not sure that what will happen if, if I'll update this code on server then it will show same error then we can't delete or change the exiting database. -
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.