Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: download created zip from function. Zipfile returns empty/not an zip-archive file
I am trying to give the user a "Save as" option when the user clicks the download button in my Django app. When the user clicks the button it kicks-off the following function. The function gets some CSVs from a blob container in Azure and adds them to a zip. That zip should then be offered to download and store in a location of the user's choice. def create_downloadable_zip(): container_client = az.container_client(container_name=blob_generator.container_name) blobs = container_client.list_blobs() zip_file = zipfile.ZipFile(f'{models.AppRun.client_name}.zip', 'w') for blob in blobs: if blob.name.endswith(".csv"): downloaded_blob = container_client.download_blob(blob) blob_data = downloaded_blob.readall() zip_file.writestr(blob.name, blob_data) zip_file.close() return zip_file My views.py looks like follow: def download_file(request): if request.method == 'POST': zip = create_downloadable_zip() response = HttpResponse(zip, content_type='application/zip') response['Content-Disposition'] = 'attachement;' f'filename={zip}.zip' return response # # else: # # return a 404 response if this is a POST request # return HttpResponse(status=404) return render(request, "download_file.html") The functionality works, but it returns an empty non-zip file when the "Save as" window pop-ups. However, the actual zip file contains the files is being saved in the root folder of the Django project. I really don't get why I doesn't return the zip file from memory, but rather directly stores that zip file in root and returns … -
How do I update Django database from field choices?
I'm developing a CRM using django and for my lead details I am trying to display my choices in the html form but also have it update the database when a new choice is selected and saved. Currently, I am able to display the choice that was selected upon lead creation, but I don't know how to allow the agent to change the choice and have that new choice update the database. I am still in the process of learning Django so theres still a lot i'm learning as i go. views.py class LeadDetailView(LoginRequiredMixin, DetailView): template_name = "lead-details.html" queryset = Lead.objects.all() context_object_name = "leads" models.py class Lead(models.Model): PROBLEM_LEAD = 'Problem Lead' PAY_TOO_FAR = 'Payments Too Far' PAY_TOO_SMALL = 'Payments Too Small' NPI = 'No Payment Information' ACTIVE = 'Active Deal' NO_DEAL = 'No Deal' choices_lead_status = [ (PROBLEM_LEAD, 'Problem Lead'), (PAY_TOO_FAR,'Payments Too Far'), (PAY_TOO_SMALL,'Payments Too Small'), (NPI,'No Payment Information'), (ACTIVE,'Active Deal'), (NO_DEAL,'No Deal') ] choices_lead_owner = [ ("Settlement, New",'Settlement, New'), ("Lead, Sales",'Lead, Sales'), ] lead_status = models.CharField(max_length=100, choices=choices_lead_status, blank=True) lead_owner = models.CharField(max_length=100, choices=choices_lead_owner, blank=True) agent = models.ForeignKey(Agent, null=True, on_delete=models.SET_NULL, blank=True) def __str__(self): return f"{self.first_name} {self.last_name}" html # this displays the lead_owner but i also need it to iterate through the … -
bootstrap table and a form (inline formset factory) associated with each row in that table
I have a bootstrap table and a form (inline-formset-factory) associated with each row in that table. That form should appear and disappear below the corresponding row when a button is clicked in that row. i tried Bootstrap collapse option but while clicking the button(form submit) in the row to induce the inline formset factory form with specified parent model, the form opens in all the rows. But i wanted the from to appear in that corresponding row only. -
Pythonic to way fix circular imports in Django (with task management framework)
I have a pattern that comes up fairly often in a Django app with some task management lib (say celery or dramatiq) that looks as follows: my_app/ executors/ my_executor.py tasks/ my_task.py and the executor may schedule the task # my_executor.py import my_app.tasks.my_task class MyExecutor(): def some_method(self): my_app.tasks.my_task.some_actual_task.send() # my_task.py import my_app.executors.my_executor @decorating_as_task def some_actual_task(): executor = my_app.executors.my_executor.MyExecutor() executor.execute() There is no issue actually running the app (or tests), but pylint complains about a R0401: Cyclic import between the modules. But it is not clear to me whether this type of dependency is acceptable or not (Python does not seem to be complaining) and whether there are way of actually improving the code structure (having a higher level module my_app.task_management importing both executors and tasks?) while pleasing pylint on this. I have seen many similar questions but could not find a satisfactory solution from them. -
Django Celery. How to make tasks execute at the appropriate different times given in variables
I try to make a task that will be done at a certain time. Example: A customer borrowed a book on 01/01/2023 15:00 so the tasks will do exactly one week from now if he doesn't return it and charge a fee. How to make it do at certain different times. I'm trying to use django celery with rabbitmq, but I'm not succeeding in making this task open at different times only schematically e.g. every 60 minutes -
(mysql.connector.errors.DatabaseError) 2005 (HY000): Unknown MySQL server host 'db' (8) (Background on this error at: https://sqlalche.me/e/20/4xp6)
I'm developing a project with Django and I want to use a database to create a dataframe, but I'm stuck with the subject issue (mysql.connector.errors.DatabaseError) 2005 (HY000): Unknown MySQL server host 'db' (8). (Background on this error at: https://sqlalche.me/e/20/4xp6) How should I fix it? views.py from sqlalchemy import create_engine, text def user_detail(req, id): engine = create_engine("mysql+mysqlconnector://user:mariadb@db:9051/mariadb") query = "SELECT * FROM LoanParcel" df = pd.read_sql_query(sql=text(query), con=engine.connect()) df = df.drop(["id", "date_add", "start_date", "description"], axis = 1) return render(req,'pages/user_detail.html') docker-compose.yml version: '3.7' services: db: image: mariadb:10 command: --default-authentication-plugin=mysql_native_password restart: always environment: - MYSQL_ROOT_PASSWORD=mariadb - MYSQL_DATABASE=mariadb - MYSQL_USER=mariadb - MYSQL_PASSWORD=mariadb - MARIADB_ROOT_PASSWORD=mysecretpassword ports: - 9051:3306 volumes: - "mysqldata:/var/lib/mysql" web: build: . restart: always command: python manage.py runserver 0.0.0.0:8000 environment: - DATABASE_URL=mysql+mysqlconnector://user:mariadb@db:9051/mariadb ports: - "9052:8000" depends_on: - db volumes: mysqldata: docker-compose ps command NAME COMMAND SERVICE STATUS PORTS myproject-uborrowu-db-1 "docker-entrypoint.s…" db running 0.0.0.0:3306->3306/tcp myproject-uborrowu-web-1 "python manage.py ru…" web running 0.0.0.0:8000->8000/tcp -
Differences between get_media_prefix and media_url
What is the difference between them? MEDIA_URL = 'media/' <a href="{{MEDIA_URL}}uploads2/711397.png">link</a> <a href="{% get_media_prefix %}uploads2/711397.png">link</a> They seem to work exactly the same, they create the same link. -
How to set Time zone to TIME_ZONE = "Asia/Karachi" in Django Project?
I want to change the timezone of my django project to Asia/Karachi. I have added this in my settings.py file: TIME_ZONE = "Asia/Karachi" Time zone of my postgres is also set to Asia/Karachi. But still when I create the objects, the time zone of DateTimeField is set to UTC. class MyClass(models.Model): name = models.CharField(max_length=64) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.name Now when I create the object of MyClass, created_at and updated_at are storing Time with UTC timezone. Why is this so and how can I fix it? -
Counting letter "r" in Django queryset
I need to count all "r"s in field 'wertung' in a queryset. "right = protokoll.filter(wertung__contains ='r').count()" - counts the fields containing a "r" - no matter if there is one "r" or two "rr", but now I need to count all "r"s. -
Unable to get local issuer certificate (_ssl.c:997)
Environmernt: Digital Ocean Droplet - Ubuntu 20.04.2 LTS. Certbot - manage certificated on NGINX Python:3.10 running in docker container Nature of error: On making any request whether I get the SSL: CERTIFICATE_VERIFY_FAILED. But in a case where my request fails I get a proper 400 error message from the server. Error: (In this case I'm trying to register) Internal Server Error: /auth/register/ Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 54, in inner response = get_response(request) File "/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.10/contextlib.py", line 79, in inner return func(*args, **kwds) File "/usr/local/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 55, in wrapper_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/app/apps/core/views.py", line 45, in post data = UserService.register_user(email=email, serializer=serializer) File "/app/apps/core/services/registration.py", line 13, in register_user MailerClass.send_email(data) File "/app/apps/core/utils.py", line 20, in send_email email.send() File "/usr/local/lib/python3.10/site-packages/django/core/mail/message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/local/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line 125, in send_messages new_conn_created = self.open() File "/usr/local/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line 90, in open self.connection.starttls(context=self.ssl_context) File "/usr/local/lib/python3.10/smtplib.py", … -
How can I authenticate web socket connection in postman?
This is my ASGI file: from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import os import app.routing from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") application = get_asgi_application() application = ProtocolTypeRouter({ 'http': get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( app.routing.websocket_urlpatterns ) ), }) This is my routing.py file: from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/sc/', consumers.MySyncConsumer.as_asgi()), path('ws/ac/', consumers.MyASyncConsumer.as_asgi()), path('ws/test/', consumers.TestConsumer.as_asgi()), path('ws/scg/', consumers.MySyncGroupConsumer.as_asgi()), ] This is my consumer file: class MySyncConsumer(SyncConsumer): def websocket_connect(self,event): print("Web socket connected", event) self.send({ 'type':'websocket.accept' }) print("Channel layer ",self.channel_layer) print("Channel name", self.channel_name) async_to_sync(self.channel_layer.group_add)("test_consumer_group_1", self.channel_name) def websocket_receive(self,event): print("Web socket recieved",event) print(event["text"]) async_to_sync(self.channel_layer.group_send)("test_consumer_group_1", { 'type':'chat.message', 'message':event['text'] }) #event handler, whuch is sending data to client def chat_message(self,event): print('Event...', event) print('Event...', event["message"]) self.send({ "type":"websocket.send", "text":event['message'] }) def send_notification(self, event): print("send_notification called") print('Event...', event['value']) self.send({ "type":"websocket.send", "text":event['value'] }) def websocket_disconnect(self,event): print("Web socket disconnect", event) async_to_sync(self.channel_layer.group_discard)("test_consumer_group_1", self.channel_name) raise StopConsumer() How can I authenticate web socket connection in postman? I want to authenticate web socket connection so that self.scope["user"] returns currently logged in user in consumers.py. Otherwise it returns an anonymous user. -
HTML select options do not get populated with getElementById and innerHTML
I am currently working on a reservation function for a fictional restaurant as part of an assignment in Django. On the reservation page, the user should type in his name, select a date and a free reservation_slot between 10am and 8pm. Effective values for the reservation_slot that will be stored in the MySQL database via the Booking model and Form are [10-20] and will get transformed with the formatTime function in 'book.html'. reservation_slot that are already picked on that specific date should be disabled in the selection drop down. This is handled when the selection options are built. The name- and date field work fine, but the dropdown for reservation_slot is not getting populated. I even tried to hardcode one option and inserted it with .innerHTML, also did not work. The same problem applies for "reservations for <current selected date>" in a second column, it should display all reservations for the selected date and is getting populted with .innerHTML as well. There is one case, where the population with .innerHTML actually worked; the date in "reservations for <current selected date>". following is the book.html: {% extends 'base.html' %} {% load static %} {% block content %} <section> <article> <h1>Make a … -
How to count the number of elements of each category in Django?
I have a list of elements. There is a 'status' value here. I need a code that in an HTML page will show the total number of items for each 'status'. How to do it? For intance, there is the list in the page: appnumber status №54534534 accepted %46342322 in process %55745232 accepted %67456452 denied %76454534 accepted %52864525 denied %86752525 accepted The result should be: accepted - 4 denied - 2 in process - 1 My code: home.html <div class="headtext"> <form method="GET" action="{% url 'search' %}"> <input type="search" type="text" name="q" prequired placeholder="Put appnumber"> <button type="submit">Find</button> </form> </div> <div> {% for application in object_list %} <div> <p>Application: {{ application.appnumber }}, status: {{ application.status }}</p> </div> {% endfor %} </div> views.py class HomeView(ListView): model = Application template_name = 'home.html' class Search(ListView): template_name = 'home.html' def get_queryset(self): return Application.objects.filter(appnumber__icontains=self.request.GET.get("q")) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["q"] = self.request.GET.get("q") return context -
i am facing issue to add path to product urls file then this path will direct to core's url .py i am using router for viewset in views .py
i am creating CRUD for categories by using https request against the user when using postman. i register router as default in urls.py(Products) for viewset of categories and we have to include path into the core url.py file. i am facing isues i am creating CRUD for categories by using https request against the user when using postman. i register router as default in urls.py(Products) for viewset of categories and we have to include path into the core url.py file. i am facing isues. Product => urls.py -
How can code be activated on click of a button in a Django view?
I have a template that contains a button. I have a view for this template in a view file. How can a part of the code be activated when this button is clicked - which is in the template? How can you make this as easy as possible? How can code be activated on click of a button in a Django view? def click_button_summ(request): context = {} if request.POST.get("button_table_summ") == "button_table_summ": ///code/// return render(request, "click_button_summ.html", context) <div class="ui container"> <div class="column"> <button type="submit" class="ui button" name="button_table_summ" value="button_table_summ">Button</button> </div> </div>` -
How to install fonts in a docker, which runs on a raspberry pi/linux?
I am currently using a docker to run a litte django programm with GUI on a raspberry pi. And I wanna change the fonts in the GUI by changing the setting in a .css file. Should i install a wished fonts in the docker first? If yes, how should i do this? Any suggestions and anwsers are fully welcomed :) -
After deploying project on a VPS, the django app works fast on port 8000 as the local server, but when checking on port 80 some templates do not load
After deploying django project on a VPS, the django app works fast on port 8000 when running on the local server using python manage.py runserver 0.0.0.0.8000 , but when checking the url on port 80 some templates do not load why! VPS hostinger Openlightspeed Cpu 2 cores Some html Templates do not load quickly on django production phase. -
Wich workflow engine do you recommend for an Angular Business SaaS?
Im looking for a good workflow engine built to work together whit Angular in Frontend, the Backend i would code whit Django/Python. Any Suggestions? I found this on Google: https://github.com/topics/workflow-engine?l=typescript https://github.com/optimajet/workflow-designer-angular-sample https://github.com/ti-ka/ng-workflow -
Split radio buttons in several groups with crispy-forms
I would like to create a django form to plan a meeting. I have to propose several timeslots, and regroup them by day, like in the following image. Is it possible to do that with crispy-forms, by using the same ChoiceField for all the radio buttons ? -
Not getting value of other attributes using select_related in django
I am trying to fetch the values from TypingTest model. The foreign key is referencing to the UserProfile model. While fetching the data I want the username to be displayed in the result of the query as well. So, after researching a bit I found out that select_related could be a way of doing this. But when I am trying to use select_related. I am not able to see the username, Only the value of the primary key is getting shown. These are the two models that I have. class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) userName = models.CharField(max_length=26,unique=True) email = models.EmailField(max_length=254,unique=True) profilePhoto = models.ImageField(default="/default.png") rank = models.CharField(max_length=26,default="Novice") def __str__(self): return self.userName class TypingTest(models.Model): user = models.ForeignKey(UserProfile,on_delete=models.CASCADE) time = models.IntegerField() wpm = models.IntegerField() accuracy = models.IntegerField() raw = models.IntegerField() dateTaken = models.DateTimeField(auto_now_add=True) This is the view code that I have written. @protected_resource() @api_view(['GET']) def getAllTests (request): testListQuerySet = models.TypingTest.objects.all() selectRelated = models.TypingTest.objects.select_related('user').only("userName") print(selectRelated.values()) serializer=serializers.TypingTestSerializer(models.TypingTest.objects.select_related('user'),many=True) return Response(serializer.data) Please let me know if this is the right way of doing the thing intended and if not what is ?. Thanks. -
How to fix AttributeError 'OptionEngine' object has no attribute 'execute'
I'm currently working on a project where association rule is used, and I'd like it to retrieve data from a database to make a model for the introduction of lists, but I have a problem with the 'OptionEngine' object has no attribute 'execute', how should I fix it? views.py from sqlalchemy import create_engine def user_detail(req, id): engine = create_engine("mysql+mysqlconnector://user:mariadb@db:9051/mariadb") QLoanParcel = "SELECT * FROM LoanParcel" dfParcel = pd.read_sql(QLoanParcel, engine) df = dfParcel.drop(["id", "date_add", "start_date", "description", "reasonfromstaff", "status","type", "quantity", "statusParcel", "quantitytype", "nameposition"], axis = 1) df = df.drop_duplicates().reset_index(drop=True) df = df.pivot(index='parcel_item_id', columns='user_id', values='user_id') df = df.notnull().astype(int) docker-compose.yml version: '3.7' services: db: image: mariadb:10 command: --default-authentication-plugin=mysql_native_password restart: always environment: - MYSQL_ROOT_PASSWORD=mariadb - MYSQL_DATABASE=mariadb - MYSQL_USER=mariadb - MYSQL_PASSWORD=mariadb - MARIADB_ROOT_PASSWORD=mysecretpassword ports: - 9051:3306 volumes: - "mysqldata:/var/lib/mysql" web: build: . restart: always command: python manage.py runserver 0.0.0.0:8000 environment: - DATABASE_URL=mysql+mysqlconnector://user:mariadb@db:9051/mariadb ports: - "9052:8000" depends_on: - db volumes: mysqldata: I have successfully installed mysqlconnector. -
How to set up a maximum value in a Django DurationField?
I have a Django models with a DurationField. I would like that the users cannot put a value over 00:09:59. Unfortunately I could not find any information to do this in the doc : https://docs.djangoproject.com/en/4.1/ref/models/fields/#durationfield -
Apply if-else statement on a dictionary using django-templates
In a django - webapp I am classifying between two classes of images i.e. Ants and Bees I have returned the dictionary to the templates(index.html) context={ 'ant':("%.2f" % predictions[0]), 'bee': ("%.2f" % predictions[1]), } when applying this {% for key , value in pred.items %} <p>{{key}}: {{value}}%</p> {% endfor %} i got this which is pretty much what i wanted to display now i want to display the one with greater probability how do i do it ? I cannot access elements of the dictionary inside if else statement , though i tried doing this {% for key, value in pred.items %} {% if value.0 > value.1 %} <p>Result : {{value.0}}</p> {% elif value.0 < value.1 %} <p>Result: {{key}}</p> {% endif %} {% endfor %} -
How to order by user-defined serializer field when using Django REST Framework with Django REST Framework JSON API
I want to sort by user-defined serializer field, all fields that defined in Serializer class can be sorted except primary key of the model, so I must assign ordering_fields into Class-Based View to solve sort by primary key problem. views.py from rest_framework_json_api.views import viewsets from .serializers import ConjunctionSerializer from .models import Conjunction class ConjunctionViewSet(viewsets.ModelViewSet): queryset = Conjunction.objects.all() serializer_class = ConjunctionSerializer permission_classes = [permissions.AllowAny] ordering_fields = '__all__' def get_queryset(self): queryset = super().get_queryset() report_pk = self.kwargs.get('report_pk') if report_pk is not None: queryset = queryset.filter(report__pk=report_pk) return queryset serializers.py from .models import Conjunction from rest_framework_json_api import serializers, relations class ConjunctionSerializer(serializers.HyperlinkedModelSerializer): norad = serializers.IntegerField(source='satellite.norad_cat_id', read_only=True) name = serializers.CharField(source='satellite.satellite_name', read_only=True) primary_object = CoordinateSerializer(read_only=True) secondary_object = CoordinateSerializer(read_only=True) class Meta: model = Conjunction fields = '__all__' models.py class Conjunction(models.Model): class Meta: managed = False db_table = 'conjunction' ordering = ['tca'] conjunction_id = models.IntegerField(primary_key=True) tca = models.DateTimeField(max_length=3, null=True) missdt = models.FloatField(null=True) probability = models.FloatField(null=True) prob_method = models.CharField(max_length=45, null=True) satellite = models.OneToOneField(SatelliteCategory, to_field='norad_cat_id', db_column='norad', null=True, on_delete=models.DO_NOTHING) doy = models.FloatField(null=True) ephe_id = models.IntegerField(null=True) primary_object = models.OneToOneField(Coordinate, db_column='pri_obj', related_name='primary_object', null=True, on_delete=models.DO_NOTHING) secondary_object = models.OneToOneField(Coordinate, db_column='sec_obj', related_name='secondary_object', null=True, on_delete=models.DO_NOTHING) report = models.ForeignKey(Report, related_name='conjunctions', related_query_name='conjunction', null=True, on_delete=models.DO_NOTHING) probability_foster = models.FloatField(null=True) probability_patera = models.FloatField(null=True) probability_alfano = models.FloatField(null=True) probability_chan = models.FloatField(null=True) This is the URL that … -
ModuleNotFoundError: No module named 'webpush'
I am using webpush in my Django application. Following the recommendation it works well locally. When I push the code to my host, it gives me this mistake ModuleNotFoundError: No module named 'webpush'. Application does not work. Error log: 2023-02-15 07:51:15,780: Error running WSGI application 2023-02-15 07:51:15,780: ModuleNotFoundError: No module named 'webpush' 2023-02-15 07:51:15,780: File "/var/www/www_……….._pl_wsgi.py", line 30, in 2023-02-15 07:51:15,781: application = get_wsgi_application() 2023-02-15 07:51:15,781: 2023-02-15 07:51:15,781: File "/home/……/.virtualenvs/venv/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2023-02-15 07:51:15,781: django.setup(set_prefix=False) 2023-02-15 07:51:15,781: 2023-02-15 07:51:15,782: File "/home/……/.virtualenvs/venv/lib/python3.10/site-packages/django/init.py", line 24, in setup 2023-02-15 07:51:15,782: apps.populate(settings.INSTALLED_APPS) 2023-02-15 07:51:15,782: 2023-02-15 07:51:15,782: File "/home/……./.virtualenvs/venv/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate 2023-02-15 07:51:15,782: app_config = AppConfig.create(entry) 2023-02-15 07:51:15,782: 2023-02-15 07:51:15,782: File "/home/…../.virtualenvs/venv/lib/python3.10/site-packages/django/apps/config.py", line 193, in create 2023-02-15 07:51:15,782: import_module(entry) 2023-02-15 07:51:15,783: I did « pip install Django-webpush » (no mistake), I executed « python manage.py migrate » (in line with instructions on host as well, no mistake at this point, migration is done successfully). I have the Error when I try to reload the application on host. Anyone can help?