Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
many to one field self relationship
i used a self relation ship inside model with foreignkey , purpose was to make a replyable comment , but idk how to use it in templates, i mean whats different between 3 ManyToOne relationships i used in template , how can i know form send reply or comment? model: class Comment(models.Model): #comments model post = models.ForeignKey(Post,related_name='comments',on_delete=models.CASCADE) text = models.CharField(max_length=300) user = models.ForeignKey(get_user_model(),related_name='users',on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) parent = models.ForeignKey('self', null=True,related_name='reply',on_delete=models.SET_NULL) class Meta(): verbose_name_plural = 'Comments' ordering = ['date'] def __str__(self): return self.test[:50] template: <div> <form method="post"> {% csrf_token %} {{ form.as_p }} <button value="submit">Send</button> </form> </div> <div> {% for comment in object.comments.all %} <p>{{ comment.text }}</p> {% for reply in object.reply.all %} <p>{{ reply.text }}</p> {% endfor %} <form method='post'> {% csrf_token %} {{ form.as_p }} <button value="submit">reply</button> </form> {% endfor %} </div> {% endblock %} can you a little explain how it works? -
How to set the extra value to 0 if the item is saved unchanged in django admin?
I use tablularinline and now when I save the item without any changes, 3 values are added to it. How can I set the extra value to 0 if the item is saved without changes? class ProductPictureAdminInline(SortableTabularInline): formset = CustomInlineFormSet fields = ("title", "image", "is_default", "order", "created_by", "created_at", "updated_at") readonly_fields = ("created_by", "created_at", "updated_at") model = ProductPicture def get_extra(self, request, obj=None, **kwargs): if obj: return 0 # For changing an item else: return 3 # For adding a new item -
How to debug 400 bad request with axios uploading file to Django restframework
I bumped into this error when uploading file from browser. Same javascript code was working yesterday ,but today it's not. I start digging into the error but not found the clue. in browser console. { "message": "Request failed with status code 400", "name": "AxiosError", "stack": "AxiosError: Request failed with status code 400\n at settle (webpack://frontend_react/./node_modules/axios/lib/core/settle.js?:24:12)\n at XMLHttpRequest.onloadend (webpack://frontend_react/./node_modules/axios/lib/adapters/xhr.js?:120:66)", "config": { "transitional": { "silentJSONParsing": true, "forcedJSONParsing": true, "clarifyTimeoutError": false }, "adapter": [ "xhr", "http" ], "transformRequest": [ null ], "transformResponse": [ null ], "timeout": 0, "xsrfCookieName": "csrftoken", "xsrfHeaderName": "X-CSRFTOKEN", "maxContentLength": -1, "maxBodyLength": -1, "env": {}, "headers": { "Accept": "application/json, text/plain, */*", "X-CSRFTOKEN": "Na6rGVCyq1lgDxeiks0LdHjrU5nLVpmp" }, "withCredentials": true, "method": "post", "url": "http://localhost:8000/api/drawings/", "data": {} }, "code": "ERR_BAD_REQUEST", "status": 400 } in django runserver console there is not almost hint. [15/Feb/2023 09:06:21] "GET /undefined HTTP/1.1" 404 3566 Bad Request: /api/drawings/ [15/Feb/2023 09:06:24] "POST /api/drawings/ HTTP/1.1" 400 36 My source code is like this below. formData.append("drawing",filePath); formData.append("detail",JSON.stringify({})); axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; axios.post( `http://localhost:8000/api/drawings/`,formData,{ headers: {'Content-Type': 'multipart/form-data'} } -
VS-Code Languages Mode more than one language definition
I am writing Django, Coding in template html using VS-Code IDE. When Language Mode is set on Django HTML then VSCode not autocomplete HTML codes. (e.g. not auto-closing with </html> and so one) Thus get autocomplete works on Django codes. (e.g. {% auto-closing %} and...) And vice versa. I need the VSCode Language Mode set on either Django HTML and 'HTML` same, auto complete each one codes. -
How to store and display map location in wagtails
I am trying to create an API for contact us page. The API take location through map click at wagtail admin panel and send API too. For now I want to know how can I ask user to pin a location and store it in my model. I cant think of anything to do. class Contact_UsPage(Page): pass My page name is Contact us thank you. I tried looking at official wagtails documentation and couldn't find anything that would help me. -
Django user.is active
Why when i desactive user on Django admin site in my class in post method requirement return negative first if requirement user is not None ? Probably if user desative true Django don`t look him in user table ? class LoginView(View): template_name = 'login.html' def get(self, request): form = LoginForm() return render(request, self.template_name, locals()) def post(self, request): form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('home') else: alert = messages.error(request, 'Twoje konto zostało zablokowane!') return render(request, self.template_name, locals()) else: alert = messages.error(request, 'Błędna nazwa użytkownika!') return render(request, self.template_name, locals()) -
List of months from django queryset
this is the model class PaymentChart(models.Model): pharma = models.ForeignKey(PharmacyProfile , on_delete=models.CASCADE) wholesale = models.ForeignKey(WholesaleProfile , on_delete=models.CASCADE) amount = models.CharField(max_length=10) reqeuest = models.BooleanField(default=False) paid = models.BooleanField(default=False) date = models.DateTimeField() credit = models.BooleanField(default=False) class Meta: ordering = ['-date'] i want to filter the list of all months, .ie [09/2021,10/2021,11/2021] -
Everytime Celery is restarted all the scheduled tasks are acknowledged first and if takes 20 minutes if there are 100 thousands of tasks
I mean every time when we restart our Celery workers because of our App being deployed - they are not actually executing any tasks from the Q until all the tasks are received/acknowledged first. Which take a huge amount of time given our amount of the tasks in the Q - close to 100K tasks and close to 20 minutes of lag accordingly. This question was already asked in 2016 here, here is what I can come up with given that, but I hope there is a better way: We can support multiple celery Qs inside a single RMQ and do this: tasks by default go to the new Q upon every deploy we move all thousands of the tasks from the new to old Q (dunno how quickly this can be done) different workers deal with old and new tasks That way at least the new incoming tasks won't be waiting for the old ones to be acked. But imagine - what if in the old tasks there is a task which should be executed during this period while the old tasks are still being fed to the workers - this approach won't solve it.