Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying to production a Django app - Azure
I have a Django app in a Github repo. Through a Github action, it is deployed as a Python app in Azure. In the Azure portal: 1- In "Configuration > Application" settings, I've defined POST_BUILD_COMMAND as python manage.py makemigrations && python manage.py migrate as described in Configure a Linux Python app for Azure App Service. 2- I have configured a deployment slot and a production slot. It offers a 'Swap' option, to push the live app in the deployment slot to production. However, I'm under the impression that doing that doesn't run the POST_BUILD_COMMAND command for the production Django app, leaving the database unaltered - which means that the production frontend gets the new fields/updates, but the migrations don't occur. What's the best way to perform the migrations in production? Would the correct way be to set "Configurations > General settings > Startup Command" to 'python manage.py makemigrations && python manage.py migrate'? Would that work? -
Connection to server at "localhost" failed in Docker - Django
Im very new to Docker and im trying to create a one for my django application. but i encounter the error "Is the server running on that host and accepting TCP/IP connections?connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address" I've tried this and this and this . Basically everything I could find but still doesnt work . Docker-compose version: '1' services: web: build: . container_name: evident_django hostname: evident_django restart: always image: evident:latest volumes: - ./logs:/var/log/evident - ./src:/code - static_volume:/code/static expose: - 7000 ports: - "127.0.0.1:7000:7000" env_file: - ./src/.env depends_on: - db networks: - evident_network db: image: postgres:13-alpine restart: always container_name: evident_postgres hostname: evident_postgres volumes: - ./storage:/var/lib/postgresql/data/ env_file: - ./src/.env expose: - 5432 networks: - evident_network volumes: static_volume: networks: evident_network: driver: bridge Dockerfile FROM python:3.10.4-slim-bullseye COPY requirements.txt /requirements.txt RUN set -ex \ && BUILD_DEPS=" \ apt-utils \ build-essential \ ffmpeg libsm6 libxext6 \ postgresql-client \ python3-opencv \ " \ && apt-get update && apt-get install -y --no-install-recommends $BUILD_DEPS \ && pip install -U --force-reinstall pip \ && pip install --no-cache-dir -r /requirements.txt \ && rm -rf /var/lib/apt/lists/* RUN mkdir /code/ WORKDIR /code COPY /src . EXPOSE 7000 ENTRYPOINT [ "./entrypoint.sh" ] and the errors im getting … -
Create multiple user types in django
I want to create multiple user types in Django. Each type has several unique attributes, and some common like username and email. The code below creates 3 tables with one to one connection to the Account user model. However I want to add choice field to the user model and store user types in tuples, instead of creating is_type1 is_type2 etc. variables, but I'm not sure how to connect those types with it's class. Here is my account model in models.py: class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=255, unique=True) username = models.CharField(verbose_name='username', max_length=30, unique=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_type1 = models.BooleanField(default=False) is_type2 = models.BooleanField(default=False) is_type3 = models.BooleanField(default=False) objects = MyAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True And here is my subclasses: class Type1(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE, primary_key=True) #unique attrs def __str__(self): return self.account.username class Type2(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE, primary_key=True) #unique attrs def __str__(self): return self.account.username class Type3(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE, primary_key=True) #unique attrs def __str__(self): return self.account.username -
In Django how to add a placeholder to a form based on model charfield
I have a form: class SideEffectForm(ModelForm): class Meta: model = SideEffect fields = ['se_name'] def __init__(self, *args, p, **kwargs): super().__init__(*args, **kwargs) if p == 'antipsychotic': self.fields['se_name'].choices = [ ("insomnia_and_agitation", "Insomnida and Agitation"), ("akathisia", "Akathisia"), ("dystonia", "Dystonia"), ] That is based on this model: class SideEffect(TimeStampedModel): SE_CHOICES = [ ("insomnia_and_agitation", "Insomnida and Agitation"), ("akathisia", "Akathisia"), ("anticholinergic_effects", "Anticholinergic Side Effects") ] se_name = models.CharField("",max_length=200, choices=SE_CHOICES, blank=False) concern = models.IntegerField("",default=50) case = models.ForeignKey(Case, on_delete=models.CASCADE) As it stands the form displays the first option. I would however like to have a place holder e.g. 'Please select a side effect'. I could do this by having it as one of the options but would prefer not to as then would need to implement measures to stop the placeholder being saved as a valid user entry. I have tried a range of suggestions on the site but none have been sutiable -
Django : Plotly plot shows on localhost but not on heroku
I am trying to display some plots(created with plotly) on my page, it works totally fine on localhost but when deployed on heroku the plots are not shown. code to create plot in views.py def icons(request, name): l1 = testtable.objects.values() d1 = [] d2 = [] for i in l1: d1.append(i["d1"]) d2.append(i["d2"]) fig =px.bar(x=d1,y=d2) photo = plotly.io.to_html(fig,config= {'displayModeBar': False}) fig2 = px.line(x=d1, y=d2) photo1 = plotly.io.to_html(fig2,config= {'displayModeBar': False}) return render(request, 'icons.html', {'name':name,"photo":photo,"photo1":photo1}) code in icons.html {% extends 'index.html' %} {% block content %} <div class="content icon-content"> <div class="container icon-container"> <h3 class="icon-heading">Quick Launch</h3> <div class="icon-bar"> <a class="active" href="#"><i class="fas fa-hand-pointer fa-2x"></i><span>Time In/Out</span></a> <a href="#"><i class="fa-solid fa-copy fa-2x"></i><span>My Attendance Record</span></a> <a href="#"><i class="fa-solid fa-calendar-minus fa-2x"></i><span>My Leave List</span></a> <a href="#"><i class="fa-solid fa-file-invoice-dollar fa-2x"></i><span>My Payslips</span></a> <a href="#"><i class="fa-solid fa-calendar-check fa-2x"></i><span>Apply Leave</span></a> <a href="#" class="timesheet-icon"><i class="fa-solid fa-calendar-days fa-2x"></i><span>My Timesheet</span></a> <a href="#" class="team-icon"><i class="fa-solid fa-people-group fa-2x"></i><span>My Team</span></a> </div> </div> <hr> <div class="container icon-container"> <h3 class="icon-heading">Pending My Approval</h3> <div class="icon-bar"> <a class="active" href="#"><i class="fa-solid fa-file-circle-check fa-2x"></i><span>Leave</span></a> <a href="#"><i class="fa-solid fa-user-check fa-2x"></i><span>Attendance Regularization</span></a> <a href="#"><i class="fa-solid fa-business-time fa-2x"></i><span>Timesheet</span></a> </div> </div> <div> {% if photo %} {{ photo|safe }} {% else %} <p>No graph was provided.</p> {% endif %} </div> <div> {% if photo1 %} {{ photo1|safe }} {% … -
Django ManyToMany field relationship confusion
I am using Django 3.2 I am writing an app for commuities, and I want to be able to provide functionality for Administrators of a Community, as well as functionality to allow users to request access to restricted or private Groups. I seem to be getting myself confused with the ManyToMany relationships. This is what I have so far (redacted): class Community(models.Model): pass # Group of administrators responsible for moderation and membership approvals # (for restricted and private communities) # Note: administrators can autopost and delete topics and comments class CommunityAdministrator(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.RESTRICT) community = models.ForeignKey(Community, on_delete=models.CASCADE, related_name="administrators") class Meta: constraints = [ models.UniqueConstraint(fields=['user', 'community'], name='idxu_commty_admin') ] # Community membership approvals (for restricted and private communities) # class CommunityMembership(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.RESTRICT) communities = models.ManyToManyField(Community, though='CommunityMembershipApproval') class CommunityMembershipApproval(models.Model): PENDING = 0 APPROVED = 1 REJECTED = 2 APPROVAL_STATES = ( (PENDING, 'Pending'), (APPROVED, 'Approved'), (REJECTED, 'Rejected') ) person = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) community = models.ForeignKey(Community, on_delete=models.CASCADE) approval_state = models.PositiveIntegerField(choices=APPROVAL_STATES, default=PENDING) request_tstamp = models.DateTimeField(auto_now=True) Will the tables above allow me to implement the functionality I described above - namely: Administrators - allow me to add/remove administrators of a community, and also access the administrators of a community via an … -
use ->, #> operators in django JSONfield ORM
I would like to use ->, #> operators with Django ORM. at the moment I was able to perform only: ModelWithJsonField.objects.filter(id=1).values('outputs__key') that is translate from ORM in: SELECT ("app_model_with_json_field"."outputs" #> ARRAY['key']) FROM "app_model_with_json_field" WHERE "app_model_with_json_field"."id" = 1; args=(['key'], 1) but .values() it can't be used with single object, so if I try: ModelWithJsonField.objects.get(id=1).values('outputs__key') Any ideas to how perform this kind of operators in Django ORM? -
How to get actual return value instead of task id in celery?
I have a django app to run some linux commands accepted from a form. I'm implementing both actual process, and one using celery. I pass arguments to celery task and want to get return value from it, but I'm getting only the task id I guess. This is me running celery task in views.py: if 'celeryform' in request.POST: command = request.POST.get('command') rep = request.POST.get('rep') dur = request.POST.get('dur') cmd ='powershell -command '+command result=celery_run.delay(cmd,rep,dur) context = {'output':result} return render(request,'home.html',context) This is my tasks.py: from __future__ import absolute_import,unicode_literals from celery import Celery, shared_task import time,subprocess app = Celery('tasks', broker='redis://localhost:6379',include=['problem.tasks.add']) @shared_task def celery_run(cmd,rep,dur): output='' for i in range(int(rep)): time.sleep(int(dur)) p=subprocess.run(cmd,capture_output=True,text=True,shell=True) output += p.stdout return output I display my output in a textarea in a webpage, I'm getting output as d59af727-b24d-4518-9b66-dff063864c4a The above one is task id I guess How to get actual return value? Sample return value using normal method with command=pwd,rep=1,dur=2 Path ---- D:\betsol\Linux_command_app Path ---- D:\betsol\Linux_command_app -
Change object label on specific value in js
I'm working on charts in React.js and i want to display data sorted by month. In django i've created view for displaying json with total events per month and it looks like this: [ { "month": "2022-06-01T00:00:00+02:00", "total": 4 }, { "month": "2022-08-01T00:00:00+02:00", "total": 1 } ] ] I would like to sort every object in that array and change value 'month' from numbers to month name, so it would be: [ { "month": "june", "total": 4 }, { "month": "august", "total": 1 } ] ] For generating charts i'm using chartist. -
Django IntegrityError when change data in admin
Sorry I don't know much about deployment, My django rest framework project (I'm using it as a backend API), works fine in my computer, I can access to my django admin page and do modifications. The problem is, when I deployed my project to a server (I used nginx and gunicorn), I can't change data in django admin page, but I can see data and all my models. The message I get when I try to modify a model's data : IntegrityError at /admin/myproject/study/185/change/ Error: null value in column "id" violates not-null constraint PS: I don't have an id column in my Model, and I already run migrations PS: I use postgresql I imported the database that I have exported from my local project -
Explicity enable cache in Django by function/endpoint but not site wide
Our Django application is quite big, and it has reached the point where Caching in certain parts will improve a lot the performance. However, when we enable caching it will do site wise, and so some endpoints are failing for different reasons. Our ideal solution therefore would be to have cache by explicitly setting it by function or rest api endpoint, and all the rest disable by default. In order to enable it we could just use the decorator: @cache_page The problem is that I cannot get the default cache to be disabled, I tried these different options but non of them seem to work. CACHES = { 'manual': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', } } -- CACHES = { 'default': {}, 'manual': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', } } -- CACHES = { 'default': None, 'manual': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', } } -
icant see my 404 and 500 custome pages in django
hello i try to make a custom 404 and 500 pages in my django project so when i use this codes i cant see any result ! views.py: def handle404(request,exception): return render(request,'400.html',status=404) def handle500(request): return render(request,'500.html',status=500) url.py : handler404 ='base.views.handle404' handler500 = 'base.views.handle500' i see only this page : enter image description here anybody have some suggestions to improve my code ? -
list action with modal(not intermidiate page) to update model with input value
I want to update a list of model with input values but using modal instead of intermediate page, I googled a lot but I don't find any help, can someone give me some helps ? -
QR Application in Python
I want to create Django application. The logic is next: I scan the QR-code using QR- scanner, and then send this code to the web app. After that the app connect with Data Base and regarding to this information display some information. Could you give advice how to start this project, maybe some examples? i don't understand how looks the process of sending qr code from Qr scanner to app. -
Google Cloud Run + Django + RabbitMQ (or another message broker)
I have a contenerized Django application, which I deployed on Google Cloud Run. For the most time no requests are made to the app, so GCP can reduce it to 0 instances (and the billing is small). Some requests provide time consuming tasks and I need to handover them to another service by RabbitMQ (or possibly another message broker). I wanted to use pika at the Django app side, but if I understand correctly it forces it to be running all the time. So is there a solution, where I can pass messages to message broker from Django app and also listen to message queue, but the app can reduce to 0 instances when the queue is empty (and increase instances if it's not)? Thanks -
Date filter binned data
I have a model in django that contains a start and end date for a financial year and a value for demand volume. start_date = models.DateField(null=True) end_date = models.DateField(null=True) new_demand = models.PositiveIntegerField(default=0) I would like to filter this data on a given date range that may not coincide with the date ranges of the data, taking a proportion of the demand from each data point that may fall somewhere in the filter date range. I am assuming I need to work out if the data point falls over the edge of the filter and divide the demand by the number of days inside the filter? But I am having a hard time trying to write this. any help would be appreciated! :) -
How to count my checkboxes and insert to my vizualization of my table?
I have a problem that looks really simple to solve but I can't find the solution. I have in my django model a field nb_engins corresponding to an integerfield, my model is of this type : models.py class Flottes(models.Model): name = models.CharField(max_length=255, null=True) nb_engins = models.IntegerField(validators=[MaxValueValidator(9999999999)], default=0) engins = ArrayField(models.CharField(max_length=555, blank=True), null=True) calculateur = models.CharField(max_length=555, null=True) type_fichier = models.CharField(max_length=255, null=True) created_at = models.DateTimeField(auto_now_add=True, null=datetime.date.today) Here are now my 2 functions, one is used to retrieve the selected checkboxes and the other to validate my form component.ts // Get List of Checked Items getCheckedItemList(){ this.checkedList = []; this.count = 0; for (var i = 0; i < this.engins.length; i++) { if(this.engins[i].isSelected) this.count = this.count+1; this.checkedList.push(this.engins[i]); } this.checkedList = JSON.stringify(this.checkedList); } submitForm(): void { const { value } = this.form; // get selected fruit from FormGroup value const selectedEngin = value?.engins?.filter((f: Engins) => f.checked) || []; // form value binded console.log('current form value: ', value); console.log('only selected form value: ', selectedEngin); // original value from database not change console.log('original engins list: ', this.engins); this.result = { name: value?.name || '', selectedEngin, nb_engins: value?.checkedList|| '', calculateur: value?.calculateur || '', type_fichier: value?.type_fichier|| '', } alert('La flotte a été enregistré avec succès !'); this.api.registerFlotte(this.form.value) .subscribe((res:any)=>{console.log(res)}); … -
Infinity loop when i override the get() method in a class based view django
I want to override the get method. But I get the error : The view auctions.views.AuctionsDetail didn't return an HttpResponse object. It returned None instead. If I use a httpresponse I reload the function and call the function again. How can solve this? Its a detail view ''' def get(self, request, *args, **kwargs): list_auction = self.kwargs['pk'] set_current_bid=Bids.objects.filter(listing_auctions__id = list_auction).latest('id') print(f'offer {set_current_bid.offer}') return HttpResponseRedirect(reverse('auctions_detail', args=(list_auction,))) ''' -
Django quick quest on making queries for blog posts and categories
I have a blog page showing all the user's posts. Each post has a 'Category'. (Ex: Post 1 --> category: general coding, Post 2 --> category: general coding, Post 3 --> category: web dev) If I wanted to show all the categories that the user posted in (Ex: User profile page listview--> Categories posted --> general coding, web dev ) , would I have to use a 'for loop' and put them in a list? Or is there a better way to do this. posts = user.post_set.all() category_list = [] for post in posts: if post.category not in category_list: category_list.append(post.category) models.py class Category(models.Model): category_name = models.CharField(max_length=50, default='general coding', verbose_name="Categories") class Post(models.Model): title = models.CharField(max_length=100, help_text="100 characters or less") content = models.TextField() category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) liked = models.ManyToManyField(Profile, blank=True, related_name='likes') -
Django model constraint for ensuring one or both fields are not empty strings
Following this answer I want to set up a constraint on a Django model that ensures one or both of two fields are set. However, while that answer assumes the empty fields are NULL, in my case they are always empty strings. I'm not sure how to check for that in the constraint. from django.db import models from django.db.models import Q class Person(models.Model): firstname = models.CharField(max_length=150, blank=True, null=False, default="") surname = models.CharField(max_length=150, blank=True, null=False, default="") class Meta: constraints = [ models.CheckConstraint( name="%(app_label)s_%(class)s_firstname_and_or_surname", check=( Q(firstname__exact="", surname__exact!="") | Q(firstname__exact!="", surname__exact="") | Q(firstname__exact!="", surname__exact!="") ), ) ] This should work except that, unlike surname_isnull=False, surname__exact!="" isn't valid syntax. I know that if I had a queryset I could use exclude(surname__exact="") to mean "is not empty", but I'm not sure how to do that in this constraint with Q() expressions. -
how safe is it to use post requests through ajax?
I'm making inventory control applications in django. All data from the database is taken through ajax and api, that is, get, post and put requests. I use django view only to display html templates I need advice on how safe it is to use code like this: function iterTable() { let items = []; let docDate; let docContragent; let docWare; let comment; let table = document.querySelector(".invoice-add-table table"); for (var i = 1, row; row = table.rows[i]; i++) { if(row == document.querySelector('.add-elements')) { break; } docDate = document.querySelector('input[name="invoice-date"]').value docContragent = document.querySelector('select[name="invoice-contragent-select"]').value docWare = document.querySelector('select[name="warehouse-select"]').value comment = document.querySelector('textarea[name="invoice-comment"]').value // ITEMS let name = row.cells[1].querySelector('span').dataset.id let quantity = row.cells[2].querySelector('input').value let buy_price = row.cells[3].querySelector('input').value let sell_price = row.cells[5].querySelector('input').value items.push({ "product": name, "buy_price": buy_price, "sell_price": sell_price, "quantity": quantity, }); } let invoice = { "warehouse": docWare, "date": docDate, "comment": comment, "contragent": docContragent, "items": items } let json = JSON.stringify(invoice); const csrftoken = Cookies.get('csrftoken'); $.ajax({ data: json, contentType: "application/json; charset=utf-8", type: "POST", // GET or POST headers: {'X-CSRFToken': csrftoken}, url: "http://127.0.0.1:8000/warehouse/api/notes/", success: function (response) { alert('ok') }, error: function (response) { console.log(response.responseJSON.errors) } }); return false; } document.querySelector('span[name="note-submit-btn"]').addEventListener("click", iterTable); serialisers.py def create(self, validated_data): last_num = ConsignmentNote.objects.filter(warehouse__company=self.context['request'].user.company).latest('id') items = validated_data.pop('items') note = ConsignmentNote.objects.create(**validated_data, doc_type = 1, number … -
How to connect AWS Opensearch with Django project on AWS Lambda
I'm working on a project that is almost finished except for one thing and I'm in despirate need of help.. The backend of my project that is written in Django/Python is deployed on AWS Lambda using a library called Zappa because my knowledge about AWS is really low and this seemed (for the first version) the best and fastest way to have my project up and running. It uses a AWS RDS PostgreSQL database to handle my database. The frontend of my project is written in Javascript/ReactJS has been put on a S3 bucket en made publicly available through Cloudfront by following this tutorial. Now, all of the above already works perfectly, it's just that now, because we have a lot of data that needs to be send from our backend/database to our frontend through API's, I want to make use of elasticsearch. So, I started using the AWS Opensearch Service (and using elasticsearch version 7.10) which then generated an endpoint for me to connect at. This all works great on my localhost, I can connect by using the code below, create my indexes using the ElasticsearchDSL library. Also because the endpoint is publicly availbable, I can just make an … -
Weight converter program in python using while loop [closed]
python use to printing the variables Question: weight:? lbs or kg:k 32 kilos -
How to test query_params?
how can i test query_params? I have provided a response and a request, but it still doesn't work. Initially, the error was like this: price = int(self.context.get('request').query_params.get('price', None)) AttributeError: 'NoneType' object has no attribute 'query_params' test_api.py class IpotekaApiTestCase(APITestCase): def setUp(self) -> None: self.offer_1 = Ipoteka.objects.create(bank_name='test', term_min=1, term_max=3, rate_min=1.5, rate_max=4.8, payment_min=12345, payment_max=123456) self.offer_2 = Ipoteka.objects.create(bank_name='test_1', term_min=1, term_max=3, rate_min=1.5, rate_max=4.8, payment_min=12345, payment_max=123456) def test_get(self): url = reverse('offer-list') response = self.client.get(url) view = IpotekaModelViewSet.as_view({'get': 'list'}) request = RequestFactory().get('/') context = {'request': view(request), 'response': response} serializer_data = IpotekaSerializer([self.offer_1, self.offer_2], context=context, many=True).data self.assertEqual(status.HTTP_200_OK, response.status_code) self.assertEqual(serializer_data, response.data['results']) serializers.py def get_payment(self, obj) -> int: try: price = int(self.context.get('request').query_params.get('price', None)) deposit = int(self.context.get('request').query_params.get('deposit', None)) term = int(self.context.get('request').query_params.get('term', None)) if price == 0 or term == 0: return 0 return self._get_offer_result(price, deposit, term, obj) except (ValueError, TypeError): return 0 Got this error: File "D:\Work\Django\Test_ipoteka\ipoteka\serializers.py", line 22, in get_payment price = int(self.context.get('request').query_params.get('price', None)) AttributeError: 'Response' object has no attribute 'query_params' ---------------------------------------------------------------------- Ran 1 test in 0.014s FAILED (errors=1) I also deleted response but it didn't help -
OR match in Python Redis scan
I'm using Django Redis to manage our application's Redis cache. Let's say I have the following keys in the cache: user-1:color user-1:sport user-2:color user-3:color user-3:whatever I want to delete all keys for user-1 and user-2. I know I can use the delete_pattern() method (see docs): for user_id in [1, 2]: cache.delete_pattern(f"user-{user_id}:*") However, this is very slow. See these links for more details about why: https://github.com/sebleier/django-redis-cache/issues/169 https://morganwu277.github.io/2017/07/16/Django-Redis-Scan-Too-Long/ I would like to try building a broader pattern so I only need to make one call to delete_pattern(). According to the docs, the pattern is glob syntax but I've tried the following and it's not working: cache.delete_pattern(f"user-{1,2}:*") Any ideas on how to construct this pattern?