Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
`Django` cannot be imported after Ubuntu upgrading
After upgrading my Ubuntu from 20.04 to the latest version, my website cannot be deployed. Here is my /var/log/apache2/error.log: Wed Feb 15 15:16:56.565327 2023] [wsgi:error] [pid 1940107] [client 159.226.116.208:56112] Traceback (most recent call last): [Wed Feb 15 15:16:56.565340 2023] [wsgi:error] [pid 1940107] [client 159.226.116.208:56112] File "/home/djuser/djsites/mgkd/mgkd/wsgi.py", line 12, in <module> [Wed Feb 15 15:16:56.565344 2023] [wsgi:error] [pid 1940107] [client 159.226.116.208:56112] from django.core.wsgi import get_wsgi_application [Wed Feb 15 15:16:56.565351 2023] [wsgi:error] [pid 1940107] [client 159.226.116.208:56112] ModuleNotFoundError: **No module named 'django'** **No module named 'django'** I have another server which has not been upgraded, and the django websites there deployed normally. It seemed that django cannot be imported after Ubuntu upgrading. Then I checked my django virtualenv. I have really installed django in my virtualenv, but I cannot import it. -
Django url which accept both with parameter or without
I want to accept the both url such as /top/ /top/1 I tried a few petterns path('top/<int:pk>/', views.top, name='top_edit'), path('top/(<int:pk>)/', views.top, name='top_edit'), path('top/(<int:pk>)/$', views.top, name='top_edit'), def top(request: HttpRequest,pk = None) -> HttpResponse: return render(request, 'index.html', context) It accept /top/1 however /top/ is not accepted. How can I make it work? -
object.save() not working for arrayfield django
I have a ArrayField and want to change, but when I use .save(), object didn't update. from django.contrib.postgres.fields import ArrayField dates = ArrayField(models.CharField(max_length=10), size=300) object.dates += new_list object.save() -
How to get the authentication information in ModelViewSet?
I am using rest framework with ModelViewSet class DrawingViewSet(viewsets.ModelViewSet): queryset = m.Drawing.objects.all() serializer_class = s.DrawingSerializer filterset_fields = ['user'] def list(self, request): queryset = m.Drawing.objects.all() serializer = s.DrawingSerializer(queryset, many=True) return Response(serializer.data) With this script, I can use filter such as /?user=1 Howver this user=1 is not necesary when authentication information is used in script. (Because one user needs to fetch only data belonging to him/herself) How can I get the authentication data in list? -
Django filter in operation is not working with DateTimeobject
In Django ORM, I want to filter records using in-operation. Earlier when I was running the below query it was working fine: EndTime = 2023-02-01 (Varchar) week_list = ['2023-01-01','2023-01-21','2023-02-02','2023-02-12'] Query : count = Stats.objects.filter(EndTime__in = week_list).values('EndTime ').annotate(dcount=Count('EndTime ')) From this query, I was getting the proper result. But when I am trying the same with the below values it is not working. EndTime = 2023-02-01 12:00:09 (DateTimeobject) week_list = ['2023-01-01','2023-01-21','2023-02-02','2023-02-12'] count = Stats.objects.filter(EndTime__in = week_list).values('EndTime').annotate(dcount=Count('EndTime')) In this case, it is not returning the output but I want the same data as the earlier query was giving with the DateTime object field. can anyone please help ?? how can I achieve this?