Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix django-registration-redux error
I'm using django-registration-redux in my django project, but when I visit: http://127.0.0.1:8000/accounts/register/ it redirect me into: http://127.0.0.1:8000/accounts/profile/ I tried with "LOGIN_REDIRECT_URL='/accounts/register/'" in settings.py but it didn´t work This is my settings.py code: INSTALLED_APPS = [ #apps django 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', #apss terceros 'crispy_forms', 'registration', #mis apps 'inicio', 'boletín', ] and ACCOUNT_ACTIVATION_DAYS = 7 REGISTRATION_AUTO_LOGIN = True SITE_ID = 1 This is my urls.py code: urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', views.boletin, name='boletín'), url(r'contact/$', views.contact, name='contact'), url(r'about/$', about, name='about'), url(r'^accounts/', include('registration.backends.default.urls')), ] -
Django commands not running on Heroku
My app works perfect locally, but when deploying yo heroku my commands to create records for my objects are not working. For example, locally I've a command to create Category objects from reading a CSV file. python manage.py samples However, the tables are created in me PostgreSQL DB on Heroku when running: python manage.py migrate In my project I've a Procfile to call all my commands, but according to error they are not been executed: File "D:\web_proyects\stickers-gallito-app\shop\views.py", line 94, in SamplePack slug=product_slug, File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\django\db\models\query.py", line 399, in get self.model._meta.object_name shop.models.Sample.DoesNotExist: Sample matching query does not exist. Procfile: release: python manage.py makemigrations release: python manage.py migrate release: python manage.py ubigeo_peru release: python manage.py groups release: python manage.py categories release: python manage.py products release: python manage.py products_pricing release: python manage.py samples release: python manage.py samples_pricing web: gunicorn stickers_gallito.wsgi --log-file - settings.py import os # SITE_ROOT = root() # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '^_67&#r+(c+%pu&n+a%&dmxql^i^_$0f69)mnhf@)zq-rbxe9z' ALLOWED_HOSTS = ['127.0.0.1', 'stickers-gallito-app.herokuapp.com', 'stickersgallito.pe', 'www.stickersgallito.pe'] # … -
Django settings not found when trying to deploy
I have my Django app settings in a folder within the app folder with an init.py and this works fine on my current VPS server, Pycharm development and in the Divio local development environment. However, when I try and deploy this to Divio staging I get "ModuleNotFoundError: No module named 'settings'". Why is this? -
Virtual Enviroments Inside Virtual Enviroments?
When I start a Django 2 project using Pycharm Pro it automatically creates a virtual environment for my project. It sets up a basic Django app with a functional admin app (and some others "apps" apparently I haven't got to yet) Am I supposed to create additional virtual environments for each Django app I build in a sub directory? -
I don't understand why the following error is generated "The SECRET_KEY setting must not be empty." on executing python manage.py runserver
I have already set the SECRET_KEY as an environment variable on windows, but the error says that the "The SECRET_KEY setting must not be empty" on running the development server. I do not understand that ? settings.py import os from . import storage_backends from decouple import config, Csv # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'WebBoard', 'Search', 'widget_tweaks', 'storages' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'Board.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Board.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = … -
django.db.utils.OperationalError: (2006, 'SSL connection error: SSL_CTX_set_tmp_dh failed') - Django MySQL Database Configuration
Receiving django.db.utils.OperationalError: (2006, 'SSL connection error: SSL_CTX_set_tmp_dh failed') error when trying to connect with my existing MySQL DB by skipping the SSL check. Current Configuration i have in my settings.py file. 'default': { 'ENGINE' : 'django.db.backends.mysql', 'NAME': <db_name>, 'USER': <db_username>, 'PASSWORD': <db_password>, 'HOST': <host_name>, 'PORT': '3306', 'OPTIONS': { 'ssl' : { 'ssl_disabled': True } } Could someone tell me how to bypass the SSL check by MySQL DB connection using Django? Note: conda 4.6.14 Python 3.7.3 -
What is the difference between Django inline_formset and 3rd party django-nested-admin?
I've created model with different relationships and now I need to allow other users to post new content. Naturally I want to use single form to post model and related models and not just show select element or to open a popup to create a related model. With Djangon builtin inline_formset i couldn't achieve inline forms and quite frankly cannot say that does it even support this kind of requirement? However, I ran into django-nested-admin which made quite straighforward and now I have form with inline tabular forms for related models. From documentation I can see that it can be used inplace of built-in classes and is inherited from Django's builtin? django.contrib.admin django_nested_admin ModelAdmin NestedModelAdmin InlineModelAdmin NestedInlineModelAdmin StackedInline NestedStackedInline TabularInline NestedTabularInline -
Why django form input is not being saved in database?
I created a form which will take input and save input values in database(mysql). My forms.py class postcreation(forms.Form): post_title = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'name':'post_title'})) post_name = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'name':'post_name'})) post_post = forms.CharField(widget=forms.Textarea(attrs={'name':'post_post'})) My models.py class postdata(models.Model): title = models.CharField(max_length=200) name = models.ForeignKey(userdata, on_delete='CASECADE') post = models.TextField() def __str__(self): return self.title At first I had not used the 'attr' value. It didn't work. I saw a stackoverflow answer which says that I should. Still no luck. My views.py def postinput(request): if request.method == 'POST': form = postcreation(request.POST) if form.is_valid(): inputpost = postdata(title=request.POST['post_title'], name=request.POST['post_name'], post=request.POST['post_post']) inputpost.save() return redirect('index') else: form = postcreation() context = { 'form': form } return render(request, 'firstapp/postinput.html', context) html template <form method="POST" action="{% url 'index' %}"> {% csrf_token %} {{ form }} <button type="submit">Post</button> </form> I was trying to get input through form and save it to database. But I was not being able to do so. I cannot understand why. I was going through some of the tutorials and some stackoverflow questions. It still doesn't work. Thanks for your help. -
Why doesn't JsonResponse automatically serialize my Django model?
I have these models: class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class User(AbstractUser): username = models.CharField(max_length=255, unique=True) email = models.EmailField(unique=True, null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Post(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE) content_url = models.URLField(null=False) I want to be able to fetch all of the models in the database. When I do this: urlpatterns = [ path("", views.get_all_posts, name="get_all_posts")] def get_all_posts(request): return JsonResponse({"posts": Post.objects.all()}) I get an error about JSON serialization. So, as per the advice on other posts, I do this: def get_all_posts(request): posts = serializers.serialize('json', Post.objects.all()) return JsonResponse({"posts": json.loads(posts)}) But then I get an object of this shape: ('[{"model": "api.post", "pk": 1, "fields": {"created_at": ' '"2019-05-06T20:22:43.928Z", "updated_at": "2019-05-06T20:22:43.928Z", ' '"user": 1, "content_url": "tmp/posts/None.md"}}]') Do you see how ridiculous this is? To get the actual content of the post, I need to map each "response" to its fields property, and even then, I am still missing the primary key!! I'm wondering why the JSON response interface isn't as simple as this: def get_all_posts(request): return JsonResponse({"posts": Post.objects.all()}) It seems that to deliver a serialized JSON to the client I have to jump through a series of hoops that, honestly, should not exist in … -
How add to cache file image to Django HttpResponse
How can I solve this? How add cache header in HttpResponse? Now the file is not cached.This module is needed to search and return photos or gifs. Just need to cache the file on the client in the browser. my views: def q(request, slug, name): arr = { 'png': 'image/png', 'jpg': 'image/jpeg', 'gif': 'image/gif', } current_time = datetime.datetime.utcnow() image_data = open(path, 'rb').read() response = HttpResponse(image_data, content_type = arr[extension]) last_modified = current_time - datetime.timedelta(days=1) response['Last-Modified'] = last_modified.strftime('%a, %d %b %Y %H:%M:%S GMT') response['Expires'] = current_time + datetime.timedelta(days=30) response['Cache-Control'] = 'public, max-age=315360000' response['Date'] = current_time response['Cache-Control'] = 'no-cache' return response Response headers: Cache-Control: no-cache, max-age=900 Content-Length: 767365 Content-Type: image/gif Date: 2019-05-06 20:21:25.134589 Expires: 2019-06-05 20:21:25.134589 Last-Modified: Sun, 05 May 2019 20:21:25 GMT Server: WSGIServer/0.2 CPython/3.7.3 X-Frame-Options: SAMEORIGIN Request headers: Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3 Accept-Encoding: gzip, deflate, br Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 Cache-Control: max-age=0 Connection: keep-alive Host: localhost:8088 If-Modified-Since: Sun, 05 May 2019 20:21:14 GMT Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36 -
How to integrate Paytm payment gateway in Django Oscar?
What is the best way to intgrate paytm payment gateway in a django oscar project. Has anyone tried this? -
Ubuntu Instance API`s doesn`t works when I close the aws instance
I have deployed my django app on ubuntu cli. When the cli is opened using ssh my django apis work but as soon as I close the instance my api`s stop working. How to make my instance running even when I have closed the connection and fyi my database is postgresql which is also working fine. I just want my API to run even if I close the instance -
The view didn't return an HttpResponse object when use redirect()
I tried creating model form to add new record to my models in django, but I got this error: The view post.views.add_job_resume didn't return an object. It returned None instead. this is my files(Notice that in this file I have more codes than what I write here): view.py def add_job_resume(request): if request.method=="POST": form = AddJobForm(request.POST) if form.is_valid(): job_resume = form.save(commit=False) job_resume.user= request.user job_resume.save() return redirect('view_job_resume') else: form = AddJobForm() return render(request, 'education/job_research_education_records/job_resume/add_job_resume.html', {'form': form}) forms.py class AddJobForm(ModelForm): class Meta: model = JobRecord fields = [ 'title', 'explains', 'post', 'organization', 'time_start', 'time_end', 'upload_url', ] models.py class JobRecord(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) title = models.TextField(max_length=250, blank=False) explains = models.TextField(max_length=500, blank=True) post = models.TextField(max_length=100, blank=False) organization = models.TextField(max_length=100, blank=False) time_start = models.TextField(max_length=100) time_end = models.TextField(max_length=100) upload_url = models.FileField(upload_to='job-resume-files/') def __str__(self): return self.title add_job_resume.html <form method="post" > {% csrf_token %} {{form.as_p }} <button type="submit" class="btn btn-info">add</button> </form> urls.py urlpatterns = [ path('edu/resume/job/', views.view_job_resume, name='view_job_resume'), path('edu/resume/job/add', views.add_job_resume, name='add_job_resume')] I search a lot for this error but I can't solve that! What is going on? -
How to use indexes in Django models?
There're a number of ways how to set an index in Django, at least these seem to be. I mean one can assign an index for a field of a class in models.py with: db_index option in a field in a model; definition of that in the official docs is very scarce (link) index_together & indexes Meta options Index class Moreover, I took a look at indexes in my database (with special viewer) and saw that there are no indexes for the fields with db_index=True, it made me quite confused. The question Please explain me what are indexes in Django (what do all the ways do)? Off-top -
Django Can't load Json in POST request body if more than 1 parameter is passed in URL
I have a views.py with an endpoint like this: def endpoint(request): if request.method == "POST": body = request.body.decode('utf-8') body = json.loads(body) param1 = request.GET.get('param1','default1') param2 = request.GET.get('param2','default2') My urls.py have this urlpattern: url(r'^endpoint$', views.endpoint, name="endpoint") The problem I have is that if I send requests in one of the following ways it works fine: curl -X POST http://localhost:8000/endpoint -d @data.json curl -X POST http://localhost:8000/endpoint?param1=val1 -d @data.json curl -X POST http://localhost:8000/endpoint?param2=val2 -d @data.json But if I send a request with both parameters: curl -X POST http://localhost:8000/endpoint?param1=val1&param2=val2 -d @data.json I get the exception: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Why I get JSONDecodeError when having multiple parameters? Is it because it's a POST request? -
How to filter the results of a query passing a string as a field
I need to append the email_d_list only if the flag is set in the model. I am calling this function with the airport_code already coming in from the user. Now I would like to add the user to the email list if they have the flag selected for the user or not. Each user in the model has six boolean flags, one flag for each report possible. The text for the flag is in the middle. I have tried .get() and .filter() Models.py class DistributionList(models.Model): ''' List of all email addresses that are to receive automated emails from the system ''' email = models.CharField(max_length=40, primary_key=True) name = models.CharField(max_length=40) receive_emails = models.BooleanField() IATA_CODES = Aerodrome.objects.all().values_list('iata', flat=True) ''' Dynamically creates a checkbox field for each aerodrome in the Aerodrome table ''' for aerodrome in IATA_CODES: aerodrome_report = "receive_" + aerodrome + "_report" DistributionList.add_to_class(aerodrome_report, models.BooleanField(default=False)) script.py for users in DistributionList.objects.all(): report_code_filter = 'receive_' + airport_code + '_report' report_code = DistributionList.objects.get(**{report_code_filter: True}): if users.**report_code: mail_d_list.append(users.email) -
Django rest framework and Postgres SQL CHECK constraint
I am trying to set custom constraint directly to the database. I executed these queries as raw SQL in the latest migration (basically to insure unique combination of names in different tables): CREATE OR REPLACE FUNCTION f_assemblies_validate_name(_owner_id uuid, _name text) RETURNS bool AS $func$ SELECT NOT EXISTS ( SELECT 1 FROM internal_products, group_products WHERE internal_products.owner_id = group_products.owner_id AND ((internal_products.owner_id = $1 AND internal_products.name = $2) OR (group_products.owner_id = $1 AND group_products.nickname = $2))); $func$ LANGUAGE sql STABLE; CREATE OR REPLACE FUNCTION f_group_products_validate_nickname(_owner_id uuid, _nickname text) RETURNS bool AS $func$ SELECT NOT EXISTS ( SELECT 1 FROM internal_products, assemblies WHERE internal_products.owner_id = assemblies.owner_id AND ((internal_products.owner_id = $1 AND internal_products.name = $2) OR (assemblies.owner_id = $1 AND assemblies.name = $2))); $func$ LANGUAGE sql STABLE; CREATE OR REPLACE FUNCTION f_internal_products_validate_name(_owner_id uuid, _name text) RETURNS bool AS $func$ SELECT NOT EXISTS ( SELECT 1 FROM group_products, assemblies WHERE group_products.owner_id = assemblies.owner_id AND ((group_products.owner_id = $1 AND group_products.nickname = $2) OR (assemblies.owner_id = $1 AND assemblies.name = $2))); $func$ LANGUAGE sql STABLE; ALTER TABLE assemblies ADD CONSTRAINT c_assemblies_name CHECK (f_assemblies_validate_name(owner_id, name)) NOT VALID; ALTER TABLE group_products ADD CONSTRAINT c_group_products_nickname CHECK (f_group_products_validate_nickname(owner_id, nickname)) NOT VALID; ALTER TABLE internal_products ADD CONSTRAINT c_internal_products_name CHECK (f_internal_products_validate_name(owner_id, name)) NOT VALID; … -
Node or Django with React?
I have a very big project to re-develop because nowadays is outdated. I love react and i decide to use it in frontend, but my doubt is about backend... As I said is a very big project, and it must be a very scalable and maintainable. I used Node with a some projects and It works fine for me but my fear is could be small and disorganized for a big project. Instead, i develop in Python but never used Django, but i heared a lot of it and I don't know if this will be a better solution for my project. ¿It integrates good with React? What you think is better Python or Node with big project? Thank you in advice. -
How can I do to avoid logout function deletes info about sessions
I want to identify navigator sessions, not users sessions. I want session_id to perdure even if they log in or logout, but logout functions deletes all the information about sessions, I don't want to delete nothing. -
How to make the mock object iterable ['TypeError: 'Mock' object is not iterable'] Need to Mock the django query that is iterating through for loop
I am trying to mock the below django query object : 1.) if MyModel.objects.filter(data='some_data').exists(): then 2.) for row in MyModel.objects.filter(ListId=id): I am trying to test below django query inside my method. def my_method(some_parameter): if formsList.objects.filter(data=some_data).exists(): for item in formsList.objects.filter(data1='data1',data2='data2'): formNameInDb = (item.fileId).formName if formNameInDb == formName: return True Below is my approach: @mock.patch('MyModel.objects') def test_checkCombinationOfStateAndProduct(self, formsList_mock): formsList_mock_data = mock.MagicMock(spec=MyModel) formsList_mock_data.fileId.formName ='test data' formsList_queryset = Mock() formsList_mock.filter.return_value = formsList_queryset # formsList_mock.filter.return_value = [formsList_queryset] formsList_queryset.exists.return_value = True For the query 1). It is working like I am able to mockupto if formsList.objects.filter(data=some_data).exists() but again for the query 2) for item in formsList.objects.filter(data1='data1',data2='data2'): I am getting mock object(formsList_queryset) should be iterable so if I make it iterable like this [formsList_queryset]. Then i am getting error " AttributeError: 'list' object has no attribute 'exists'. I guess it is because after making the mock object iterable it is behaving like list so it does not has the exists attribute. My problem is I am not able to make the mock object(formsList_queryset) iterable so that it will work in the both above mentioned query. Is there other way mock both query to handle this issue. Can anyone help to solve the chain queries. Any help or … -
Dockerize django with nginx and gunicorn. Static files not being served
After I've gone through 5 or 6 guides, I'm still struggling to make this work. Although app itself is served normally, static and media files won't load. My Dockerfile located at the same level as manage.py #Dockerfile FROM python:3.7-alpine RUN apk --update add \ build-base \ libpq \ # pillow dependencies jpeg-dev \ zlib-dev RUN mkdir /www WORKDIR /www COPY requirements.txt /www/ RUN pip install -r requirements.txt ENV PYTHONUNBUFFERED 1 COPY . /www/ docker-compose.yml: #docker-compose.yml version: "3" services: web: build: . restart: on-failure volumes: - .:/www env_file: - ./.env command: > sh -c "python manage.py makemigrations && python manage.py migrate && python manage.py collectstatic --noinput && gunicorn --bind 0.0.0.0:8080 portfolio.wsgi:application" ports: - 8001:8080 nginx: image: "nginx" restart: always volumes: - ./nginx/conf.d:/etc/nginx/conf.d - ./static/:/static - ./media/:/media ports: - 80:80 depends_on: - web nginx config: portfolio.conf server { listen 80; location /static/ { alias /www/static/ } location /media/ { alias /www/media/ } # pass requests for dynamic content to gunicorn location / { proxy_pass http://web:8080; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') # Media MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') DEBUG is set too False Maybe I'm just too tired … -
How to fix "WebSocket connection failed' in channels official tutorial
I am following channels chat app tutorial. I have done everything on the tutorial but I seem to not be getting messages to show in the text area. var roomName = {{ room_name_json }}; var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/'); chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data['message']; document.querySelector('#chat-log').value += (message + '\n'); }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; -
Problem to index with django-python using django_elasticsearch_dsl
I'm working on a project using django-python. This has "oaisearch" installed to retrieve the metadata from different websites and "django_elasticsearch_dsl" to index them. It was verified that "oaisearch" runs without problems. The problem occurs when "python3 manage.py search_index --create -f" is run to start indexing. The file "documents.py" that has the configuration of what you want to index is the following. from elasticsearch_dsl import analyzer from django_elasticsearch_dsl import DocType, Index from oaisearch.models import Digital_Resources digital_resources = Index('digital_resources') digital_resources.settings( number_of_shards=1, number_of_replicas=0 ) html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["standard", "lowercase", "stop", "snowball"], char_filter=["html_strip"] ) @digital_resources.doc_type class Resources(DocType): class Meta: model = Digital_Resources fields = [ #'oai_server', 'creator', 'title', 'subject', 'description', 'identifier', ] The console failure message after executing the aforementioned command is as follows Creating index 'digital_resources' PUT http://localhost:9200/digital_resources [status:400 request:0.014s] Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/dist-packages/django_elasticsearch_dsl/management/commands/search_index.py", line 128, in handle self._create(models, options) File "/usr/local/lib/python3.5/dist-packages/django_elasticsearch_dsl/management/commands/search_index.py", line 84, in _create index.create() File "/usr/local/lib/python3.5/dist-packages/elasticsearch_dsl/index.py", line 203, in create self.connection.indices.create(index=self._name, body=self.to_dict(), **kwargs) File "/usr/local/lib/python3.5/dist-packages/elasticsearch/client/utils.py", line … -
How to import environment variables to Django from local file
I'm preparing for production on my first professional Django project, and I'm having issues with environment variables to secure the the application. So far I've managed to create a local file to store all variables on my pc... env_variables.py import os db_user = os.environ.get('db_user') db_password = os.environ.get('db_password') # AWS DJANGO export AWS_ACCESS_KEY_ID = "access_key" export AWS_SECRET_ACCESS_KEY = "secret_key" export AWS_STORAGE_BUCKET_NAME = "bucket_name" print(db_user) print(db_password) I've used the environment settings(windows) to create username and password. When I run the file they work. I'm using my AWS credentials to test this. I've been under the impression that Django can access this information no matter where it is on my local pc. Correct me if I'm wrong. settings.py ... AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') ... I know that Django isn't accessing this file because I get 400 for all of my media files, but it works when I place the keys directly into the settings.py file. I believe I'm missing a few steps here. I've seen other python coders capable of doing this without having to use something like django-environ or other packages. If anyone can help it would be greatly appreciated because I'd like to do this for … -
I've got error when i set debug to false after new update
I am currently learning python and django framework Developing my article site i've discovered a problem Here is my github repo: https://github.com/theseems/tsite Well i've done my update replacing TinyMCE with CKEditor and when i set debug mode to False, i've got 500 error I just tried to delete STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' And then it works. What is my problem about? I know that my code is bad or whatever but i am only a begginer so try not to judge me