Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django models slug mixin with unique constrain handling
I have three models Book, Part, Chapter, in my models.py that uses the SlugField. For the Book class, I have written a slug handler in the custom save method that checks if an object exists with the slug. And when it does, it makes it unique by appending a count to it. How do I rewrite the block inside Book's to SlugMixin so that I can use for the rest of the models? models.py ... class SlugMixin(models.Model): slug = models.SlugField(max_length=50, unique=True) class Meta: abstract = True class Book(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) def save(self, *args, **kwargs): if not self.pk and not self.slug: slug = slugify(self.title, allow_unicode=True) slug_exists = True counter = 1 self.slug = slug while slug_exists: try: slug_exists = Book.objects.get(slug=slug) if slug_exists: slug = self.slug + '_' + str(counter) counter += 1 except Book.DoesNotExist: self.slug=slug break class Part(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='parts') title = models.CharField(max_length=30) slug = models.SlugField(max_length=30, unique=True) class Chapter(models.Model): part = models.ForeignKey(Part, on_delete=models.CASCADE, related_name='chapters') title = models.CharField(max_length=40) slug = models.SlugField(max_length=40, unique=True) -
django serializers validated_data.pop('grocery_menu_price') is not working properly
having a problem in Validated_data.pop() i am using django and python3 my views- class RestaurantMenuView(viewsets.ModelViewSet): def create(self,request): ''' add restaurant menu item detail ''' serializer = AllMenuSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({"success":True,"message":"Created sucessfully", "data":serializer.data}, status=status.HTTP_201_CREATED) def list(self,request): try: print(request.GET.get('restaurant')) restaurants = Restaurant.objects.get(id=request.GET.get('restaurant')) serializer = RestoActiveMenuSerializer(instance=restaurants) return Response({"success":True,"restaurants_menu":serializer.data}, status=status.HTTP_200_OK) except Exception as e: print("Exception",e) return Response({"success":False,"message": "Something went wrong!"}, status=status.HTTP_400_BAD_REQUEST ) here is my serilizer class - class GroceryMenuUnits(serializers.ModelSerializer): measuring_unit = serializers.SerializerMethodField() def get_measuring_unit(self,obj): return Measurements.objects.get(measurement=obj.measuring_unit).measurement if Measurements.objects.get(measurement=obj.measuring_unit).measurement else None class Meta: model = GroceryMeasurmentsQuantity fields = '__all__' class GroceryAllMenuSerializer(serializers.ModelSerializer): grocery_menu_price = GroceryMenuUnits(many=True) def create(self, validated_data): grocery_menu_data = validated_data grocery = validated_data.pop('grocery') category = validated_data.pop('category') grocery_menu_price = validated_data.pop('grocery_menu_price') print(grocery_menu_price) grocery_menu = GroceryMenu.objects.create(grocery=grocery,**grocery_menu_data) for category in category: grocery_menu.category.add(category) for unit in grocery_menu_price: print('quantity-------------------',unit['quantity'],unit['measuring_unit']) measurement = unit['measuring_unit'] if unit['measuring_unit'] else None GroceryMeasurmentsQuantity.objects.create(grocery_menu=grocery_menu,measuring_unit=measurement,**unit) grocery_menu.save() return grocery_menu class Meta: model = GroceryMenu fields = ('grocery','category','item_name','type_item','image','description','stock','available','grocery_menu_price') here when i am printing print(grocery_menu_price) then its printing only price and quantity- > [OrderedDict([('quantity', Decimal('2.00000')), ('price', > Decimal('250.00000'))]), OrderedDict([('quantity', > Decimal('1.00000')), ('price', Decimal('250.00000'))])] Internal > Server Error: /api/restaurant/v2/grocery-menu/ Traceback (most recent > call last): File > "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", > line 34, in inner > response = get_response(request) File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/django/core/handlers/base.py", > line 115, in _get_response > response = self.process_exception_by_middleware(e, request) File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/django/core/handlers/base.py", … -
Is there a list of Django imports? [closed]
I would like to create a flashcard deck with Django imports on memrise.com. So far I have this list: https://www.memrise.com/course/5736049/django-imports But this, I created it manually. Is there a complete list of all imports so that I can bulk add them in the deck and every time I (or anyone who uses this flashcard deck to memorize it) don't have to look up on search engines and just have them in mind. Thanks in advance. -
Django template select specific value with hide and show
This is my model and form with my choices: class Method(models.Model): principle = models.CharField(choices=PRINCIPLE_CHOICES, max_length=2) method = models.CharField(choices=METHOD_CHOICES, max_length=4) class PartMethodForm(forms.ModelForm): principle = forms.ChoiceField( widget=forms.Select( attrs={'class': 'btn btn-primary'}), choices=PRINCIPLE_CHOICES) method = forms.ChoiceField( widget=forms.Select( attrs={'class': 'btn btn-primary'}), choices=METHOD_CHOICES) METHOD_CHOICES=( ('1.1','Method 1.1'), ('1.4','Method 1.4'), ('2.2','Method 2.2'), ('10.4','Method 10.4'), ('11.3','Method 11.3') ) PRINCIPLE_CHOICES=( ('1','Principle 1'), ('2','Principle 2'), ('10','Principle 10'), ('11','Principle 11') ) In my view I am passing my form and filtered lists of my methods and principles that are possible to select e.g. method = ['1.1','2.2','10.4'] principle = ['1','3'] What I would like to achieve is the following: select a principle (principles that are not in the list should be disabled for selection) when principle selected then show only possible methods e.g. if principle 1 -> methods 1.1 and methods 1.4 possible select a method (methods that are not in the list should be disabled for selection) Can someone help? I came up only with this approach: {% block content %} <div class="container"> <script type="text/javascript"> function showmethod() { if (document.getElementById('1').checked) { document.getElementById('div0').style.display = 'block'; document.getElementById('div').style.display = 'block'; } else { document.getElementById('div').style.display = 'none'; document.getElementById('div0').style.display = 'none'; } } </script> <h5><b>Choose principle</b></h5> <form class="mt-5" method="post" name="method-form" id="method-form"> {% csrf_token %} <div class="col col-md-12"> … -
Django + Nginx + uWSGI: 500 Internal Server Error
I get this Error when i send a form with a picture and when i send it without a picture it's work, in a localhost this project work normely. this is a message i get when i send a form enter image description here this message is getted with postman. I follow this guid to deploy django with nginx and uWSGI Setting up Django and your web server with uWSGI and nginx -
Django multi select ManyToMany widget like the admin group multi select
I am trying to use the FilteredSelectMultiple widget inside of my admin panel similar to how the default groups and user permissions are. enter image description here I have tried to research and it seems most people are using this outside of the admin panel. I still want to use this in my admin panel. I have a couple multi select fields that contain 200+ items and I have to "ctrl" click to select multiple. If I miss the "ctrl" then it resets everything. Was hoping it was easy to use this widget inside the admin panel since I am still learning Django. -
Access Django's Static files on Amazon S3 with 'same-origin' referrer policy
Since Django 3.0, SECURE_REFERRER_POLICY was added and also included on the python manage.py check --deploy command. In order to make to make my Django project read media files from Amazon S3, I previously had mine set to strict-origin-when-cross-origin, as well as a S3 policy allowing for the programmatic user to do everything and another policy that checked if the referrer header was set to my domain (similar to what's been described in this question Amazon S3 Bucket Policy Referer). But that was a very rudimentary hotlink protection and I was advised at the Django Forums to switch to same-origin. However, now my site can no longer get any of its asset files (403 Error) and navigating through django-storages and S3 docs searching for an answer has proved to be tough and fruitless so far. :( Here's what I currently have: On the Django side, I have django-storages configured with: AWS_DEFAULT_ACL = 'authenticated-read' SECURE_REFERRER_POLICY = 'same-origin' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' On AWS, I have the following policy (the access policy by referrer has been removed): { "Statement": [ { "Sid": "Allow programatic admin to handle bucket", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::xxxxxxxxxxxxxx:user/bucket-manager" }, "Action": "s3:*", "Resource": "arn:aws:s3:::bucket-name/*" } ] } The following … -
How modelform works with database and serializers in Python + Django?
I would like to know the internal working of modelforms with database and serializers in Python + Django. Can anyone briefly explain? -
I faced an error said 'Reverse for 'login' not found. 'login' is not a valid view function or pattern name. '
this is my urls.py path('login/', views.login, name="login"), path('signOut/', views.signOut, name= "signOut"), these are my views, I replaced 'login' in the signOut function with 'home' but I still have the same error. def login (request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request , username = username ,password = password) if user is not None: dj_login(request, user) return redirect ('home') context= {} return render (request , 'freelancing_app/login.html' ,context ) def signOut (request): logout(request) return redirect('login') -
Django filter many to many relation
I have problem with manyToMany models in django. I have structure like this: Table Project class Project(models.Model): name = models.CharField(max_length=100, blank=True, null=True) description = models.TextField(blank=True, null=True) ordernr = models.IntegerField(db_column='orderNr', blank=True, null=True) # Field name made lowercase. map = models.ManyToManyField(Image, through='ProjectMapImage') class Meta: managed = False db_table = 'Project' And table Image class Image(models.Model): url = models.CharField(max_length=100, blank=True, null=True) typeid = models.ForeignKey('ImageType', models.DO_NOTHING, db_column='typeId', blank=True, null=True) # Field name made lowercase. ordernr = models.IntegerField(db_column='orderNr', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'Image' ordering = ['ordernr'] Mapping table ProjectMapImage class ProjectMapImage(models.Model): projectid = models.ForeignKey(Project, models.DO_NOTHING, db_column='projectId', blank=True, null=True) # Field name made lowercase. imageid = models.ForeignKey(Image, models.DO_NOTHING, db_column='imageId', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'Project_Map_Image' Finally this is my view class ProjectListView(ListView): model = Project context_object_name = "projects" This view return all project and i have access to all linked images in HTML {% for image in project.map.all %} But I wanto to load only images with typeid for example 1. How can i filter this? -
How to pass the javascript variable value from one html page to the another html page?
I am creating the quiz application using JavaScript and Django. Actually entire logic was done in the JavaScript . For the quiz application ,I have a score variable that score variable value i am showing in the index.html as show below: resultCont.innerHTML = 'Your Score:- ' + score + '/80' ; Here score is the JavaScript variable. Another thing I need to store this score variable into my DB . So that I need to use the ajax to post the score variable to my views.py file where my function is running to submit the score along with username to the Django models. models.py: class Results(models.Model): username = models.CharField(max_length=50,default='') score = models.IntegerField() def __str__(self): return self.username Here I have taken the username and score variable . And the username is the foreign key. views.py def score(request): if request.method == 'GET': return render(request, 'quiz/html/end.html',{'form':Score()}) else: try: form = Score(data=request.POST) newscore = form.save(commit=False) newscore.owner = request.user newscore.save() return redirect('category') except ValueError: return render(request, 'quiz/html/end.html',{'form':Score(), 'error' :'please fill the form properly'}) end.html: Here I have used the form to submit the score along with name . I hidden the username so that user cannot change the name. <form method="POST"> {% csrf_token %} <div> … -
Still getting KeyError: 'SECRET_KEY' in my Django Project having set up environment variables
I created environment variables for my django project within my pipenv virtual envronment bin/activate (linux) or scripts\activate(windows) file , i made necessary changes in settings file as well as exiting and re activating the virtual environment but im still getting a keyerror (I'm working on a windows machine) variables in settings.py SECRET_KEY = os.environ['SECRET_KEY'] EMAIL_HOST_PASSWORD = os.environ['EMAIL_HOST_PASSWORD'] evnvironment variables in virtualenv\scripts\activate file export SECRET_KEY= "mysecretkey" export EMAIL_HOST_PASSWORD= "mypassword" error File "C:\Users\Dell\.virtualenvs\team-272-SMES-Server-dSgdZ4Ig\lib\os.py", line 673, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' -
Creating a web app in django that creates a video (with moviepy) and plays it: Where to start?
I would like to make a web application where a user can: click a button on a webpage to create a **random video (with moviepy) play that video back on the webpage click the button again to create a new **random video that replaces the existing one ** The random video will be created with a python/moviepy script that downloads a bunch of random video clips from the internet to a directory on my computer. It then compiles them into one video (.mp4 file). I've done the python script bit already which successfully creates the video file. To make the web app bit I have been recommended django and that's where I'm stuck! So far I have installed django and got to grips with the basics .. I have a home page that says "Hello world". My question is where do I go from here? How do I connect my python/moviepy script with django? What steps, apps, components etc, within django should I look into to make this thing? I'm new to coding and looking for some guidance. Thanks! -
Can we use python related api's on the Django templates?
I am new to Django and hence not having thorough knowledge about it. So I am facing a few errors in Django. Currently I am trying to print the type of a variable from the Django template html file as follows: <center><h2>The type of feature list report for version {%type(version)%} is<h2></center> For the above, I am getting the following error: Invalid block tag on line 9: 'type(version)'. Did you forget to register or load this tag? So what's going wrong here? How can we use the python related api's (like type(), strip(), get(), etc) from the html template files? I think inside the {% .... %} we can use python related evaluations. Am I right? Please throw some lights on this . -
Issues with two forms submission in django one after another
I'm working on forget password page in which the user first have to answer the question for enabling the textfields for creating new password. Here, I have two forms, One for security question and second for password and confirm password. Following is my forms.py from django import forms from .models import SecurityQuestions class PasswordForm(forms.Form): password = forms.CharField(disabled=True, widget=forms.PasswordInput(attrs={'placeholder':'New Password'})) password_confirm = forms.CharField(disabled=True, widget=forms.PasswordInput(attrs={'placeholder':'Re-enter Password'})) def clean(self, *args,**kwargs): password = self.cleaned_data.get('password') password_confirm = self.cleaned_data.get('password_confirm') if password and password_confirm: if password != password_confirm: raise forms.ValidationError('Password Mismatch') return super(PasswordForm, self).clean(*args, **kwargs) class PasswordVerificationForm(forms.Form): question = forms.ModelChoiceField(queryset=SecurityQuestions.objects.all(), empty_label=None, widget=forms.Select(attrs={'class':'form-control','id': 'sectxt'})) answer = forms.CharField(label='answer', widget=forms.TextInput(attrs={'placeholder':'Answer','id': 'anstxt'})) Following is my views.py from django.shortcuts import render, redirect from .forms import PasswordForm, PasswordVerificationForm from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.hashers import make_password from .models import SecurityQuestions from django.contrib import messages @login_required @csrf_exempt def password_reset(request): form = PasswordForm(request.POST or None) form1 = PasswordVerificationForm(request.POST or None) if request.method == 'POST': if request.POST.get("verify", False): question = request.POST.get('question') answer = request.POST.get('answer') print("question",question) print("answer",answer) check = SecurityQuestions.objects.get(id=question) #id=1 print(check.answer) if check.answer == answer: messages.success(request, 'Enter Your New Password', 'alert-success') form.fields['password'].disabled = False form.fields['password_confirm'].disabled = False else: redirect('/') messages.error(request, 'Incorrect Answer', 'alert-danger') if request.POST.get("create", False): if form.is_valid(): print("For Changing Password...") password … -
How to find which entry contains a string in Django + SQLite
I have a string s = "Hello, my name is Bob". I also have MyModel with name = models.CharField(). All the entries of MyModel are like this: MyModel(name="bob").save() MyModel(name="jack").save() MyModel(name="alice").save() Given s how do I find the first instance of MyModel? I'm aware of MyModel.objects.filter(name__icontains=s). That wouldn't work, since I'm not searching if name contains s but if s contains name. -
Mysql Architecture for Django Application
I am running a django application with MySQL database. It contains multiple celery tasks which have many read and write queries. Task of celery job is to fetch records from third party to temporary stage table and store data from stage table to main table. So, I want to know, what is the best suitable architecture for above use case in MySQL so that we can distribute data in MySQL efficiently (replication, partitioning etc.) -
Getting flake8 returned a non none zero code : 1 in docker
I was following this article. https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/#production-dockerfile In the Production Dockerfile section, the Dockerfile.prod file has these lines. # lint RUN pip install --upgrade pip RUN pip install flake8 COPY . /usr/src/app/ RUN flake8 --ignore=E501,F401 . When I run the below command, docker-compose -f docker-compose.prod.yml up -d --build I'm getting the below error. ERROR: Service 'web' failed to build: The command '/bin/sh -c flake8 --ignore=E501,F401' returned a non-zero code: 1 I'm not much aware of flake8, When I commented the 'RUN flake8 --ignore=E501,F401 .' line from the Dockerfile.prod file everything worked. Can anyone please tell me why I'm facing this issue. I'm not much aware of flak8 and I'm quite new to Docker too. Thanks. -
Push changes to data in one Django model to another
I writing an application that has a change control workflow. Users retrieve data for a particular month and then they make edits to it and there is a review phase where they can approve records. There are 2 identical tables a master and a staging table. When the user loads up the application they load data from the master table and can edit it in a crud grid. When they hit the stage button I want that data to get pushed inserted into the staging table. How do i tell my view to do that. The staging table doesnt have the associated records yet, i want the records that are sent back as part of the push to get inserted there rather than doing an update to the master table? Any advice would be greatly appreciated. -
What is the exact difference between get_list_or_404 and get_object_or_404 in Django?
I am slightly confused by the difference between get_list_or_404 and get_object_or_404 in Django. I am using the object one on getting posts of a particular user but would like to know more on how I could be using get_list_or_404. -
Django fails at sending e-mail in production but works in develoment
I have a django app running in google cloud that sends emails through gmail in production and development, but when I added a new app to the project, using another gmail account, it works in development, but not in production, which is really weird. Production settings.py EMAIL_HOST = os.getenv('EMAIL_HOST') EMAIL_PORT = os.getenv('EMAIL_PORT') EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') EMAIL_HOST_USER_MED = os.getenv('EMAIL_HOST_USER_MED') EMAIL_HOST_PSSWD_MED = os.getenv('EMAIL_HOST_PSSWD_MED') EMAIL_USE_TLS = True Sending email function for not working app def email(pedido): conexion = get_connection() conexion.password = settings.EMAIL_HOST_PSSWD_MED conexion.username = settings.EMAIL_HOST_USER_MED asunto = f'Solicitud pedido {pedido.codigo}' remitente = f'Lab_C403' destinatario = [pedido.proveedor.contacto] html_message = render_to_string( 'email_medicina.html', {'pedido': pedido, 'saludo': saludo} ) plain_message = strip_tags(html_message) send_mail( asunto, plain_message, remitente, destinatario, html_message=html_message, connection=conexion, fail_silently=False, ) As you can see, I change the email account and the password for it. Weirdly it works in development but not in production. I don't think gmail is blocking my server IP since it's a google's server. Also the other app using the default settings works. Any help guys? Thanks! -
Django Channels, Docker Compose, Errno 111] Connect call failed ('127.0.0.2', 6379)
I am following the Django Channels tutorial available at https://channels.readthedocs.io/en/latest/tutorial/part_2.html I am using docker-compose to build the redis server: docker-compose.yml redis: image: "redis:alpine" command: redis-server --requirepass letmein ports: - "6379:6379" volumes: - ./redis.conf:/usr/local/etc/redis/redis.conf environment: - REDIS_REPLICATION_MODE=master networks: node_net: ipv4_address: 127.0.0.2 networks: node_net: ipam: driver: default config: - subnet: 127.0.0.0/16 When attempting to test the connection with async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) I get the error `File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/asgiref/sync.py", line 120, in __call__ return call_result.result() File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 425, in result return self.__get_result() File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/usr/local/lib/python3.6/site-packages/asgiref/sync.py", line 180, in main_wrap result = await self.awaitable(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/channels_redis/core.py", line 299, in send async with self.connection(index) as connection: File "/usr/local/lib/python3.6/site-packages/channels_redis/core.py", line 835, in __aenter__ self.conn = await self.pool.pop() File "/usr/local/lib/python3.6/site-packages/channels_redis/core.py", line 73, in pop conns.append(await aioredis.create_redis(**self.host, loop=loop)) File "/usr/local/lib/python3.6/site-packages/aioredis/commands/__init__.py", line 175, in create_redis loop=loop) File "/usr/local/lib/python3.6/site-packages/aioredis/connection.py", line 113, in create_connection timeout) File "/usr/local/lib/python3.6/asyncio/tasks.py", line 339, in wait_for return (yield from fut) File "/usr/local/lib/python3.6/site-packages/aioredis/stream.py", line 24, in open_connection lambda: protocol, host, port, **kwds) File "/usr/local/lib/python3.6/asyncio/base_events.py", line 794, in create_connection raise exceptions[0] File "/usr/local/lib/python3.6/asyncio/base_events.py", line 781, in create_connection yield from self.sock_connect(sock, address) File "/usr/local/lib/python3.6/asyncio/selector_events.py", line 439, in sock_connect return (yield from fut) File "/usr/local/lib/python3.6/asyncio/selector_events.py", line … -
Including custom url with urlpatterns from Router in Django 3
Using Django 3, in my urls.py file I am defining the urlpatterns as shown below. I want to include both views from my router, but I would also like to display a few custom links. I have included an example that I am trying to make a redirection up one directory. However, when I go to view the page, only the link to myModels is there. How can I achieve this? router = routers.DefaultRouter() router.register('myModels', views.MyModelViewSet) url_list = list() url_list.append(path('home', RedirectView.as_view(url="../", permanent=False), name='home')) url_list.extend(router.urls) urlpatterns = [ path('', include(url_list)), ] -
problem with static django files on hosting
The problem is that on the hosting I do not have access to direct configuration of Apache. All I can do is work with it using .htaccess. Apache does not process my static files when Debug = False. my settings.py: STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"),] # STATIC_ROOT = '/home/acc_name/domains/site_name/public_html/static_all' # STATIC_URL = '/home/a0173508/domains/abiturient.jurac.ru/myproject/static' MEDIA_URL = '/media/' MEDIA_ROOT = '/home/a0173508/domains/abiturient.jurac.ru/myproject/media' my .htassecc DirectoryIndex site.wsgi index.html Options +ExecCGI AddHandler wsgi-script .wsgi RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /site.wsgi/$1 [QSA,PT,L] RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE] I tried adding RewriteCond %{REQUEST_URI} !^\/static_all\/ to the .htassecc but this did not help. collectstatic collects all files into the desired folder and everything works correctly when 'django.contrib.staticfiles' works with files. my urls.py urlpatterns = [ ### ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \ + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) folder structure: site_name -public_html ---static_all ---.htaccess ---site.wsgi -myproject ---app1 ---app2 ---myproject -----settings.py -----urls.py site.wsgi: import os, sys virtual_env = os.path.expanduser('/home/a0173508/python') activate_this = os.path.join(virtual_env, 'bin/activate_this.py') with open(activate_this) as f: exec(f.read(), {'__file__': activate_this}) sys.path.insert(0, os.path.join('/home/acc_name/domains/site_name/myproject')) os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
Why data gets stored on ephemeral file system on heroku and not in db.sqlite 3?
So, I deployed my django app for the first time on heroku. I noticed that the user registrations are saved temporarily in app/admin page for some time. This happens because heroku has a ephemeral file system. The data gets stored on a dyno's file system which when discarded also deletes the data in its filesystem. While my local server adds data to my db.sqlite3 file, the heroku server adds it to its own file system instead of db.sqlite3 file resulting in deletions after some time. Only the data which were intially stored in my db.sqlite3 file are the ones that remain permanently. Without using s3 bucket is it possible to resolve this issue so that any future registrations in my app on heroku live server are stored permanently (in my db.sqlite3 file like my local server does)? My settings.py file (databases code) I assume changes here in this block of code will be the only reason to change database storage settings. I can edit the question in future to add more of any code if needed to resolve the issue. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } If not possible, any enlightenment as to why …