Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
A celery task called twice modifies one object
I'm experimenting with celery to understand how it works. I've written a simple worker, which modifies an array: from .celery import app import time arr = [] status = 'waiting' @app.task def push_back(val): global arr if status == 'busy': return 'try later' status = 'busy' arr.append(val) time.sleep(5) status = 'waiting' return arr And here is my client: from proj.tasks import push_back from sys import argv res = push_back.delay(int(argv[1])) data = res.get() print(data) I call the client twice, one immediately after the other with different arguments. E.g. my call is: python3 update_object.py 3 & python3 update_object.py 5 The responses are [3] and [5], respectively. I have another task for checking the state of the array, which returns [3], so only the first call has made any effect. Could somebody explain what exactly is going on during such a call? Why is the status not checked? Why does the second call modify the array? My ultimate goal is to implement Django API and an AI server being a celery worker. Besides predictions, I also want to load different models (modify the state) using remote calls from Django. I want to disable the task execution if it has been called by another user. … -
Permission denied when trying to link pycharm to dockerized django venv
I'm trying to connect pycharm to the django dockerized venv but pycharm get an error about permission denied. "Error response from daemon: failed to create shim: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "/usr/src/qatrackplus/deploy/docker/user-data/.venv": permission denied: unknown" I already tried to chmod +777 the venv folder in case of rights problem but, pycharm still can't access it... -
Separate databases for development and production in Djang
I am trying to split my django settings into production and development. Th ebiggest question that I have is how to use two different databases for the two environments? How to deal with migrations? I tried changing the settings for the development server to use a new empty database, however, I can not apply the migrations to create the tables that I already have in the production database. All the guides on multiple databases focus on the aspect of having different types of data in different databases (such as users database, etc.) but not the way I am looking for. Could you offer some insights about what the best practices are and how to manage the two databases also in terms of migrations? Thank you! -
Created m2m fields values are assigned to all existing users
i am new in Django and try to create a user profile with many to many job fields. My models looks like: ``class Job(models.Model): CARRYING = 'carrying' CARRYING_FOR_MOVE_TOOLS = 'carrying_for_move_tools' CHOICES = [ (CARRYING, 'yyyyyyyyy'), (CARRYING_FOR_MOVE_TOOLS, 'xxxxxxxxxx'), ] job = models.CharField(max_length=1000, choices=CHOICES, primary_key=True, default=''unique=True) display_sort_key = models.FloatField(default=0.) def __str__(self): return self.get_job_display() def get_slug_prefix(self): return self.SLUG_PREFIX[self.job] class Userprofile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=70) jobs = models.ManyToManyField(Job, default='') def __str__(self): return self.email`` When i create Jobs in the admnin panel or send the jobs via the client interface (Angular) all created jobs are assigned to all existing users. How can i assign the created jobs only to the curent user. Please help! How can i assign the created jobs only to the curent user? -
how do i start the Django server directly from the Docker container folder
I have this project structure: └── folder └── my_project_folder ├── my_app │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── manage.py ├── .env.dev ├── docker-compose.yml ├── entrypoint.sh ├── requirements.txt └── Dockerfile docker-compose.yml: version: '3.9' services: web: build: . command: python my_app/manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app/ ports: - 8000:8000 env_file: - .env.dev depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=db_admin - POSTGRES_PASSWORD=db_pass - POSTGRES_DB=some_db volumes: postgres_data: Dockerfile: FROM python:3.10.0-alpine WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN apk update RUN apk add postgresql-dev gcc python3-dev musl-dev COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./entrypoint.sh . RUN sed -i 's/\r$//g' /usr/src/app/entrypoint.sh RUN chmod +x /usr/src/app/entrypoint.sh COPY . . ENTRYPOINT ["/usr/src/app/entrypoint.sh"] It's working, but i dont like the line python my_app/manage.py runserver 0.0.0.0:8000 in my docker-compose file. What should i change to run manage.py from the docker folder? I mean, how can i use python manage.py runserver 0.0.0.0:8000 (without my_app)? -
How to show other paths in the router root view of Django Rest Framework?
As per the example below, the second 'path' which uses 'customauth.urls' isn't visible in the Django Rest Framework's browsable API root view. I also want to add single API views to be shown in the API root view so people can see those views. But it doesn't seem possible. How to do it? ... router = routers.DefaultRouter() router.registry.extend(articleRouter.registry) urlpatterns = [ path('', include(router.urls)), path('custom-auth/', include('customauth.urls')), # THIS DOESN'T APPEAR IN THE API ROOT VIEW ] ... -
Django: import CSV but prevent existing duplicates
I have a simple Django/sqlite application that is importing a CSV with N rows of transactions. A Transaction has the following fields: date, description, amount. When I import these I want to ignore any that already exist. This can be easily accomplished with some constraints at the database level. However, I do want to allow duplicates within the same import. e.g., I make two transactions on the same day for the same thing. I'm trying to avoid looking up each transaction as I read the CSV... I suppose I could query all transactions between the first and last dates of the CSV and search this result set as I iterate through the new transactions. Hoping for a nicer solution. -
In a Django+React separated project, how can the frontend process dynamic path?
In case of a XY Problem, I will try to state my goal: I want to build an app using both Django and React. I don't want to make it a SPA since users tend to copy the URL and share it. Also SEO with SPA is painful. However if I use the pure static frontend + Django API approach, it can only process "static" URLs, such as example.com/obj instead of example.com/obj/1. -
local variable 'content' referenced before assignment django
I'm trying to do a view in which users can respond by commenting or replying to a chapter by answering a form but I keep getting the local variable 'content' referenced before assignment error and I don't know why. When I removed the content field the same happened to the parent field. class ChapterView(DetailView): model = Chapter template_name = 'mangas/chapter.html' slug_field = 'chapter_slug' slug_url_kwarg = 'chapter_slug' def get_context_data(self , **kwargs): data = super().get_context_data(**kwargs) comments = ChapterComment.objects.filter(chapter=self.get_object()) comments_number = comments.count() data['comments'] = comments data['comments_number'] = comments_number data['comment_form'] = CommentForm() return data def post(self , request , *args , **kwargs): if self.request.method == 'POST': comment_form = CommentForm(self.request.POST) comments = ChapterComment.objects.filter(chapter=self.get_object()) if comment_form.is_valid(): content = comment_form.cleaned_data['content'] for comment in comments: if comment.content == content: messages.info(request, 'The comment is duplicate.') return redirect(self.request.path_info) try: parent = comment_form.cleaned_data['parent'] except: parent = None new_comment = ChapterComment(content=content, author=self.request.user , chapter=self.get_object(), parent=parent) new_comment.save() return redirect(self.request.path_info) class ChapterComment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE, related_name='comments') content = models.CharField(max_length=550) date_posted = models.DateTimeField(auto_now_add=True) parent = models.ForeignKey('self',on_delete=models.CASCADE, related_name='replies') class Meta: verbose_name = 'chapter-comment' verbose_name_plural = 'chapter-comments' ordering=['-date_posted'] @property def children(self): return ChapterComment.objects.filter(parent=self).reverse() @property def is_parent(self): if self.parent is None: return True return False def get_absolute_url(self): return reverse('chapter', kwargs={'pk': self.pk}) def __str__(self): … -
Unable to hit REST endpoint in django
I have following code in my MyModuleViewSet: class MyModuleViewSet(viewsets.ModelViewSet): # ... @action(detail=False, permission_classes=(IsOwnerOrReadOnly,)) @debugger_queries def my_rest_api(self, request, pk=None): # ... return HttpResponse(resp, content_type="application/json", status=status.HTTP_200_OK) It is registered in my urls.py as follows: router.register(r'mymodule', MyModuleViewSet) I tried to hit this end point with following link: http://0.0.0.0:3000/myproject/api/mymodule/1019/my_rest_api/?format=json&param1=7945 But the postman says: Page not found (404) Request Method: GET Request URL: http://0.0.0.0:3000/myproject/api/mymodule/1019/my_rest_api/?format=json&param1=7945 Using the URLconf defined in myproject.urls, Django tried these URL patterns, in this order: 1. ... 2. ... ... 37. courseware/ api/ ^mymodule/my_rest_api/$ [name='mymodule-my-rest-api'] 38. courseware/ api/ ^mymodule/my_rest_api\.(?P<format>[a-z0-9]+)/?$ [name='mymodule-my-rest-api'] ... As you can see mymodule/my_rest_api is indeed specified in the response on line 3 and 38. Then why it is not invoked? What I am missing? -
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>`