Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
save data of a select after being filtered with ajax
hello I have a problem with a select that filters the other. I did all the filtering correctly from the frontend point of view but in the backend I can not save the data, indeed data since it is a formset. the error that comes out of me is this: select a valid choise. That choice is not one of the available choices. I think the problem is in the fact of the form as it does not find 'group_single' that I pass through post in my views. my models class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'gruppo' ) class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente' ) class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField( choices = giorni_settimana_scelta, default = '-' ) dati_gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'dati_gruppo' ) gruppi_scheda = models.ForeignKey( Schede, on_delete = models.CASCADE, related_name = 'gruppi_scheda' ) class DatiEsercizi(models.Model): serie = models.IntegerField() ripetizione = models.IntegerField() peso = models.DecimalField( max_digits = 4, decimal_places = 1, blank = True, null = … -
How can I add tailwind css to an existing django app
I already have a Django project with many apps and one of them is demo_app. I have some views and templates added to the demo app but I want to start using tailwind in the demo_app templates. I have seen that to add tailwind I need to create the theme app using tailwind but I want to add it to the already existing demo_app. How can I do that? -
how to retrieve new data from database when db received new entry without refreshing or any other action in Django
I have a web & mobile application synced with the same DB. but now I want to fetch the latest data to my web app without refreshing or any other action like button click from browser. data will be saved from the mobile app. and displayed there, but in the web app when I refresh the page then I am getting the latest entries. how may I be able to fetch the latest entries from my web app without refreshing the page? what approach is best. data entered from mobile using API, the web app is in Django 3.2 and for API's I am using Django rest framework -
how to pass two models in django view in the following code?
i have two models : class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() bargainprice = models.FloatField(default=0) discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() and the second one : class BargainModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) itemId = models.IntegerField() bprice = models.FloatField() can anyone explain whats going on in the following view : class ItemDetailView(DetailView): model = Item template_name = "product.html" i know they passing one model in the view and here is how they accessed in template: <span class="mr-1"> <del>₹ {{ object.price }}</del> </span> <span>₹ {{ object.discount_price }}</span> and how can I pass two models in this view? -
DJANGO: Get a parent queryset from a child queryset
Say I have the following for my models.py: from django.db import models class Department(models.model): name = models.CharField(max_length=255) class User(models.model): name = models.CharField(max_length=255) department = models.ForeignKey( Department, related_name="department_users", on_delete=models.CASCADE ) ... So I am doing a lot of complex filtering on my User queryset to get to a subset of Users who are considered "active" but now I need to generate a list of Departments who have at least one "active" user. I know that I can use a reverse lookup like: Department.objects.filter(department_users__name__contains=...) etc and do the filtering all over again but I wanted to know if there was a way to get that information directly from the "active" User queryset. I tried using .values() but that gives me a queryset of dictionaries and I really wanted a queryset of django Models so I can do further filtering for the Department queryset. Do you guys know if there is a way to do that? -
Unable to download depencencies in virtual environment
Hope you're doing well, I was trying to work on this django project from github but i could not download all the packages in a virtual environment, it says (venv) C:\Users\me\Downloads\movie_recommender-master>pip install -r requirements.txt Unable to create process using 'C:\Users\me\AppData\Local\Programs\Python\Python310\python.exe "C:\Users\me\Downloads\movie_recommender-master\venv\Scripts\pip.exe" install -r requirements.txt' . I have read through tons of questions in stack over flow but nothing seems to work, I would be very grateful if you could help me here. My command prompt says this -
How to display loop items properly in Django
I have a list like this : {'serial1': 'BPCE-RNHC-25G8', 'subject1': 'EMP004', 'serial2': '7QF2-6HI9-XKZZ', 'subject2': 'EMP005', 'serial3': '8FIW-9JRB-NY4J', 'subject3': 'EMP003', 'serial4': 'SG8P-YQKG-ZV3C', 'subject4': 'EMP002', 'serial5': 'PBF7-WZ HT-WPZR', 'subject5': 'EMP001'} When I send this list over my html template using for loop , the serial and subject value is separated and divide into 2 column which represent: My desire output is the serial and subject appear on the same column for the same record. For example: My code: <div class="row"> <div class="col-md-5 grid-margin stretch-card"> <div class="card"> <div class="card-body"> <h4 class="card-title">Assigned Minis</h4> <div class="list-wrapper pt-2"> <ul class="d-flex flex-column-reverse todo-list todo-list-custom"> {% for key, value in assignedMini.items %} <li> <div class="form-check form-check-flat"> <label class="form-check-label"> {{ value }} </label> </div> </li> {% endfor %} </ul> </div> </div> </div> </div> -
Load images and show them in a grid contraint from max height
I have several image loaded from database linked by articles. Theses images have different width and height (portrait/landscape). 1 article can have 1 or more images. If 1 article have only one image, it show picture to take all size of (width max = 180mm) If more article I want to show them in a grid with contraint max for height. The goald is to load each article and show it on a single page (MediaPrint) to print only one article by page ... For each picture associated to one article I want to show in the same page and only on this page. In my template actually I made this ... It use jquery to show picture if portrait or landscape picture. If more than one picture, I fix width in style html properties directly without JQUERY. TEMPLATES <div class="col mb-5 text-center"> {% if value|length == 1 %} <img class="img-responsive_jquery" src="/media/photos/{{ image }}.jpeg" /> {% endif %} {% if value|length > 1 and value|length < 5 %} <img class="img-responsive" src="/media/photos/{{ image }}.jpeg" style="width:70mm !important" /> {% endif %} {% if value|length > 5 and value|length < 10 %} <img class="img-responsive" src="/media/photos/{{ image }}.jpeg" style="width:40mm !important" /> {% endif %} … -
username and email interchanged for social user
I am using google oauth2 for social authentication, I get the user's username and email and save it on my models, but the username and email fields are being swapped. What is causing such a problem? models.py class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) # is_authenticated = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) auth_provider = models.CharField(max_length=225, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.email def tokens(self): refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } register.py def register_social_user(provider, user_id, email, name): filtered_user_by_email = User.objects.filter(email=email) if filtered_user_by_email.exists(): if provider == filtered_user_by_email[0].auth_provider: registered_user = authenticate( email=email, password=os.environ.get('SOCIAL_SECRET')) return { 'username': registered_user.username, 'email': registered_user.email, 'tokens': registered_user.tokens()} else: raise AuthenticationFailed( detail='Please continue your login using ' + filtered_user_by_email[0].auth_provider) else: user = { 'username': generate_username(name), 'email': email, 'password': os.environ.get('SOCIAL_SECRET')} user = User.objects.create_user(**user) user.is_verified = True user.auth_provider = provider user.save() print('user',user) new_user = authenticate( email=email, password=os.environ.get('SOCIAL_SECRET')) print ('new:',new_user) return { 'id':user.id, 'email': user.email, 'username': user.username, 'tokens': user.tokens() } Here is the link to the full code: https://github.com/abinashkarki/rest_framework_authentication -
django restframework try using djoser to create multiple model get unexpected keyword argument
Im new to django rest-framework and Djoser and learning, trying to create a user with profile using UserCreateSerializer in Djoser. I followed bunch of tutorials to create a Serializer with two models and when trying to create a user in browser api end with: get unexpected keyword argument in the template, i know what the error means but i dont know how should i implement it or what did i do wrong. here is my model: from django.db import models # Create your models here. from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): account_Option = ( ('P', 'is_something'), ('L', 'is_somethingelse'), ) ac_type = models.CharField(_("Status"), max_length=1, choices=account_Option, default='P', help_text=_('account Option')) class MyClass(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, editable=False) my_field = models.CharField(help_text=_('Enter your...'), max_length=10, unique=True, null=True, blank=True, ) and serializers: from djoser.serializers import UserSerializer as BaseUserSerializer, UserCreateSerializer as BaseUserCreateSerializer from rest_framework import serializers from django.conf import settings from core.models import MyClass User = settings.AUTH_USER_MODEL class MyClassSerializer(serializers.ModelSerializer): class Meta: model = MyClass fields = ['my_field'] class UserCreateSerializer(BaseUserCreateSerializer): profile = MyClassSerializer() class Meta(BaseUserCreateSerializer.Meta): fields = ['id', 'username', 'password', 'email', 'first_name', 'last_name', 'profile'] def create(self, validated_data): profile_data = validated_data.pop('profile') # User_model = self.User.objects.create(**validated_data) User_model = User.objects.create(**validated_data) new_profile = self.profile.objects.create( user=User_model, **profile_data) return … -
Django - delete M2M field but keep join table
is it possible to remove an M2M field from a model and keep the joining table? context: I am trying to add through model to existing M2M field like described in this post But doing it simply like this will result in a production app crash when accessing the old table during deployment - short window between migration and code update, when old code will try to access a new database for a few moments - without the old table in it. -
How to update a value in database after n seconds of query made? Django
I have a model in which I created a field "bargain price " as shown in Models.py: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() bargainprice = models.FloatField(default=0) somewhere in my template I take input from user and update the bargain price using ajax as shown below: $.ajax({ url: "/bargain/" + id + "/", data: { csrfmiddlewaretoken: window.CSRF_TOKEN, 'input': parseFloat(input) }, type: 'POST' }).done(function (response) { alert(response); }); and I successfully update the price by the view: def Bargain(request, uid): if request.method == 'POST': item = Item.objects.get(id=uid) item.bargainprice = request.POST['input'] item.save() message = 'update successful' return HttpResponse(message) else: return HttpResponse("this is not working..") **Now what I want. I want to reset this Bargain_price updated value to default after n seconds ** Can anyone suggest to me the method to do it? Thanks in advance. -
Concat or join query values
need to join objects values from query. For example: objects = Book.objects.all() and Book objects have id as a field So need to make a query with all ids of objects array, but not as a array of ids. Need to have something like this <QuerySet '1, 2, 3, 4'> -
Strange behave of VS code terminal while CMD works well
I have tried to install django-crispy-forms in VS Code terminal but it shows install django-crispy-forms': The system cannot find the file specified. After that, I tried installing the package in the CMD terminal and it worked well and was installed. Now it if run the project from VS Code terminal then shows no module found. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\MH Habib\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\MH Habib\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "H:\Django web\NewProject\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "H:\Django web\NewProject\env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "H:\Django web\NewProject\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "H:\Django web\NewProject\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "H:\Django web\NewProject\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "H:\Django web\NewProject\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "H:\Django web\NewProject\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "H:\Django web\NewProject\env\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\MH Habib\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crispy_forms' Restart VS code several times but show the error every time. On the … -
How to get the error of no such table exist in Django API
I have the following codes @api_view(['DELETE']) def selected_device_delete(request,pk=None): if pk != None: #Open connection to database cursor = connection.cursor() #Removing related tables table1 = 'dev_interface_' + str(pk) table2 = 'dev_route_list_' + str(pk) table3 = 'dev_neighbour_list_' + str(pk) dropquery1 = f"DROP TABLE {table1}" dropquery2 = f"DROP TABLE {table2}" dropquery3 = f"DROP TABLE {table3}" cursor.execute(dropquery1) cursor.execute(dropquery2) cursor.execute(dropquery3) #Close connection to database cursor.close() device = Device.objects.filter(pk=pk) operation = device.delete() data = {} if operation: data["Success"] = "Successfully deleted" return Response(data) If user types an unknown pk which for example is 200 and the table does not exist, how do i get this error? I want to use this error and return a response like such table does not exist -
Django 3.2 Project with DB2 (IBM_DB driver)
Currently, I am working in developing a web application with Python 3.8.10, Django 3.2 and IBM_DB_DJANGO 1.5.0.0. When I am trying the first step to move from sqlite3 to DB2, I type the command: python manage.py migrate Unfortunately, I got the error as below django.db.utils.ProgrammingError: Statement Execute Failed: [IBM][CLI Driver][DB2/AIX64] SQL0401N The data types of the operands for the operation "IN" are not compatible or comparable. SQLSTATE=42818\r SQLCODE=-401 There are tables being created and including: AUTH_GROUP, AUTH_GROUP_PERMISSIONS, AUTH_PERMISSION, DJANGO_MIGRATIONS. There is one records added in the Django_migration only. I would like to know how I could confirm whether it is good to use. Thanks in advance. -
Failed - network error when downloading a file
I have configured the apache webserver for my Django application for https redirection and its working fine. When i was testing my application I found out that it sometimes shows Failed -Network error when trying to download a XLSX file .Downloading a tarfile does not give any error.. Tried in different browser but got the same result.. But when I download it via Free download manager it works fine.. Not sure what is wrong Ubuntu - 20.04 python - 3.6.9 Please Help. Thanks -
Django Model Design Difference: link multiple simple models
I am designing Django models and would like some feedback on differences between different design schemas. Also, currently I am working only with Django Admin so my confusion might be coming from there. Let's suppose I have model Industry, which has multiple Locations. Banking -> US Banking -> UK Banking -> Japan ... Also, I have another model where industry and location is selected by user (on the website). So, if Banking is selected I want to show only locations that are available for banking. Here's the basic design I have already implemented (for demo purpose): class Industry(models.Model): """ Model representing industries. """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this industry and location') name = models.CharField(blank=False,null=True,max_length=100,verbose_name="Industry") location = models.CharField(blank=False,null=True,max_length=100,verbose_name="Location") def __str__(self): field_values = get_val(self) #this functions works return ' '.join(field_values) class Meta: db_table = 'Industry' class Select(models.Model): """ Model Select """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID Select') industry = models.ForeignKey('Industry',on_delete=models.SET_NULL,related_name='+',blank=False,null=True,max_length=100,verbose_name="Industry") location = models.CharField(blank=False,null=True,max_length=100,verbose_name="Location") def __str__(self): field_values = get_val(self) return ' '.join(field_values) class Meta: db_table = 'Select' As a superadmin, let's suppose in Industry model I create Banking->USA, Banking->UK and in Select model I want to choose Banking, and for the location I want to select from available locations … -
How to translate django model field's help_text with variable
models.py: from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ class MyModel(models.Model): name = models.CharFiled(help_text=_("Name cannot contain %s") % settings.SPECIAL_CHARS) django.po: msgid "Name cannot contain %s" msgstr "xxxxx" Not working. -
validated_data is returning empty OrderedDict for nested fields with Django Rest Framework
Can someone help me figure out why some fields are not parsed correctly using nested serialziers with Django and Django-rest-framework? I've researched the issue on SO, and the only cause for this happening I've found is that the request is sent as Form-data and not Json, but I've checked that response.content_type equals application/json - so this shouldn't be the issue here. This is what my validated_data looks like (note that 3 of the fields only contain an empty OrderedDict): {'author': OrderedDict(), 'disclosed_at': datetime.datetime(2021, 10, 19, 12, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), 'event_date': datetime.date(2021, 10, 20), 'event_type': OrderedDict(), 'subject_companies': [OrderedDict()]} This is what request.data looks like (where you can see that all fields are there, and having the fields specified in each serializer): {'event_type': {'pk': 1}, 'author': {'pk': 1}, 'event_date': '2021-10-20', 'disclosed_at': '2021-10-19 12:00:00', 'subject_companies': [{'pk': 1}]} This is where I'm sending the request from (test.py): def test_authenticated_creating_event_for_own_organisation(self): view = NewsEventList.as_view() url = reverse('news_event_list', kwargs={'pk': self.organisation.pk}) request = self.client.post(url, data=json.dumps(self.payload_event), content_type='application/json') force_authenticate(request, user=self.user) response = view(request, pk=self.organisation.pk) json_data = json.dumps(response.data, indent=4) json_ = (json.loads(json_data)) self.assertEqual(response.status_code, 201, 'Should return 201 - Created') return response I have the following serializers class OrganisationNameSerializer(ModelSerializer): class Meta: model = Organisation fields = ['pk'] class EventTypeSerializer(ModelSerializer): class … -
if/else to change password for app user and social user
I am trying to build a functionality to change passwords, there are two users: registered through my app registered via social authentication. For the first case old password will be asked and then a new password to change the password for the second case since they don't have a password for the app when they want to change the password for the first time only the new password will be asked, and after that old password will also be asked. Below is what I have tried so far, the first test case passes but the second also requires old and new passwords! What is causing that? Is this the right way to approach the problem? views.py class ChangePassword(APIView): serializer_class=ChangePasswordSerializer serializer_class2=ChangePasswordSerializer2 model = User permission_classes = [IsAuthenticated] def get_object(self, queryset=None): obj = self.request.user return obj def put(self,request, *args, **kwargs): self.object = self.get_object() if self.object.auth_provider != "email": serializer = self.serializer_class2(data=request.data) if serializer.is_valid(): self.object.set_password(serializer.data.get("new_password")) self.object.auth_provider == "email" self.object.save() response={ 'status':'success', 'code':status.HTTP_200_OK, 'message':"Password changed Successfully", } return Response(response) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: #check old password serializer = self.serializer_class(data=request.data) if serializer.is_valid(): if not self.object.check_password(serializer.data.get("old_password")): return Response({'error':["Wrong_password"]}, status=status.HTTP_400_BAD_REQUEST) self.object.set_password(serializer.data.get("new_password")) self.object.save() response={ 'status':'success', 'code':status.HTTP_200_OK, 'message':"Password changed Successfully", } return Response(response) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class ChangePasswordSerializer(serializers.Serializer): model … -
Foreign key model values return same value
I have looked at all answer and nothing quite helps me. I have a model Group class Group(models.Model): group_num = models.CharField(max_length=100) group_name = models.CharField(max_length=200) type = models.CharField(max_length=200) def __str__(self): return self.group_name and a model Subgroup group class Subgroup(models.Model): sub_group_num = models.CharField(max_length=100) sub_group_name = models.CharField(max_length=200) group_number = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='group_numbers', verbose_name="Group Number") group_in_name = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='group_names', verbose_name="Group Name") def __str__(self): return self.sub_group_name when I reference the group_number and group_in_name from subgroup they give the same value in the template -
How to combine 2 arrays in python & django?
I currently have 1 array called ageSelect that looks like so : ageSelect = [] for row in xAgeSelect: rdict = {} rdict["Account"] = row[0] rdict["Name"] = row[1] rdict["Balance"] = row[2] rdict["E-mail"] = row[3] ageSelect.append(rdict) and another array that has the called thirtyDay that looks like to : for row in thirtyDay: rdict = {} rdict["30day"] = row[0] XthirtyDay.append(rdict) The problem is that both arrays are appended through different date arguments and I need to combine them to look something like this array3 = ["Account" , "Name" , "Balance" , "E-mail" , "30day"] So that when I call it in a for loop (that writes to .xlxs) it can look like this: for x in arr3: data4 = ( x["Account"], '*', ' ','','','',x["30day"],x["Balance"]-x["30day"],x["Balance"],'',x["Name"],x["E-mail"] ) I have tried using numpy for this : like so arr3 = np.dstack(ageSelect, XthirtyDay) -
Override serializer fields by pattern in Django
So I have a Django project with Django REST Framework with large number of models. For frontend to be user friendly I should display not only related object's id but also name. My idea for the solution was to replace all the PrimaryKeyRelated fields with StringRelatedFields in serializers on response. As the number of models is large I decided to make a single abstract serializer/mixin and intercept field creation replacing the field if is of correct type. This is how far I got up to now: class AbstractSerializer(serializers.ModelSerializer): class Meta: model: AbstractModel = AbstractModel read_only_fields: list = [ 'created_at', 'created_by', 'modified_at', 'modified_by', 'is_deleted', 'deleted_at', 'deleted_by' ] + ['is_active'] if 'is_active' in [field.attname for field in model._meta.fields] else [] abstract: bool = True def to_representation(self, instance): serializer = AbstractRequestResponseSerializer(instance) return serializer.data class AbstractRequestResponseSerializer(AbstractSerializer): class Meta(AbstractSerializer.Meta): pass @classmethod def _get_declared_fields(cls, bases, attrs): fields = [(field_name, attrs.pop(field_name)) for field_name, obj in list(attrs.items()) if isinstance(obj, Field)] fields.sort(key=lambda x: x[1]._creation_counter) new_fields = [] for field in fields: if isinstance(field, PrimaryKeyRelatedField): field = StringRelatedField(source=field.source, required=False) new_fields.append(field) fields = new_fields known = set(attrs) def visit(name): known.add(name) return name base_fields = [ (visit(name), f) for base in bases if hasattr(base, '_declared_fields') for name, f in base._declared_fields.items() if name … -
Using Django with db.sqlite3 with persistent volume in a Kubernetes pod outputs - django.db.utils.OperationalError: unable to open database file
I'm trying to deploy a small Django app, that creates its own db.sqlite3 database, in a Kubernetes pod. When doing so without a persistent volume to save the db.sqlite3, it works fine but when trying to save it in a persistent volume, the pod outputs django.db.utils.OperationalError: unable to open database file The first problem I had is when these commands: python ./manage.py migrate sh -c "envdir ${ENVDIR} python manage.py collectstatic" were run in the Dockerfile. After mounting the volume, none of my files would be visible. I learned that K8s volumes behaved differently from docker volumes and my solution was to put the commands in a shell script and execute it in the CMD or ENTYPOINT. This created the files after mounting and were visible but still doesn't help with the current problem. I tried using a persistent volume, tried using a hostPath defined volume and even tried using an initContainer that has the same image as the app, only it first sets the permissions to 777 for db.sqlite3 and executes the two commands above, but it can't even start for some reason. Here's the deployment.yaml: apiVersion: apps/v1 kind: Deployment metadata: name: myapp labels: app: myapp namespace: app-prod spec: replicas: …