Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In my django application I have a png image which is displayed well locally but when I deploy on heroku it is no longer displayed
In my django application I have a png image which is displayed well locally but when I deploy on heroku it is no longer displayed. All other images in my app display fine locally and on heroku. What could be the origins of this behavior? <img src="{% static 'assets/images/brand/logo_ozangue.png' %}" class="header-brand-img main-logo"> -
Is it possible to iterate over one query set but show the other in DRF?
We have a config object in our code and a simple table for config aliases (alias + config). I want to create a generic API using ModelSerializers for listing the following for each ALIAS: { "alias": "test", "config_param_1": 1, "config_param_2": True } How I imagined the serialiser to look like working with the standard ModelViewSet is like this: class DeviceConfigSerializer(serializers.ModelSerializer): class Meta: model = Alias fields = [f.name for f in Config._meta.get_fields() if f.name not in ['id', 'other_fields']] Then I would need to overwrite the method for getting the fields to take alias.conf fields. Trying a couple of ways (like below) I can't quite get it to work. def to_representation(self, instance): if isinstance(instance, Config): return super().to_representation(instance.conf) return super().to_representation(instance) TL;DR: I want the ListSerializer to iterate over the ALIAS model but really show the details for the CONFIG model plus the alias.id. -
Django.Programming Error: Table Name Does Not Exist - How to solve?
I deleted a model in Django which I created for testing purposed. Now when I try and run makemigrations and mirgrate I get the following error: django.db.utils.ProgrammingError: table "members_test" does not exist Is there a standard procedure I should be doing when deleting a model? I only deleteed the code out of my Models file and tried migrating after. I've only tried runing migrate and make migrations in addtion to scouring the web. -
Unittest sending binary protobuf file error
I'm trying to implement unit tests for my django rest framework project. I send protobuf files. My code is: def test_post_endpoint_new_version_existing_service(self): files_dir = os.path.join(settings.BASE_DIR, 'api/test_files') path = files_dir + '/test1_test2.bin' myfile = open(path,'rb') self.guest_client.post( '/config?content-disposition=%20attachment%3Bfilename%3D%22test1_test2.bin%22', data=myfile, content_type='application/octet-stream' ) And nothing happens. Where did I do wrong? -
Misuse of window function LAG() ocurred when i used sum() function
Stores are disabled with BLOCK_EVENTS events and enabled with UNBLOCK_EVENTS events. My requirement is the active range of the store. I have given the code I use below, but the problem that exists is that when I want to collect all the active_period's together, it gives an error. # models.py class PartnerEventHistory(models.Model): partner_object = models.ForeignKey(InternetShop, on_delete=models.CASCADE, related_name='events') event = models.CharField('رخداد', max_length=100, choices=EVENT_CH, null=True, blank=True) date = models.DateTimeField('تاریخ ایجاد', db_index=True, auto_now_add=True) query: PartnerEventHistory.objects.filter( event__in=PartnerEventHistory.BLOCK_EVENTS + PartnerEventHistory.UNBLOCK_EVENTS ).order_by('partner_object', 'date').annotate(prev_event=Window( expression=Lag('event'))).annotate(active_period=Case( When(Q(event__in=PartnerEventHistory.BLOCK_EVENTS) & Q(prev_event__in=PartnerEventHistory.UNBLOCK_EVENTS), then=(F('date') - Window(Lag('date'))) / (1000000 * 60 * 60 * 24)), default=Value(0), output_field=IntegerField())).order_by('partner_object').annotate( total=Window(expression=Sum('active_period'), order_by=F('partner_object').asc())).values( 'partner_object', 'cum_active_period') error: OperationalError: misuse of window function LAG() -
Unable to run migrations for a django web service with postgresql backend through docker
I am trying to grow on a bookstore project mentioned in the book titled Django for Professionals by Vincent As I try to grow on it my requirements.txt has grown to asgiref==3.5.2 Django==4.0.4 psycopg2-binary==2.9.3 sqlparse==0.4.2 django-crispy-forms==1.14.0 crispy-bootstrap5==0.6 django-allauth==0.50.0 with my Dockerfile as FROM python:3.8-slim-bullseye # set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # # Set working directory WORKDIR /code # # Installing python dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt and my docker-compose.yml as # Mentioning which format of dockerfile version: "3.9" # services or nicknamed the container services: # web service for the web web: # you should use the --build flag for every node package added build: . # Add additional commands for webpack to 'watch for changes and bundle it to production' command: python manage.py runserver 0.0.0.0:8000 volumes: - type: bind source: . target: /code ports: - "8000:8000" depends_on: - db environment: - "DJANGO_SECRET_KEY=django-insecure-m#x2vcrd_2un!9b4la%^)ou&hcib&nc9fvqn0s23z%i1e5))6&" - "DJANGO_DEBUG=True" # postgreSQL database server being constructed alongside db: image: postgres:13 # volumes: - postgres_data:/var/lib/postgresql/data/ # unsure of what this environment means. environment: - "POSTGRES_HOST_AUTH_METHOD=trust" # Volumes set up volumes: postgres_data: I have been unable to run migrations or create a super user. The primary … -
How to configure Cheetah on Django
Is there a tutorial on how to configure Django and cheetah to print out simple text like hello world in variables or lists? I'm trying to configure cheetah with Django or find instructions on how to or tutorials but without luck. I've already tried the cheetah docs Django module but it's much more going on Plz little help -
cannot connect Django to postgres
I am trying to connect my django app to postgres but it gives the following error. connection to server at "127.0.0.1", port 5432 failed: FATAL: database "testDB" does not exist the postgres server is running I have checked it also restarted the server still I get the same error my database settings. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'testDB', 'USER': 'postgres', 'PASSWORD': 'xxxxx', 'HOST': '127.0.0.1', 'PORT': '5432', } } I tried to check if the server is running and it is running, also restarted the server but still the same error. -
How do I display the django-quill-editor toolbar?
In my app I need to create, edit, and send html emails. I have installed the django-quill-editor package and was successful in displaying my html content inside the quill editor - but only in admin. In my campaign app, I can display the html, but not the toolbar for editing. In my settings.py file I added the 'django_quill' app. In campaign/models.py I have a QuillField called 'content': class CampaignStep(models.Model): id = models.IntegerField(primary_key=True) campaign = models.ForeignKey( Campaign, on_delete=models.DO_NOTHING, blank=False, null=False, related_name='campaigns',) subject = models.CharField(max_length=64, blank=False, null=False) content = QuillField() campaign/views.py: class CampaignStepContentUpdateView(UpdateView): model = CampaignStep context_object_name = 'csd' fields = ['content'] template_name = 'campaign/campaign_step_content_update.html' campaign/forms.py class ContentForm(ModelForm): class Meta: model = CampaignStep fields = ['content'] And here is the template: {% extends "base.html" %} <head> <!-- django-quill-editor Media --> {% include 'django_quill/media.html' %} </head> {% block content %} <!-- 'csd' abbreviates 'campaign step detail'. --> <h2>{{ csd.campaign }} - Step {{ csd }}</h2> <body> <p></p> <h3>Content</h3> <div class="card"> <div class="card-body"> <form action="" method="POST">{% csrf_token %} {{ csd.content }} </form> </div> </div> <p></p> <button type="submit" class="btn btn-primary btn-block mt-1">Save Changes</button> </body> {% endblock content %} The page then displays only this: <django_quill.fields.FieldQuill object at 0x104e134c0> How do I get the quill editor … -
How to send an email that doesn't need triggering a specific url?
I'm trying to build an automated email system for ecommerce purposes, So, I wanna send an email if a user is not registered, with the tracking_no whenever we have assigned a tracking_no for an OrderItem, I don't understand how I would be able to put this in a view function because it'll never get triggered if no one tries to access the url connected to the view, would I need to access the admin panel url for OrderItem save function? So that whenever the admin assigns a tracking number and saves the form, a function checks up if there's an assigned number and sends out the email to the Customer. If so how would I solve this? #Model #Customer is someone who is not registered class Customer(models.Model): email = models.EmailField(max_length=100) class Order(models.Model): customer = models.ForeignKey(Customer) class OrderItem(models.Model): order = models.ForeignKey(Order) tracking_no = models.CharField(max_length=300, null=True, blank=True) #Email subject = "tracking_no" html_message = render_to_string('emails/tracking_no.html', {'tracking_no': tracking_no}) send_mail() -
ImportError: libssl.so.1.0.0: cannot open shared object file: No such file or directory
When running a project via pipenv, I get the following stacktrace. As I typically do not work with pipenv and cookiecutter projects, I have been struggling to fix it. Any help is appreciated. In case it matters, it is this project that I am trying to build and launch. ➜ project-shop git:(master) ✗ pipenv run ./manage.py runserver [2022-11-04 13:08:19,329 autoreload] INFO: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/home/user/miniconda3/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/home/user/miniconda3/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/home/user/.local/share/virtualenvs/project-shop-d1PiLiCc/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/user/.local/share/virtualenvs/project-shop-d1PiLiCc/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/user/.local/share/virtualenvs/project-shop-d1PiLiCc/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/user/.local/share/virtualenvs/project-shop-d1PiLiCc/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/user/.local/share/virtualenvs/project-shop-d1PiLiCc/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/user/.local/share/virtualenvs/project-shop-d1PiLiCc/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/user/.local/share/virtualenvs/project-shop-d1PiLiCc/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/user/.local/share/virtualenvs/project-shop-d1PiLiCc/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/user/miniconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File … -
Pop values from a queue created on another view Django
I have two views: one that create a queue and add elements inside it and another that is called with an AJAX call, when a button is clicked, from the frontend. Now I would like to consume the things inside the queue on the view called by AJAX. The issue is that, obviusly, this view doesn't know the queue. So, my question is, is that a way to pass the queue on this view or is there another way too pass informations between different view in Django? -
Django Jazzmin custom templates error on Heroku
i have a trouble with submit_line.html on Heroku, when i deployed, my additional button does not display, some code from my project. When i run local with heroku (without debug) settings - all go good In app/module folder: templates/admin/module_name/model_name/ submit_line.html {% extends "admin/submit_line.html" %} {% load jazzmin %} {% get_jazzmin_ui_tweaks as jazzmin_ui %} {% block extra-actions %} <div class="form-group"> <a href="https://www.djangoproject.com/" class="btn {{ jazzmin_ui.button_classes.warning }} form-control" target="_blank">Go Django</a> </div> {# Process with form submission #} <div class="form-group"> <input type="submit" class="btn {{ jazzmin_ui.button_classes.primary }} form-control" value="Send message to chats" name="send"> </div> {% endblock %} In settings.py INSTALLED_APPS = [ 'jazzmin', ... ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', .... ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' WHITENOISE_USE_FINDERS = True # Must be True, without this setting - don't work STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, "static") JAZZMIN_SETTINGS = { "site_title": "Club", "site_header": "Club", "site_brand": "Club", "welcome_sign": "Welcome to Club", "copyright": "Hihi", "hide_models": ["auth.group"], # "show_ui_builder": True, # "site_logo": "/images/logo.png" "order_with_respect_to": ["channel"], "icons": { ".channel": "fas fa-comments", ".groups": "fas fa-users", ".message": "fas fa-comment-dots", ".botcommand": "fas fa-terminal", ".quiz": "fas fa-poll-h", "auth.user": "fas fa-user-circle", }, } … -
How to save files from Incoming email using imap_tools into AWS S3 bucket
I have an email server hosted on AWS EC2. I am using imap_tools for retrieving email content. when I tried to get the file through the payload, I get this return; att.payload # bytes: b'\xff\xd8\xff\xe0\' Please how do I get the actual file path from the payload or bytes to be saved on AWS S3 and be able to read it from my table? I can attach a file to my mail and save it on S3 but getting the attached file coming to a mail address is my challenge. This is a function for reading email contents with imap_tools def imap_inbox(self): unread_inbox = [] for msg in self.mailbox.fetch(): attachments = [] for att in msg.attachments: attachments += [{ "filename": att.filename, "content_type": att.content_type, "file": att.payload, }] msg_dict = { "subject": msg.subject.replace("***UNCHECKED*** ", ""), "from_mail": msg.from_, "to_mail": msg.to[0], "message": msg.text, "attachments": attachments, } if 'RECENT' in msg.flags: unread_inbox += [msg_dict] return { "unread_inbox": unread_inbox, } This is my function for mail_server_inbox def mail_server_inbox(self, request, *args, **kwargs): # imap authentication ad_imap = self.authenticate_imap() inbox = ad_imap.imap_inbox() unread_inbox = inbox.get("unread_inbox") for msg in unread_inbox: mail_instance = None file_name = None try: attachments = msg.pop("attachments", []) msg = { **msg, } attachments = list( … -
how to run a python script in cpanel command while using a subdomain
Hi I am having an issue related to running a python script.I just uploaded my django project on cpanel and want a python script to auto run itself but as I am newbee to cpanel I don't know how to provide path in the cron job command section. Here is what I am writing in the command section of cron jobs in cpanel /usr/bin/python subdomainName/folderName/folderName/folderName/folderName/fileName.py But it is not working -
DRF - How to redirect a user after already sending a response
I'm facing the following problem: I'm building a third-party integration into my Django app. Users that already use the third-party should be able to click on a button and be redirected to my app. In the redirect, the third-party will send a POST request with a JSON that contains some info (email, some IDs etc.). I'll use this info to see if I have the user in my DB already. If yes, I want to: return a response with a user ID and API Key for the third party to store then redirect the user to a login screen If no, I want to: create a user and return a response with a user ID and API Key for the third party to store then redirect the user to a confirmation screen. The question I have: How can I redirect the user AFTER returning the user ID & API key? My current logic is this: class UserList(APIView): .... def post(self, request): if account_exists: return Response(account_data) # NOW I WANT TO REDIRECT else: create_account() return Response(account_data) # NOW I WANT TO REDIRECT I'm currently using DRF to handle the POST requests, not sure whether that is the best way of doing … -
How to allow users to change their email address?
I would like sociallogins to have the ability to specify a local password (if they want to/not required), and local accounts to be able to change their email address. What is the best approach for this? -
Does anyone know if it's possible to put your Django Heroku apps onto App Store/Google Play?
I have several apps that i've written in Django and host on Heroku. The website address works great but if people want to use my app on their mobile device i have to instruct them to visit the website then click Add to Home Screen so an app icon appears on their phone. Is there a better way of doing this so they can just add the app from say the App Store/Google Play? Thanks in advance. -
ImportError: cannot import name 'TagHelperNode' from 'django.template.base'
I'm facing the error of cannot import name 'TagHelperNode' from 'django.template.base' while im trying to migrate to django 3.2 I know that the problem will be solved if I downgrad django but I can't do that -
Docker-compose environment variable is not set
Project tree /backend .env.dev docker-compose-dev.yml /project I have the following warning: docker-compose -f docker-compose-dev.yml up --build # i am in the /backend directory WARNING: The DB_USER variable is not set. Defaulting to a blank string. WARNING: The DB_PASSWORD variable is not set. Defaulting to a blank string. WARNING: The DB_NAME variable is not set. Defaulting to a blank string. It means that docker compose don't see my environment file. How can I fix it? docker-compose-dev.yml 1 version: '3.3' 2 3 services: 4 django: 5 build: ./project # path to Dockerfile 6 env_file: 7 - ./.env.dev 8 command: sh -c " 9 sleep 3 && gunicorn -w 8 --bind 0.0.0.0:8800 core_app.wsgi" 10 volumes: 11 - ./project:/project 12 - ./project/static:/project/static 13 - ./project/media:/project/media 14 - ./project/logs:/project/logs 15 expose: 16 - 8800 17 depends_on: 18 - db ....... How can I enable env file? -
How to get user of one microservice to another microservice and authenticated using DRF
I am trying to seprate the monolithic DRF project to microservices, i am using postgres database and planning to user rabbitmq as a message broker if requried. Hello everyone, I am trying to seprate monolithic DRF project into microservices, I am planing to make two microservices. one is user_auth project and another is post project. as i mentioned above i have already created project in monolithic approch and i seprate the user_auth project part while seprating the the post project, i have a problem with geting user details in post project from the user_auth project, for exmaple i want to make a post from the specific user who is login into the user_auth project but i am not able to get the user and its login status. can anyone over there help me to seprate those project into micro services also want to menthion that i do have a seprate database for two project which is postgres and i was planning to use rabbitmq as a message broker if needed. Thanks in Advance -
How Can I remove :8000 from the URL when I publish my Django project on Linode?
I have a project that has been developed using Django and is published to Linode cloud Hosting. By default each Django project is being run on localhost:8000 and for this reason now I can access my project using IP_Address:8000 or mydomain.com:8000. I want to access the project without mentioning the port number (:8000). I have added my IP address and domain name inside settings.py like below: ALLOWED_HOSTS = ['mydomain.com', '176.xx.xxx.xxx'] But I still need to specify the port number how can I solve this problem. By the way I used Linode's default python installation for the start point of my project then I changed some files and of course added new files and so on. How can I solve this problem? -
Use function for value input in html with ajax, jquery
I have an ajax function which is actually working good but I don't know how to use it on the html. What I need to achieve is that basically, attached to each checkbox there is a certain number of questions. They're all selected by default but, if I deselect one of them, the number of questions of that particular checkbox should be removed. The function I am using is working fine (in the console) but I couldn't find a way to use it on the HTML. I post some code for more clarity. let subjectId; $("#selection").on("change", function () { const selectSubjBtn = document.getElementById("select_subject"); subjectId = $(this).children(":selected").val(); let labelText = gettext( "Select the number of questions by moving the button to the right or left!" ); let title = gettext("Select Number of Questions"); let selectedQuestionsNum; $.ajax({ type: "GET", url: "/quiz/ajax_questions/" + subjectId, success: function (response) { let questions = response.questions; let topics = response.topics; let topicQuestionNum = response.question_num_list; if (topicQuestionNum != 0) { let topicsObj = topics.map(function (e, i) { return [e, topicQuestionNum[i]]; }); let subTopicHtml; // $("#sub_topic_box").append( // '<input class="form-check-input mt-0 ms-3" type="checkbox" value="" id="selectAll" checked aria-label="Checkbox for following text input">' // ); topicsObj.forEach((el) => { subTopicHtml = '<div class="row … -
Retrieve an Object using Multiple Parameters inside of an Url in Django-Rest-Framework
How to retrieve an object using multiple parameters in url? Example : 'customer/3/order/1/' or 'customer/<int:customer_pk>/order/<int:pk>/' Using shell i'm able to get the object like this but i can't seem to do it from the views. >>> from temp.models import Customer, Order >>> from temp.serializers import CustomerSerializer, OrderSerializer >>> q = Order.objects.filter(customer=1).get(order_number=2) >>> q.order_name 'fruit' views.py from rest_framework import generics, status from rest_framework.views import APIView from rest_framework.response import Response from django.shortcuts import get_object_or_404 from .models import * from .serializers import * class CustomerListView(generics.ListCreateAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer class CustomerDetailView(generics.RetrieveDestroyAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer class OrderListView(generics.ListCreateAPIView): def get_queryset(self): queryset = Order.objects.filter(customer_id=self.kwargs["pk"]) return queryset serializer_class = OrderSerializer class OrderDetailView(generics.RetrieveDestroyAPIView): serializer_class = OrderSerializer def get_queryset(self): queryset = Order.objects.filter(customer_id=self.kwargs["customer_pk"]).get(order_number=self.kwargs["pk"]) return queryset urls.py from django.urls import path from .views import * urlpatterns = [ path('', CustomerListView.as_view()), path('<int:pk>/', CustomerDetailView.as_view()), path('<int:pk>/orders/', OrderListView.as_view()), path('<int:customer_pk>/orders/<int:pk>/', OrderDetailView.as_view()), ] -
Monitoring more than one instance with Django Channels Websockets
I'm trying to make a monitoring app with Django and the Django-Channels websockets library. The idea is that, two players are playing a Tic-Tac-Toe game on my site. The third person as the admin is capable of monitoring whats going on on the board in real time. This means that the admin has in front of him the same board as the players and what players are playing. The question is, am I capable of monitoring two instances at the same time when two players are playing another game like Bingo? In this case the players have two other instances of the board, so could I replicate in real time two different boards on one page for the admin? Are there any articles, videos, tutorials to which I can refer to? Even for the monitoring part as a third person that can track a game of Tic-Tac-Toe. I'm trying to make this in Django for the backend and JavaScript/React for the frontend. Only help that I can find with websockets in Django are chat apps or some games like Tic-Tac-Toe but I would like to go a step further and add a third person that could monitor whats going on.