Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting a variable from Django Form and directing user to view based off variable
I am new to Django and web programming and am trying to do something easy but am having a lot of trouble figuring out how to get it to work. Basically, I have a view that shows information about an object from a database. From following several Django tutorials, I access the page by typing in the URL: objectViewer/$objectID. The view/template then display attribute information plus the object on a map. I am now trying to create a form that will connect to this objectViewer/$objectID URL, such that it allows the user to search the database for an object based off it's name. The form itself works fine, but what I don't understand is how to redirect the user to objectViewer/ based off the information submitted to the form. The other thing involved in this is converting the name returned by the Form to the ID to redirect to objectViewer. I can do this in python but am not sure how this is all supposed to work together to get what I need... To overview, I have: objectViewer/$objectID URL that points to objectViewer view/template and: searchByName form which allows user to enter the object name How do I: Get name … -
Django model field alternative name
I have a model which store an API response. I want to pass a dict which contain response to update a model. class Currency_Trending_Info(models.Model): """Stores a market's last price as well as other stats based on a 24-hour sliding window.""" crypto_currency = models.ForeignKey(Crypto_Currency, on_delete=models.CASCADE) market = models.CharField(max_length=30, blank=True, null=False) last_volume = models.DecimalField(max_digits=18, decimal_places=9) last_volume_to = models.DecimalField(max_digits=18, decimal_places=9) last_trade_id = models.BigIntegerField() ... ... but API response format looks like: { ... 'TYPE':'5', 'MARKET':'CCCAGG', 'FROMSYMBOL':'BTC', 'TOSYMBOL':'USD', 'FLAGS':'4', 'PRICE':6276.14, 'LASTUPDATE':1539279469, 'LASTVOLUME':0.03845327, 'LASTVOLUMETO':239.21394734299997, 'LASTTRADEID':'52275450' ... } so my question is is a there way to define alternative name to a field or should I just change model fields to correspond API response e.g. lastvolume = models.DecimalField(max_digits=18, decimal_places=9) (and of course use the key.lower() to turn a key into a lower case string.) any suggestions are welcome -
Django historical record
I have got django model like class Payments(models.Model): class Meta(): verbose_name = 'Payment' verbose_name_plural = 'Payments' db_table = 'dj_payments' client = models.ForeignKey(Clients, verbose_name='Client', related_name='payments', blank=False, null=True, on_delete=models.PROTECT) amount = models.FloatField('Amount', blank=False, null=False, default=0) date = models.DateTimeField('Plan date', blank=True, null=True) fakt_date = models.DateTimeField('Fakt date', blank=True, null=True) project = models.ForeignKey(Projects, verbose_name='Project', related_name='payments', blank=True, null=True) history = HistoricalRecords() And i have history. I want to create a model with a link to each entry to the history, i. a model with a comment field for field - date. I try like that: class PaymentsComments(models.Model): comment = models.TextField('Comment', blank=True, null=True) payment = models.ForeignKey(Payments.history, verbose_name='Comment', related_name='payments_comments', blank=True, null=True, on_delete=models.PROTECT) history = HistoricalRecords(history_change_reason_field=models.TextField(null=True, blank=True)) -
Django REST Serializer removes dictionary content when converting to Ordered Dict
I'm trying to serialize the received json and use django's built in validator. When I access the validated data, some of the content of my dictionary are lost and only a key-value pair remains. Pls help. json: {'start_date': '2018-10-11', 'end_date': '2018-10-26', 'shifts': [{'supervisor': '8', 'type': 'A', 'drivers_assigned': [{'driver': '2', 'shuttle': '1', 'deployment_type': 'E'}]}, {'supervisor': '9', 'type': 'P', 'drivers_assigned': [{'driver': '3', 'shuttle': '2', 'deployment_type': 'R'}]}]} when I serialize it, the array contents from drivers_assigned are reduced to just OrderedDict[{'deployment_type':'E'] and it gives me a key error when I pop the other supposed contents serialized: OrderedDict([('shifts', [OrderedDict([('drivers_assigned', [OrderedDict([('deployment_type', 'E')])]), ('type', 'A'), ('supervisor', )]), OrderedDict([('drivers_assigned', [OrderedDict([('deployment_type', 'R')])]), ('type', 'P'), ('supervisor', )])]), ('start_date', datetime.date(2018, 10, 11))]) views.py @staticmethod def post(request): data = json.loads(request.body) schedule_serializer = ScheduleSerializer(data=data) if schedule_serializer.is_valid(): schedule = schedule_serializer.create(validated_data=schedule_serializer.validated_data) print(schedule_serializer.errors) return Response(data={ "start_date": schedule.start_date, "end_date": schedule.end_date }, status=status.HTTP_200_OK) else: return Response(data={ "errors": schedule_serializer.errors }) serializers.py def create(self, validated_data): shifts_data = validated_data.pop('shifts') schedule = Schedule.objects.create(**validated_data) schedule.end_date = schedule.start_date + timedelta(days=14) # start_date + 14 days = 15 days (changed to +15 since every 15 days) schedule.save() new_sched = Schedule.objects.get(id=schedule.id) # gets django object to be used for shift_data in shifts_data: drivers_data = shift_data.pop('drivers_assigned') shift = Shift.objects.create(schedule=new_sched, **shift_data) for driver_data in drivers_data: shuttle_id = … -
django ORM Q object
what is the difference between : books = Book.objects.filter(name__in=names,film__isnull=True) books = books.union(Book.objects.filter(name__in=names,film__date__lte=date)).distinct("id") VS from django.db.models import Q books = Book.objects.filter(Q(name__in=names),Q(film__date__lte=date)| Q(film__isnull=True)).distinct(id) thx -
Django-storages upload FileField and ImageField to Dropbox
(Django 2.0, Django Rest Framework 3.8, Python 3.6, Django Storages 1.7, Dropbox 9.1) I'm trying to upload a file to the Dropbox App Folder I've created, but I run into the same error at every attempt: C:/TrainerPics/UI_4.png' did not match pattern '(/(.|[\r\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)' On the Dropbox dashboard from desktop, the folder I want to upload to is shown as: Dropbox > Apps > DjangoAppNameHere Here's my setup in settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = 'some_token_here' where storages is also listed in installed apps. Here's the model field I'm trying to upload: trainer_profile_pic = models.ImageField(upload_to="TrainerPics/", null=True, blank=True) I've tried this both with and without the / character, and tried this using upload_to=DjangoAppNameHere both with FileField and ImageField with no success. The documentation for Dropbox is rather sparse in the django-storages package, and doesn't describe how to set up a field to get it working. Any help is greatly appreciated. -
Python: ImportError: No module named root.settings.dev.local
I got a weird error when i try to "python manage.py runserver" at my parent directory for my web app. Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/Users/admin/ENV/lib/python2.7/site-packages/django/core/management/init.py", line 364, in execute_from_command_line utility.execute() File "/Users/admin/ENV/lib/python2.7/site-packages/django/core/management/init.py", line 308, in execute settings.INSTALLED_APPS File "/Users/admin/ENV/lib/python2.7/site-packages/django/conf/init.py", line 56, in getattr self._setup(name) File "/Users/admin/ENV/lib/python2.7/site-packages/django/conf/init.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Users/admin/ENV/lib/python2.7/site-packages/django/conf/init.py", line 110, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/init.py", line 37, in import_module import(name) ImportError: No module named root.settings.dev.local Can anyone point me in the right direction to solve this? -
Problem with AUTH_LDAP_REQUIRE_GROUP in Django
I am using OpenLDAP and I would like to connect it to Django using django_auth_ldap.I have tried many options but couldn't find solution. I am trying to login with the user test_user which was added to the group test_group on ldap. when i am trying to login without AUTH_LDAP_REQUIRE_GROUP="" and AUTH_LDAP_USER_FLAGS_BY_GROUP ={..} in settings.py i am getting permission denied error. 11/Oct/2018 15:58:01] "POST /accounts/login/ HTTP/1.1" 302 0 Forbidden (Permission denied): /events/timeline/ [11/Oct/2018 15:58:02] "GET /events/timeline/ HTTP/1.1" 403 22 but when i am trying to login with AUTH_LDAP_REQUIRE_GROUP and AUTH_LDAP_USER_FLAGS_BY_GROUP in settings.py,getting this... 11/Oct/2018 16:03:00] "GET /accounts/login/ HTTP/1.1" 200 1063 [11/Oct/2018 16:03:34] "POST /accounts/login/ HTTP/1.1" 200 1063 settings.py AUTH_LDAP_SERVER_URI = "ldap://ldap.example.com" AUTH_LDAP_BIND_DN = 'cn=admin,dc=example,dc=com ' AUTH_LDAP_BIND_PASSWORD = ' ' AUTH_LDAP_USER_SEARCH = LDAPSearch( "ou=people,dc=example,dc=com, ldap.SCOPE_SUBTREE, '(uid=%(user)s)', ) AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'cn=test_user,ou=people,dc=example,dc=com', ldap.SCOPE_SUBTREE, '(objectClass=posixGroup)', ) AUTH_LDAP_GROUP_TYPE = PosixGroupType() AUTH_LDAP_REQUIRE_GROUP = 'cn=test_group,ou=group,dc=example,dc=com' AUTH_LDAP_USER_ATTR_MAP = { 'first_name': 'displayName', 'last_name': 'sn', 'email': 'mail', } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active":'cn=test_user,ou=people,cn=test_group,ou=group,dc=example,dc=com, } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_TIMEOUT = 3600 AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) $ ldapsearch -v -W -x -D "cn=admin,dc=example,dc=com" -p 389 -h ldap.example.com -b "dc=example,dc=com" # example.com dn: dc=example,dc=com dc: example objectClass: domain # people, example.com dn: ou=people,dc=example,dc=com ou: people objectClass: organizationalUnit # group, … -
How to use SearchRank when SearchVectorField in table
For performance reasons I am using a SearchVectorField to precompute store the SearchVector representations of the content in my Django-based full text search engine: class Page(models.Model): content = models.TextField() sv = SearchVectorField() I'd like to be able to sort search results by rank, but I can't get the basic annotation to work. q = SearchQuery(string) pages = Page.objects.filter(sv=q).annotate(rank=SearchRank('sv', search_query))... This fails with "ProgrammingError: function to_tsvector(tsvector) does not exist." It doesn't seem to recognize that the column 'sv' is already a SearchVector. I took a look at the source code for SearchRank, and I can't figure out how to override it from calling SearchVector given that I am passing in a plain string. Is there any way to implement this without having to resort to raw SQL? Thanks! -
Can i incorporate my Python script on a Webpage using Django?
I'm really new to Python in general and i was learning about python for web developing and django. I made a simple Python scripts which outputs some data every second, i was looking for a way to have this data printed on a dynamic web page, this is how i found about Django. From what i understood, Django is a library for web developing with Python, so i think it could be what i'm looking for. My question is: how would exactly Django work for this? Could i just "incorporate" my script into my django project and then use django for the frontend? -
Multiple view set into router Django rest framework
I have a problem with DRF I have a model from django.contrib.sites.models import Site class Person(models.Model): site = ForeignKey(Site, on_delete=models.CASCADE) I want to create a viewset and serializer and I want to get the specific url: /api/sites/{pk}/persons/ And get all persons that They have associate site Or /api/sites/{pk}/persons/{pk} How can I do? -
User model with static set of related models
Say I have a User model in django and I want to add some achievements to users. So I've created an Achieve model: class Achive: type = .... value = .... status = BooleanField(default=False) I want all those achieves be a static set of models for every user (20 instances, for example) with ability to delete old and create new achieves. The problem is how to do it. Expected flow is: 1) user granted to use achievement system; 2) user got all those achieves (in admin panel shows like a table); 3) in admin panel per user I can change status of every achieve (affects only on edited user); 4) if new Achieve instance is created — add to all users who have achievements; 5) if existed Achieve instance has been deleted — remove from all users; Solutions with I came up: 1) use Achieve model with jsonfield. store achieves in json like dictionary, use custom widget for admin panel to show checkboxes to change status). But where to store global set of achievements to create new/delete old ones? how to manage it? 2) use many to many field to Achieve and Achieve model without status. Why: if relation between … -
Django order queryset by time starting in a specific hour with sending other results at last
I have the following django query: views.some_model.objects.all().order_by('start') This works fine. The result comes like this: {00:00, 00:30, 02:03, 04:00, 05:33} What if I need it to start the order_by from a specific hour and sending the rest to the last (also ordered)? like this: {02:03, 04:00, 05:33, 00:00, 00:30} I know that I can make two queries (one starting from the time that I need, the other for the last part), but is there a more pythonic way? -
How to make a validate_data field optional?
I am trying to create a RESTful api endpoint for creating a new user. And this is what I put in my serializer.py class UserSerializer(serializers.ModelSerializer): Class Meta: model = User field = '__All__' def create(self, validated_data): newUser = User.objects.create( name = validated_data['name'], division = validated_data['division'] image = validated_data['image'] ) return newUser; Now what I want to do is I want to make the division optional, for example, if the input division is "Education" then put is as education is my database table; But make it empty if there's no input. How can realize this? -
Django timeslots for appointments in different time zone
I have an appointment app which let us put timeslots and date available in django admin and then let the clients book thoses dates/timeslot for appointments. The thing is that in django i enter an available event the 10th october at 20:30:00pm but then the user might not be in the same country so the date and time might vary. how can i make the date-time change depending on the user location so they see the available time as their time, and the booking get saved properly here are the models: class TimeSlots(models.Model): start = models.TimeField(null=True, blank=True) end = models.TimeField(null=True, blank=True) class Meta: ordering = ['start'] def __str__(self): return '%s - %s' % (self.start.strftime("%I:%M %p"), self.end.strftime("%I:%M %p")) class Event(models.Model): event_date = models.DateField() start = models.ForeignKey(TimeSlots, on_delete=models.CASCADE, verbose_name='Slot Time', null=True) available = models.BooleanField(default=True) class Meta: verbose_name = u'Event' verbose_name_plural = u'Event' def __str__(self): return str(self.event_date) def get_absolute_url(self): url = reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name), args=[self.pk]) return u'<a href="%s">%s</a>' % (url, str(self.start)) class Patient(models.Model): event_date = models.DateField(null=True) patient_ID = models.AutoField(primary_key=True) patient_name = models.CharField(max_length=60, null=True, blank=True) phone_number = PhoneNumberField(blank=True, null=True) email = models.EmailField() event = models.OneToOneField(Event, on_delete=models.CASCADE, null=True, blank=True) start = models.ForeignKey(TimeSlots, on_delete=models.CASCADE, null=True, verbose_name='Slot time') paid = models.BooleanField(default=False) skype_key = models.CharField(max_length=60, null=True, blank=True) … -
PostGIS & Gdal to Alpine Dockerfile
I am trying to setup a PostGis Db for a Django project within a Docker Image. Specifically, I'm using the DockerFile from cookiecutter-django. The Dockerfile is building the image from python:3.6-alpine How can I install Gdal to Alpine? I'm new to Alpine so I'm not sure where to find the right Gdal library to add to the image setup - RUN apk update \ # psycopg2 dependencies && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ # Pillow dependencies && apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev \ # CFFI dependencies && apk add libffi-dev py-cffi \ # Translations dependencies && apk add gettext \ # https://docs.djangoproject.com/en/dev/ref/django-admin/#dbshell && apk add postgresql-client -
Django exception when submitting on Canvas LTI app
I'm using python 3.7 with Django 2.0.6 and django_rq 1.2.0. The LTI connects to my localhost venv on port 8000. I can run the localhost venv fine and connect to Postgres to save new assignment creations but when I press submit to run the local code so it will make comparisons to libraries such as core stanfordNLP I get the following error message on python3 manage.py runsslserver --settings=scriba.settings.local: [11/Oct/2018 14:59:33] "GET /jobs/ HTTP/1.1" 500 14080 ^XInternal Server Error: /jobs/ Traceback (most recent call last): File "/Users/Sen/Documents/BIA/scriba/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/Sen/Documents/BIA/scriba/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/Sen/Documents/BIA/scriba/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Sen/Documents/BIA/scriba/lti_app/jobs/views.py", line 22, in index 'exception': job.meta['exception'] KeyError: 'exception' I'm really stuck with this since I've only been given a few hours of a hand-over on the new system. Sorry if theres not enough context. -
React request with axiox on DRF api trow the error Forbidden (CSRF cookie not set.): / to the backend
This is my react Js code : export function loginUser({ email, password }, history) { return (dispatch) => { axios({ url: URL_LOGIN_BASE, method: "POST", headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, // withCredentials: true, data: { "email": email, "password": password } }).then(response => { dispatch(setAuthentification(true)); history.push("/dashboard"); console.log(response); }).catch(err => { console.log(err); }); }; } And here my the server configuration : ALLOWED_HOSTS = [ "127.0.0.1", "localhost", "192.168.0.1", "mockbic.spnnjy4rjm.eu-west-3.elasticbeanstalk.com" ] CORS_ORIGIN_WHITELIST = ( 'localhost:3000', '127.0.0.1:3000') CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'Access-Control-Allow-Origin', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'mock-bic-token', # IMPORTANT ) # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "storages", "datacollection.apps.DatacollectionConfig", 'corsheaders', ] So i have the backend error : Forbidden (CSRF cookie not set.): / backend error Please this question is very current but all solutions tried don't resolve my case... Help ! -
How do I stop Django or Django-Restframework from returning template or HTML error responses
I keep getting HTML tags as errors after I turned DEBUG=False, I have tried handler404, handler400, handler500 with no success. I'm using Django 2.1 and Django-Restframework. I'm customizing this tutorial: https://thinkster.io/tutorials/django-json-api/authentication to my liking. Thank you for your time, help and assistance. -
How can resolve error AttributeError: 'NoneType' object has no attribute 'meta_title' in Django2 view?
I have a problem with Django2 when render page whith error AttributeError: 'NoneType' object has no attribute 'meta_title', post my code below. Below models in myapp : meta_title = models.CharField( verbose_name='Page Meta Title', help_text='Very important for SEO. Include keywords.', blank=False, null=False, max_length=120, ) And view that cause error : def get(self, request, path, instance): context = { 'instance': instance, 'children': instance.get_children() if instance else ContentPageModel.objects.root_nodes(), 'meta_title': instance.meta_title, 'meta_description': instance.meta_description, } return render( request, 'pages/content_page.html', context, ) Traceback : AttributeError: 'NoneType' object has no attribute 'meta_title' Someone is kind enough to show me how I can solve? Thank you -
django-tenant-schema enable Admin module for all tenants
I am setting up django with multitenant architecture. I went through the https://django-tenant-schemas.readthedocs.io/en/latest/install.html instruction and get to the point that have inital startup screen. What I want to achieve is to enable admin module for each tenant. my in settings.py I have following: #Application definition SHARED_APPS = ( 'tenant_schemas', # mandatory, should always be before any django app 'customers', # you must list the app where your tenant model resides in 'django.contrib.contenttypes', # everything below here is optional ) TENANT_APPS = ( 'django.contrib.contenttypes', # your tenant-specific apps # 'myapp.hotels', # 'myapp.houses', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', ) INSTALLED_APPS = [ 'tenant_schemas', 'customers', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', ] TENANT_MODEL = "customers.Client" MIDDLEWARE = [ 'tenant_schemas.middleware.TenantMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'sitemanager.urls' PUBLIC_SCHEMA_URLCONF = 'sitemanager.urls_public' when trying to open http://localhost:8000/admin getting error: DoesNotExist at /admin/login/ Site matching query does not exist. Request Method: GET Request URL: http://localhost:8000/admin/login/?next=/admin/ Django Version: 2.1.2 Exception Type: DoesNotExist Exception Value: Site matching query does not exist. my urls.py: from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] What am I missing in configuration? -
Django 1.11 django-geoposition input fields not appearing
After migrating django from 1.9.* to 1.11.* map disapepared for django-geoposition widget, so I found a solution on their github repo: https://github.com/philippbosch/django-geoposition/pull/84 and switched to django-1.11 branch in my requirements.txt and it fixed the map problem, however now the input fields are not rendering in the html structure anymore. This is the commit that fixed the map problem: https://github.com/philippbosch/django-geoposition/pull/84/commits/679c8a2488a0154474ec888a78524491ff281097 and this is my admin class: class NotificationAdmin(TabbedDjangoJqueryTranslationAdmin): form = NotificationForm list_display = ( 'admin_title', 'title', 'category' ) fieldsets = ( ( 'Notification', { 'fields': ( 'admin_title', 'category', 'title', 'text', 'offer_categories', 'pos_categories', 'show_datetime', 'show_instantly', 'show_in_feed', 'countries', 'offer', 'send_push_notification', 'clear_previous_cards', 'membership_card_numbers', ) } ), ( 'Geolocation', { 'fields': ('location', 'radius') } ), ) with 'location' being the field set to Geolocation() field. -
Can't migrate database because environments variables are not available beanstalk
I'm currently encountering quite an annoying problem with my Django server on AWS Beanstalk. My Database and S3 storage end points, account aliases and keys all exists as env variables, so for example I would access my database like this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], 'OPTIONS': { 'autocommit': True, }, } } The problem arises when I need to make change to my model. I would want to be able to run migrations on Beanstalk after every update, so i have this in my ebextensions config file. container_commands: 01_migrate: command: 'source /opt/python/run/venv/bin/activate && django-admin.py makemigrations' command: 'source /opt/python/run/venv/bin/activate && django-admin.py migrate' leader_only: true But this doesn't work, as somehow I get the error that the environment variables I need don't exist at this stage! So if I want to run my container command, I would need to expose my env variables to my settings.py. Now this completely defeats the purpose of env variables. Why am I getting this error and is there any way to circumvent this? -
Which document file in django (settings.py, manage.py, views.py, models.py) do I have to set the size or scroll parameter in elasticsearch?
When searching using elasticsearch it only returns 10 responses, we are trying to make the software return all the responses from the database. Upon doing some research it says we have to set the size or do a scroll in elasticsearch. But we are not sure which file in django to exactly put the parameter. -
How to generate signed url in Django Rest for a file in google cloud storage?
I am using Django Rest framework for making APIs. Along with it, I am using Google Cloud Storage to store media files. I have some questions in mind: How do I generate signed file urls using the django rest framework? I have been searching the net with same but not able to get clear picture of it. So, if I delete a file in database, will it be automatically deleted from Google cloud storage as well? Thanks in advance!!!