Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku remote ERROR: Could not find a version that satisfies the requirement django-admin-black==0.0.1 (from -r /tmp/build_e45a4b07/requirements.txt
I'm updating my heroku by using a django-admin-black==0.0.1, but heroku does find this version. How can I handle this ? remote: Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) remote: Collecting Django==3.1.6 remote: Downloading Django-3.1.6-py3-none-any.whl (7.8 MB) remote: ERROR: Could not find a version that satisfies the requirement django-admin-black==0.0.1 (from -r /tmp/build_e45a4b07/requirements.txt (line 4)) (from versions: none) remote: ERROR: No matching distribution found for django-admin-black==0.0.1 (from -r /tmp/build_e45a4b07/requirements.txt (line 4)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... -
side bar not in the right position using django template
I am trying to create a reddit-like platform. In my base file, there is the header, and then the page is divided into two sessions. Here is what my base looks like: <html> <head> <link rel="stylesheet" href="{% static 'css/reddit.css' %}"> </head> <body class="base-master"> <div class="page-header-container"> <div class="page-header"> <!--more page header stuff> </div> </div> <div class="content-container"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} </div> <div class="col-md-4"> {% block sidebar %} {% endblock %} </div> </div> </div> </body> </html> This seems to work pretty fine for most of my html, I have two columns, the left one being much larger while the right one is essentially a side bar. When I applied this template to my post_detail.html, which on the left side is post detailed content + comment session and the right side is supposed to be the same side bar. The side bar doest show up on the right but rather got wrapped to the bottom after the comment session. When i remove the comment session, it seems to be working. The comment session is called into another html, the format looks like this: {% extends 'Reddit_app/base.html' %} {% load humanize %} {% block content %} <div … -
ProgrammingError - Trying to have images appear under multiple categories
I have a model called CarModel and a model called CarModelImage. I want to be able to have images be associated to multiple CarModels. For this I tried using a ManyToManyField. When I visit the admin page for CarModelImage I get the following error. ProgrammingError at /admin/cars/carmodelimage/ Exception Value: column cars_carmodelimage.model_id does not exist Why is it that I can use the many to many in CarModel but not in CarModelImage? Is there a way I can add id to all my models without having to drop the database? class CarModel(models.Model): title = models.CharField(max_length=80) category = models.ManyToManyField(CarCategory) ... class Meta: verbose_name_plural = "Car Models" def __str__(self): return self.title class CarModelImage(models.Model): timestamp = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='cars/') model = models.ManyToManyField(CarModel) # This is what I had before: model = models.ForeignKey(default=1, on_delete=models.CASCADE, to='cars.CarModel') def filename(self): return basename(self.image.name) class Meta: verbose_name_plural = "Car Model Images" ordering = ["timestamp"] def __str__(self): return self.filename() -
Why is my xpath not working with selenium?
I need to write a script that given the user's input in my website it connects to this page to submit the number and download a file. The thing is, the xpath is not working at all. What am I doing wrong? This is the view (I deleted the parts not relevant to the question): from django.shortcuts import render, HttpResponse import requests from django.views.generic import FormView from time import sleep from selenium import webdriver class ConstanciaInscripcion(FormView): def get(self, request): return render(request, 'app/constancia-inscripcion.html') def post(self,request): form = MonotributoForm(request.POST) email = request.POST['Email'] cuit_r = int(request.POST["CUIT"]) #Selenium script DRIVER_PATH = 'C:/Users/python/chromedriver.exe' driver = webdriver.Chrome(executable_path=DRIVER_PATH) driver.get('https://seti.afip.gob.ar/padron-puc-constancia-internet/ConsultaConstanciaAction.do') driver.implicitly_wait(20) cuit = driver.find_element_by_xpath("//input[@id='cuit']").send_keys(cuit_r) submit = driver.find_element_by_xpath("//input[@id='btnConsultar']").click() return render(request, 'app/constancia-inscripcion.html') The website also has a captcha and I was given a method to deal with it, should I also add the captcha field to a driver.find_element and pass the method there? -
Solution to serializing a <class 'django.core.paginator.Paginator'> object?
Currently, I am implementing an Django view which reads from a MySQL database, saves that table into a Pandas dataframe, converts that table into a JSON string, then loads that string into a list. Code: def myView(request): ... #saved dataframe = df JSON = df.to_json(orient="records") JSON = json.loads(JSON) return django.http.JsonResponse(JSON, safe=False) The issue is that with our database, after N number of objects being rendered on the browser, the browser crashes and says it is "out of memory". So, I'm trying to put implement pagination into its view. The problem is that the class 'django.core.paginator.Paginator' is not serializable. There is not many solutions that I could find online. This is the only one I could find: Serializing a pagination object in Django, and my Django project doesn't use models so this one isn't useable. Therefore, does anyone have any advice? I know I could use Django REST, but refactoring my project to use models has me worried I might corrupt our database so I'm trying to be safe. -
Background task for Django on Google App Engine
I have a problem I haven't been able to find a (simple) solution for. In views.py at the moment from .utils import some_heavy_function @login_required def my_function_view(request): user = request.user instance = MyModel(user=user) if request.method == "POST": form = MyModel_form(request.POST,instance = instance) if form.is_valid(): form.save(commit=False) #Run function which saves the form some_heavy_function(form) messages.success(request, "Success!") return redirect("my_template") else: form = MyModel_form() return render(request, "my_app/my_html.html") As you can see, I want to run some_heavy_function in the background when the user submits a form - all it does is to run a python-script and update some values in form.instance based on the script. The user should not wait for this to end. I have looked into django-background-tasks, django-q and the sync_to_async but I have not managed to make it work (sync_to_async does not work with @login_required, redis does not work on windows and django-background-tasks needs an extra call to actually execute the queued processes) What would be the best way to do so? My Django app is running on Google App Engine, if that makes it more easy -
In which circumstances we should use workers for django channels?
As this answer says, we normally won't need workers for django channels. So, for light tasks like delivering simple text messages over websockets, we shouldn't need workers. But, here's an app from a Django core developer, which uses channels' workers. Even though the app is very very simple (just delivers text), it uses workers. So I'm a bit confused. I only use django channels for the chat app of my website, which delivers simple text messages for now. Should I use workers of channels or not? Or when should I consider using a worker? -
What is the best tech-stack for someone learning full-stack development
I have tried some Typescript and Django, I want to try a bit of everything before I decide what stack to focus on. The only database I know is PostgrteSQL and I'd like to stick to that database, I am pretty familiar with React, but Im open to other frameworks as well -
cant overwrite on django Stripe webhook and convert BooleanField to True?
i'm using django Stripe Cli and i have a E-Commerce Website and i'm trying to make the order is True after Payment Models.py: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateField(auto_now_add=True) order_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username Here is some of my OrderPayment Views: class OrderSummary(LoginRequiredMixin, View): def post(self, request, *args, **kwargs): order = Order.objects.get(user=self.request.user) #this is to bring the order return JsonResponse({'id': checkout_session.id}) here is my stripe-webhook views @csrf_exempt def stripe_webhook(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) ) if event['type'] == 'checkout.session.completed': session = event['data']['object'] customer_email = session["customer_details"]["email"] orders = session["metadata"]["order"] delivered=orders.ordered delivered=True delivered.save() return HttpResponse(status=200) This is the Error: AttributeError: 'str' object has no attribute 'ordered' -
Django/Python Hostgator
vengo renegando hace bastante con Hostgator por problemas de compatabilidad y demas! Lo ultimo que recibi de su parte fue lo siguiente, (no funciona el acceso a mi pagina) **Traceback (most recent call last): File "index.fcgi", line 11, in <module> WSGIServer(get_wsgi_application()).run() File "/home1/ingenia4/.virtualenv/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/home1/ingenia4/.virtualenv/lib/python3.5/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home1/ingenia4/.virtualenv/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home1/ingenia4/.virtualenv/lib/python3.5/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home1/ingenia4/.virtualenv/lib/python3.5/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home1/ingenia4/.virtualenv/lib64/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 662, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home1/ingenia4/public_html/mydjango/settings.py", line 127, in <module> MEDIA_ROOT=os.path.join(BASE_DIR, 'media') File "/home1/ingenia4/.virtualenv/lib64/python3.5/posixpath.py", line 89, in join genericpath._check_arg_types('join', a, *p) File "/home1/ingenia4/.virtualenv/lib64/python3.5/genericpath.py", line 143, in _check_arg_types (funcname, s.__class__.__name__)) from None** TypeError: join() argument must be str or bytes, not 'PosixPath' [Thu Feb 25 09:48:30.059609 2021] [fcgid:warn] [pid 96554:tid 22791784634112] (104)Connection reset by peer: [client 179.108.123.250:21087] mod_fcgid: error reading data from FastCGI server, referer: http://ingeniartech.co/ [Thu Feb 25 09:48:30.059751 2021] [core:error] … -
Django: multithread vs multiprocessing vs asyncio
I have a Django application where users can upload a file and my site will convert the file to a format of their choice. I recently discovered that if multiple users convert files at the same time it will process like this: Converting user 1s file waiting....... done converting user 2s file waiting....... done This is obviously very inefficient when multiple users are downloading files. I have looked into things like multithreading vs multiprocessing vs asyncio for python. I can't seem to pick out the differences between the 3. What is the difference and which would be best for my particular Django site? Thanks :) -
Filtering on a Window Annotation in Django
I realize this is a well known 'limitation', that you cannot straightforwardly filter on a window functions annotation, but I am looking for ways around that. I have seen an answer to this question that suggests using a subquery, but I cannot work out what the syntax should be without getting a *** django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression error. The data represents a timeseries with discrete states. These states change over time. I need to get a list of timestamps (or indices) where the 'state' changes from one to the next. Using a Window Function, I can get a queryset with the state change, but cannot then filter on that to get the index/timestamp of when the change occurs. Very simplified (non-working) code is: *models.py class MyModel(models.Model): parent = models.ForeignKey('MyParent') timestamp = models.DateTimeField() state = models.IntegerField() *view deltas = MyModel.objects.filter(parent=parent).annotate( previous_state=Window( expression=Lag('state', offset=1, default=0), order_by=F('timestamp').asc() ), delta=F('state')-F('previous_state') ).values('delta') This gives a queryset of records with the diff value indicating a state change (e.g. where state goes from 0->1, diff = 1, where state goes from 3 -> 2, diff = -1, etc.), however I cannot filter on it to find where those … -
How to send A LOT of files to browser for client-side archiving?
Not long ago I did small web-service which collected a lot of images on user request, archived them on server and send back to user. Problem was that these archives were 1-3 GB and storing them even few hours on server was wasteful. I want to remake service, but I need a way to load images into user browser and when collecting is finished - archive it client-side. Seems like it should possible, but I don't know where to start and what to google or read. What I definetly know, that I need solution for Django/Flask because my experience is mostly Python. -
Set up Disque Nodes for Django Q
I'm trying to make Django Q work in my current Django Project, but I think there's some documentation missing. It just states "configure the broker and move on", but I cannot find any documentation of how to configure Disque Nodes. I have installed redis and taken the following code-snippet from the documentation here: #settings.py Q_CLUSTER = { 'name': 'DisqueBroker', 'workers': 4, 'timeout': 60, 'retry': 60, 'disque_nodes': ['127.0.0.1:7711', '127.0.0.1:7712'] } but running python manage.py qcluster returns redis.exceptions.ConnectionError: Could not connect to any Disque nodes. I assume I'm missing a step or two, but I cannot find any documentation what so ever, apart from the code-snippet and the "configure your broker"-line. -
Default value Timefield Django
I have a timefield and I would like to set up a default value. I tried time = models.TimeField(default=datetime.time(10, 0)) but I have the error cannot cast type time without timezone to timestamp with time zone Any idea ? -
GCP App Engine django make migrations on a VPC cloud SQL
So I've been followed the turorial deploying a Django App on App Engine, basically I'm struggling a lot with Cloud SQL because my organization has a non-external-ip allowed for Cloud SQL instances, which means that all the Cloud SQL instance should be deployed on a VPC network (a network that I couldn’t find a way to connect from my local computer). So what I did was to deploy a local mysql and use it to run locally while I developing. When I send the app to the App Engine Cloud I create a connector to connect the app with the VPC-Cloud Sql instance. The problem that I'm having is that the app does not run the python manage.py makemigrations on the cloud SQL instance, and I don't know how to make the migrations on a VPC Cloud Sql Instance Please any help will be appreciate -
python matplotlib.pyplot - Cannot use setattr on plt objects
I need to dynamically change plot properties based on an input where the user selects the property they want to change and enters the value they want to change it to. I thought I could accomplish this by performing the following: Selected_Property is a plot parameter (e.g., xscale ect..) Entered_Value is whatever the user wants to change the value to import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5, 6] y = [1, 10, 100, 1000, 10000, 100000] plt.plot(x,y) setattr(plt, Selected_Property, Entered_Value) plt.show() However, no matter what I put in setattr, no changes are applied to the plot. I cannot change plot properties using plt.(property to change) because this property is selected dynamically based on the user's input and I do not know how to access plot properties using variables and "." notation. Is there anything I can try to fix this issue? -
Django + Docker - Server Error 500. Long Post
I am currently trying to get my Django application ready for deployment. I am trying to 'dockerize' my application by creating an image of my application using docker, dockerfile and uwsgi. I can do this with the following command: sudo docker create --name container --network network --network-alias container -t -p 40001:8001 image_name docker build -t image_name . The image gets built, I can start it and I can access the home page of the containerised application. However, when I try to navigate to other pages within the application, i get a Server Error (500) and in the console (Firefox), i get this error: The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol. I have this in my base.html: <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <meta content="utf-8"> And every webpage extends this page. I believe this could be an issue with my static files configuration as I am using WhiteNoise. But I was having issues with my dockerfile and uwsgi.ini file. settings.py """ Django … -
Custom User fields with token submission django rest framework simplejwt
I'm using django rest framework simplejwt web tokens for vue js app, I can receive web token with email and password and then reuse them to get data. I want to get custom user fields like address or mobile # with token submission from vue js. So far i'm unable to make an end point with such information. Right now i'm only able to make an end point which returns username with the help of request.user class UserListCreateAPIView(APIView): permission_classes = [IsAuthenticated] def get(self, request): username = request.user serializer = AccountSerializer(username) return Response(serializer.data) I know i can do it while fetching token as following but i want to fetch custom user info via token submission. Kindly suggest a solution where i can make such end point with custom user fields. I'm new to this so let me know if you need any more info regarding my problem. class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) refresh = self.get_token(self.user) data['refresh'] = str(refresh) data['access'] = str(refresh.access_token) # Add extra responses here data['username'] = self.user.username data['email'] = self.user.email # data['groups'] = self.user.groups.values_list('name', flat=True) return data class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer -
Wagtail API - How to filter by foreign key field, other than primary key
I'm currently using Wagtail's API. I have the following: ... @register_snippet class DocumentCategory(index.Indexed, models.Model): """ Defines a Document category """ # Name of the category name = models.CharField( verbose_name=_("Nome"), max_length=100, blank=False, null=False, unique=True, ) # String representation of this model def __str__(self): return self.name class Meta: verbose_name = _("Categoria de Documento") verbose_name_plural = _("Categorias de Documentos") ordering = ["name"] # alphabetical order class DocumentPage(BasePage): """ Document Page """ # The document document = models.ForeignKey( "wagtaildocs.Document", verbose_name=_("Documento"), blank=False, null=False, related_name="+", on_delete=models.PROTECT, ) # Category of the document (only 1 category) category = models.ForeignKey( "document.DocumentCategory", verbose_name=_("Categoria"), blank=False, null=True, on_delete=models.SET_NULL, help_text=_("Categoria do Documento"), related_name="document", ) Let's assume I have a category named Categoria Doc 1. How can I hit Wagtail's API to filter based on the foreign key name? I would like to do the following: GET /api/pages/?type=document.DocumentPage&category=Categoria Doc 1 However, when I do this, I get the following: -
How to add watermark to video file while saving using django using moviepy
To Accomplish : watermarked video Process Followed : Create a models.py with user, video_file, upload_date fields Create a forms.py to accept video_file with validations Lastly views.py to link file and process watermark process while uploading the video. Here is my views.py def upload_video(request): if request.method == "POST": form = VideoUploaderForm( data = request.POST, files = request.FILES, ) if form.is_valid(): obj = form.save(commit = False) vid = request.FILES['video_file'] clip = VideoFileClip(vid.temporary_file_path()) #watermark video = VideoFileClip(clip) logo = (ImageClip(LOGO_PATH) .set_duration(video.duration) .resize(height=50) .margin(right=8, top=8, opacity=0) .set_pos(("center","bottom"))) final_ = CompositeVideoClip([video, logo]) final_.write_videofile("watermarked.mp4") obj.save() return redirect(page_to_load) else: form=VideoUploaderForm() return render(request,'page.html',{"form":form}) quote I also want to add LOGO to the video which can be a simple PNG image. Error I got: 'VideoFileClip' object has no attribute 'endswith' -
python: Send string value without using string
I'm setting a python application that uses an external module padelpy that wraps the access to a rest API: from padelpy import padeldescriptor I have a dictionary with settings names and values: settings = { 'fingerprints': False, 'd2_d': False, ... } I loop through the received POST.request parameters to check which setting(s) to communicate as true: for setting in settings.keys(): if setting in request.POST: settings.update({setting: request.POST.get(setting)}) str_conf = '%s=TRUE' % setting padeldescriptor(str_conf) if I use padeldescriptor(fingerprints=TRUE) it works but if I use padeldescriptor(str_conf) it's the same as sending padeldescriptor("fingerprints=TRUE") and I get an error back from the server: Exception in thread "main" java.lang.NumberFormatException: For input string: "fingerprints=TRUE" How can I send the settings without using strings? Thanks -
Angular with Django API on different port not passing auth cookies
I'm trying to get the following to work but am having trouble with CORS and SAMESITE. Here's the request/response from chrome. I'm requesting from a page rendered at http://myhost.foo:4200: General: Request URL: http://myhost.foo/api/rest/accounts/login/ Request Method: POST Status Code: 200 OK Remote Address: 10.33.86.254:80 Referrer Policy: strict-origin-when-cross-origin Response: HTTP/1.1 200 OK Server: nginx/1.16.1 Date: Fri, 05 Mar 2021 18:37:03 GMT Content-Type: application/json Content-Length: 361 Connection: keep-alive Vary: Accept, Cookie, Origin Allow: GET, POST, HEAD, OPTIONS X-Frame-Options: SAMEORIGIN Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://myhost.foo:4200 Set-Cookie: csrftoken=ybByAOa1I7LJptNPKUgG58SLTgiL3kENQxF4r772TmpyM88Ib0trKBM0sLTdFvar; expires=Fri, 04 Mar 2022 18:37:03 GMT; Max-Age=31449600; Path=/; SameSite=Lax Set-Cookie: sessionid=u7awj20fwp7uejglblsb56uhmbndvk9i; expires=Sat, 06 Mar 2021 18:37:03 GMT; Max-Age=86400.0; Path=/; SameSite=Lax Request: POST /api/rest/accounts/login/ HTTP/1.1 Host: myhost.foo Connection: keep-alive Content-Length: 43 Accept: application/json, text/plain, */* DNT: 1 X-CSRFToken: Bg451MFngAOd1a785v2dt5zPRtcAZTu3MP0OSK2kPwqOwTlkDvaUd76Z4dcI8EGO User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.72 Safari/537.36 Content-Type: application/json Origin: http://myhost.foo:4200 Referer: http://myhost.foo:4200/ Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.9 That seems successful. We Set-Cookie with csrf and sessionid. It's Lax, and I can't use None because this is a dev instance that doesn't use https, which would require secure=true. When querying with the next request, the cookies are not sent: General: Request URL: http://myhost.foo/api/rest/accounts/login/ Request Method: GET Status Code: 401 Unauthorized Remote Address: 10.33.86.254:80 Referrer … -
How to 'order_by' model objects in Django using a field several levels of relationship apart
I have multiple models for an app that will contain option to generate forms for various companies. I am using mySQL. Also, I am a Noob :( FSForm is the master form. Whenever it is generated, it gets its 'fskey' from the 'Company' object (some logic determines which of the two keys to select). The are lots of 'FSRows' that a form can have. Django determines which rows to select and populate for the 'FSForm' as follows. The 'FSKeyRow' objects pertaining to the 'fskey' of the form are retrieved. Then the corresponding 'FSRows' in those objects are populated as objects of the 'FSDataPoint' model for that form. Following are my models: class Company(models.Model): """Represents all companies""" symbol = models.CharField(max_length=5) name = models.CharField(max_length=255) annual_fskey = models.ForeignKey("FSKey", on_delete=models.CASCADE, related_name="company_annual_key") qtr_fskey = models.ForeignKey("FSKey", on_delete=models.CASCADE, related_name="company_qtr_key") class FSForm(models.Model): """Represents all forms""" company = models.ForeignKey("Company", on_delete=models.CASCADE, related_name="company_fsform") functional_currency = models.ForeignKey("Currency", on_delete=models.CASCADE, related_name="fsform_currency") fskey = models.ForeignKey("FSKey", on_delete=models.CASCADE, related_name="fsform_key") class FSKey(models.Model): """Represents keys which determine the rows to populate in the FSForm""" name = models.CharField(max_length=100) comments = models.TextField(max_length=500, blank=True) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) class FSRow(models.Model): """Represents all possible rows""" name = models.CharField(max_length=255) comments = models.TextField(max_length=500, blank=True) class FSKeyRow(models.Model): """Represents all rows that pertain to a … -
How to connect django to postgres in kubernetes?
I have a kubernetes deployment for postgres: resource "kubernetes_deployment" "backend_postgres" { metadata { name = "backend-postgres" labels = { app = "backend-postgres" role = "deployment" } } spec { replicas = 1 selector { match_labels = { app = "backend-postgres" } } template { metadata { labels = { app = "backend-postgres" role = "deployment" } } spec { volume { name = "data" persistent_volume_claim { claim_name = kubernetes_persistent_volume_claim.data.metadata[0].name } } container { name = "postgres" image = "postgres:10-alpine" port { container_port = 5432 } env { name = "POSTGRES_PASSWORD" value = "PASSWORD" } env { name = "POSTGRES_USER" value = "postgres" } env { name = "POSTGRES_DB" value = "postgres" } volume_mount { name = "data" mount_path = "/var/lib/postgresql/data" sub_path = "postgres" } } } } } } This deployment is exposed using this kubernetes service: resource "kubernetes_service" "backend_postgres" { metadata { name = "backend-postgres" labels = { role = "deployment" } } spec { port { port = 5432 target_port = "5432" } selector = { app = "backend-postgres" } } } And I also have another deployment for django: resource "kubernetes_deployment" "backend" { metadata { name = "backend" labels = { app = "backend" role = "deployment" …