Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django get textarea value without quotes
am using Django 3.2, i need to get the value of a textarea from template my template code is: <div class="form-group"> <label for="text_to_change">Text to replace</label> <textarea name="replace_text" class="form-control" rows="3"></textarea> </div> i need to pass a list e.x ['Old text', 'New Text'] but what is get is a string: "[Old text', 'New Text']" i tried to use unescape_string_literal without luck -
Do not change the language of CK Editor
I want to change the language of CK Editor to Persian in my Django project After inserting the following code, I receive an error in the console. And CK Editor is not displayed Other languages work properly. What is the problem? I am using the following Python package for CK Editor in my project https://pypi.org/project/django-ckeditor/ Error Image Code CKEDITOR.replace( 'id_html_content', { language: 'fa' } ); -
Django: urls.py giving No Reverse Match error
I installed django-axes which allows you to set a url to redirect to upon 5 login failures. I added this line to settings.py per the documentation: AXES_LOCKOUT_URL = 'account-locked' I then added this line to users/urls.py: path('account/locked/?username=<str>', user_views.account_locked, name='account-locked'), When i input 5 incorrect username/password combos in the login screen, it attempts to redirect me, but I get this error: NoReverseMatch at /login/ Reverse for 'account-locked?username=user2' not found. 'account-locked?username=user2' is not a valid view function or pattern name. -
save multiple hidden fields in django
I have two hidden that the user is not able to fill from form, but I want to provide values for these fields before I save the entry. I have the snippet below to achieve this if I have just one hidden field, but not sure how to make it work for more than one. if request.method == 'POST': var1 = AppName(col1=value1) # var2 = Notice(col2=value2) form = AppNameForm(request.POST, instance=var1) if form.is_valid(): form.save() return redirect("home") How can I bring var2 into the form values before saving? -
gunicorn failing when log configuration added to settings.py in Django
Basically as soon as I add logging configuration, gunicorn responds with this ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Fri 2021-04-23 19:05:44 UTC; 7s ago TriggeredBy: ● gunicorn.socket Process: 4154 ExecStart=/home/ubuntu/.local/share/virtualenvs/name-fma1nZHV/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock name.wsgi:application (code=exited, status=1/FAILURE) Main PID: 4154 (code=exited, status=1/FAILURE) Apr 23 19:05:44 ip-10-0-84-161 gunicorn[4154]: self.stop() Apr 23 19:05:44 ip-10-0-84-161 gunicorn[4154]: File "/home/ubuntu/.local/share/virtualenvs/nameapi-fma1nZHV/lib/python3.8/site-packages/gunicorn/arbiter.py", line 393, in stop Apr 23 19:05:44 ip-10-0-84-161 gunicorn[4154]: time.sleep(0.1) Apr 23 19:05:44 ip-10-0-84-161 gunicorn[4154]: File "/home/ubuntu/.local/share/virtualenvs/nameapi-fma1nZHV/lib/python3.8/site-packages/gunicorn/arbiter.py", line 242, in handle_chld Apr 23 19:05:44 ip-10-0-84-161 gunicorn[4154]: self.reap_workers() Apr 23 19:05:44 ip-10-0-84-161 gunicorn[4154]: File "/home/ubuntu/.local/share/virtualenvs/nameapi-fma1nZHV/lib/python3.8/site-packages/gunicorn/arbiter.py", line 525, in reap_workers Apr 23 19:05:44 ip-10-0-84-161 gunicorn[4154]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Apr 23 19:05:44 ip-10-0-84-161 gunicorn[4154]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Apr 23 19:05:44 ip-10-0-84-161 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Apr 23 19:05:44 ip-10-0-84-161 systemd[1]: gunicorn.service: Failed with result 'exit-code'. However, when there is no logging in my settings.py file for Django, gunicorn works fine. Below is my settings.py with and without logging (the settings.py works fine in dev environment on localhost, just breaks gunicorn in production) - also, for every part of the settings that I wanted to keep to myself such … -
Trouble connecting to AWS ElasticSearch from django-haystack using an SSH tunnel
I have a Django app running on EC2, and it can connect to my AWS ElasticSearch using the following django-haystack configuration: HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': os.environ.get('ELASTICSEARCH_URL', 'http://elasticsearch').strip(), 'INDEX_NAME': 'my_index' }, } if 'es.amazonaws.com' in HAYSTACK_CONNECTIONS['default']['URL']: HAYSTACK_CONNECTIONS['default']['KWARGS'] = { 'port': 443, 'http_auth': AWS4AuthEncodingFix( os.environ.get('AWS_ACCESS_KEY_ID').strip(), os.environ.get('AWS_SECRET_ACCESS_KEY').strip(), os.environ.get('ELASTIC_SEARCH_AWS_REGION', 'us-east-1').strip(), 'es'), 'use_ssl': True, 'verify_certs': True, 'connection_class': RequestsHttpConnection, } This works fine, but now for debugging purposes, I need to connect to the production ElasticSearch from my local development machine. To do this, I created an SSH tunnel: ssh -v -N -L localhost:9200:${ELASTICSEARCH_ENDOINT}:443 -i my_secret_pem_file.pem ${EC2_USERNAME}@${EC2_IP} From the SSH logs I can see that the connection is established, and this works fine: 10:26 $ curl -k -X GET 'https://localhost:9200/_cat/indices?v' health status index pri rep docs.count docs.deleted store.size pri.store.size yellow open .kibana-4 1 1 2 0 9.5kb 9.5kb yellow open my_index 5 1 1150327 547242 2.2gb 2.2gb (note that I had to use -k with curl to bypass SSL verification, as the certificate would not be valid for localhost. To connect from django-haystack, I added the following else branch to the configuration above: else: HAYSTACK_CONNECTIONS['default']['KWARGS'] = { 'port': 9200, 'use_ssl': False, 'verify_certs': False, } When I start my Django app and try … -
remove all record of a model in Django restfull
I try to remove all records of a model by using API but I get an error how can I do that View : @api_view(["DELETE"]) @csrf_exempt @permission_classes([IsAuthenticated]) def delete_site(request): try: Site.objects.all().delete() return Response(status=status.HTTP_204_NO_CONTENT) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) URL router.register('site-delete',views.delete_site) Error : assert queryset is not None, '`basename` argument not specified, and could ' \ AssertionError: `basename` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute. -
Django inline formset does not do this
I am creating a Calorie Log website using Django. One creates an account, and can start logging the amount of calories he consumed and burnt on a particular date, then it shows whether on that day he consumed or burnt more calories. The User can store frequently eaten food and frequent exercise that he does so that when he adds the data he can use that item Using the given midels user can add food-item and exercises. Food Model: class Food(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) food_name = models.CharField(max_length=50, null=True, blank=True) calories = models.IntegerField(null=True) food_pic = models.ImageField(default="default_food.jpg", null=True, blank=True) def __str__(self): return f"{self.food_name}" Exercise Model: class Exercise(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) exercise_name = models.CharField(max_length=100, null=True, blank=True) calories = models.IntegerField(null=True) exercise_pic = models.ImageField(default="default_exercise.png", null=True, blank=True) def __str__(self): return f"{self.exercise_name}" I use the following two models to store the information about a particular date: DailyFood Model: class DailyFood(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) food_name = models.ForeignKey(Food, on_delete=models.CASCADE, null=True) quantity = models.FloatField(null=True) date = models.DateField(auto_now_add=True, null=True) def __str__(self): return f"{self.customer}, {self.date}" DailyExercise Model: class DailyExercise(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) exercise_name = models.ForeignKey(Exercise, on_delete=models.CASCADE, null=True) quantity = models.FloatField(null=True) # number of hours done exercise date = models.DateField(auto_now_add=True, null=True) def __str__(self): return f"{self.customer}, … -
Django rest framework + cpanel's application manager(phusion passenger) = error 500
I'm able to run a local server with the quickstart example from https://www.django-rest-framework.org/tutorial/quickstart/, but after deploy with Application Manager (Phussion Passenger) the server only display the following page: no css, js And console: error When click /users : Server error I did run python manage.py collectstatic Setup: Centos 7.9 Cpanel Application Manager (Phusion Passenger) - Development = True Python 3.8 venv Django + Django Rest Framework - Debug = True Settings.py : from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'secret' # 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', 'rest_framework', ] MIDDLEWARE = [ '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 = 'tutorial.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'tutorial.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', … -
smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server - trying to send email via Django
I have a Docker container where I am trying to send an email via Django. I have a separate email server on another domain that I want to use for this purpose. I have other applications connect with it with no problem. My Django production email setup looks like this (I intend to replace username and password with Kubernetes secrets in the future, but for testing I am just putting them inside the file): EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.mydomain.io' EMAIL_USE_TLS = False EMAIL_PORT = 587 EMAIL_HOST_USER = "<username>" EMAIL_HOST_PASSWORD = "<password>" In my module, I have the following code: from rest_framework.views import APIView from django.core.mail import send_mail class MailView(APIView): def post(self, request): subject = request.data.get("subject") message = request.data.get("message") sender = request.data.get("sender") receipients = request.data.get("receipients") send_mail(subject,message,sender,receipients,fail_silently=False,) ... more This works locally, however when I try to run it inside the container, I get the following error: smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server. Do I need to install some sort of SMTP relay or server to my Docker container? My Docker container is based on the python:3.7 container and I am not currently installing any SMTP extensions or anything to it. -
Django RESTApi Using ForeignKey as filter still produces error
I think I come closer to my problem with API, but I still get the following error: TypeError: Field 'id' expected a number but got <built-in function id>. Model: from django.contrib.auth.models import User class Todos(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=20, default="") text = models.TextField(max_length=450, default="") done = models.BooleanField(default=False) Serializer: class TodosSerializer(serializers.ModelSerializer): class Meta: model = Todos fields = ("id", "owner", "name", "text", "done") View: class TodosView(viewsets.ModelViewSet): queryset = Todos.objects.filter(owner__id=id) serializer_class = TodosSerializer urls: router = routers.DefaultRouter() router.register("todos/<int:id>", views.TodosView) urlpatterns = [path("", include(router.urls))] I want to get all todos for a single User. What am I doing wrong here? -
How do I register one to one users in django rest_framework?
I'm lost on how should I register and login a user which is extendable to many roles. I have different apps in my project: Admin Student Teacher And all these apps with their models are connect to my Custom User model with one to one relationship. Now what should I implement to make these endpoints: POST 'admin/register' - registers an admin POST 'student/register' - registers a student POST 'teacher/register' - registers a teacher POST 'admin/login' - login an admin POST 'student/login' - login a student POST 'teacher/login' - login a teacher What this will do is, whenever, someone registers as a admin it will first create a user and then register it as an admin. I tried using djoser but didn't find much on custom create methods. Little guidance will be appreciated! -
Mongodb connection error from digitalocean app platform
I am having an unusual problem: I successfully deployed a Django app on the digital ocean app platform but the problem is that whenever I am trying to reach any route that requires database app crashes because of MongoDB connection problem and after some time I see upstream connect error or disconnect/reset before headers. reset reason: connection termination When I check the logs I see the ServerSelectionTimeoutError from pymongo So the first thing I checked is the host URL which is correct because using the same credentials I am able to connect and query data from my local pc by a python program I followed the format: "mongodb:srv//myusername:mypassword@clustername.mongodb.net/mydbname my password doesn't contain any special characters In my Django app settings, I put all the required variables to get Django working with MongoDB -I used djongo as an engine DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'stocks', 'HOST': os.getenv("DB_HOST"), 'USER': os.getenv("DB_USERNAME"), 'PASSWORD': os.getenv("DB_PASSWORD") } } All the variables are set correctly I checked in an App platform console Another thing is that if I run python shell in apps console on digital ocean so directly on a server I get a different error immediately but when accessing from the deployed … -
ModuleNotFoundError, even thought it exist, and is installed
I tried makemigrations and i get: from SocialNetwork.Accounts.models import User ModuleNotFoundError: No module named 'SocialNetwork.Accounts''= I made a few applications, installed it in settings, and even pycharm sees it, but i get an error as above. My project structure: -SocialNetwork -Accounts -__init__.py -admin.py -apps.py -models.py -tests.py -urls.py -views.py -Chats -__init__.py -admin.py -apps.py -models.py -tests.py -urls.py -views.py -Other apps And tried install models from account in chats: from django.db import models from SocialNetwork.Accounts.models import User class Chat(models.Model): firstUser = models.ForeignKey(User, on_delete=models.CASCADE) secondUser = models.ForeignKey(User, on_delete=models.CASCADE) I doubt that it will be helpful but i can write models from user: class User(models.Model): name = models.CharField(max_length=50, null=True) phone = models.PhoneNumberField() dateBirth = models.DateField(blank=True, null=True) description = models.CharField(max_length=200, blank=True, null=True I have been sitting with this for 2 hours, what can i should do in this case? Maybe something more with settings or structure? But structure seems be as always in django projects. Any help will be approciated cos i am a little bit new in django. -
Bootstraps cards get encapsulated on Django Landing page
I have a myterious phenomenom and hopefully somebody has experienced this already as well. I want to put three cards in a row on my Django landing page. I fill these cards with dynamic content, means i populate three lines of text which get selected in a for loop in my template. With a dummy text everything looks fine. But as soon as the dynamic text lines gets populated, the third card gets encapsulated into the second card. I would have expected the third card to wrap into the new line but for some reason the layout reacts differently (strangely). Has anyone a clue how I can prevent this to happen? I assume it has sth. to do with the width... :( Thanks a lot in advance for any helpful tip! Best regards Rudy -
how to check ping response of multiple website in django based site?
I have created one website which contains different company application in bootstrap cart format. So this cart is showing the application version and allowing the user to download it by clicking on the button. Requirement: Now I am trying to implement functionally where it will show whether the site is online/reachable or not by a green color dot. I have tried the below code but I found that only for a few 1 sites it is showing green color and for the remaining, it is showing False. Also found that the site is taking time to load the home page I have seen this functionality in another website. Can anyone suggest me how to implement it in the best way? Please find the below code. views.py(showing only logic code) data = {} for singlesite in allsites: site=singlesite.product_by try: subprocess.check_call(['ping', '-c', '1', str(site)]) except subprocess.CalledProcessError: online = False data['online'] = online print('Checking The Ping Response:', online) else: online = True data['online'] = online print('Checking The Ping Response:', online) in the above code, product_by means I am taking it from model str form. HTML code. .logged-in { color: green; font-size: 8px; } .logged-out { color: red; font-size: 8px; } {% if online … -
Django readonly datetime field in inline causing naive datetime RuntimeWarning in tests
I'm getting this annoying error printed to the console when testing the admin add form. The ProductAdmin has an inline with a readonly datetime field which is the culprit of the error: RuntimeWarning: DateTimeField Production.created_at received a naive datetime (2021-04-16 00:00:00) while time zone support is active. class ProductionInline(admin.TabularInline): model = models.Production extra = 1 fields = ('amount', 'details', 'created_by', 'created_at') readonly_fields = ('created_by', 'created_at') @admin.register(models.Product) class ProductAdmin(admin.ModelAdmin): inlines = ( ProductImageInline, ProductionInline, ) def test_get_add(self): url = reverse('admin:product_product_add') response = self.client.get(url) self.assertEqual(response.status_code, HTTPStatus.OK) The error is pretty self explanatory, I'm wondering if someone knows an easy way around this without setting a custom formset on the TabularInline that specifies a timezone aware initial value for the created_at field. Interestingly this happens in the browser as well on initial page load after ./manage.py runserver but subsequent page loads don't print the error. -
prefetch_related() error in ,django while inner joining
I am create a code that is inner join of two object Contest and ContestDetails def get_queryset(self): try: key = self.kwargs['pk'] if key is not None: return ModelA.objects.filter(custom_id=key, is_deleted=False).prefetch_related( Prefetch('modelb_set', queryset=ModelB.objects.filter())) \ .order_by('-updated') except Exception: return ModelA.objects.filter(is_deleted=False).prefetch_related( Prefetch('modelb_set', queryset=ModelB.objects.filter())) \ .order_by('-updated') And when I run it then I am getting below error raise AttributeError("Cannot find '%s' on %s object, '%s' is an invalid " AttributeError: Cannot find 'modelb_set' on ModelA object, 'modelb_set' is an invalid parameter to prefetch_related() I checked some example related to this but why I am getting below error in my code? Where I did wrong? How can I fix? -
Django i18n language switcher not working on deploy at subdirectory
I've got a site with two languages (it will get more in time) and a little dropdown menu to switch languages. It works as desired/expected in the development server. Urls look like this when visiting the site: localhost:8000/en/home localhost:8000/pl/home The django project gets deployed on a server (Apache w/ mod-wsgi) at a subdirectory location, lets say: mysite.com/django Everything works as expected, even the admin site, etc, underneath that subdirectory, however, my little menu to change languages doesn't work anymore. When I change the language, the page reloads, but on the same language that it was on when I tried to change it. I can go back and forth between the languages by manually changing the url in the browser and all the pages work as expected with the translations; it's just the dropdown button that doesn't work anymore. mysite.com/django/en/home mysite.com/django/pl/home At first, I thought it was my button (pretty standard off a tutorial): <form action="{% url 'set_language' %}" method="post" class="form-inline">{% csrf_token %} <div class="form-group mx-sm-3 mb-0"> <input type="hidden" name="text" value="{{ redirect_to }}" class="form-control form-control-sm"> <select name="language" id="langselect" onchange="this.form.submit()"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" … -
Django: Model Class Variables Inheritance
I have below classses class power_source_template (models.Model): power_source_current_type_choices = (("AC", "Alternating Current"),("DC", "Direct Current")) class Meta: abstract = True and class power_sources(power_source_template, tracking_template): ... power_source_current_type = models.CharField(max_length = 2, choices = power_source_current_type_choices) ... When running python3 manage.py check, the following error appears: > File "/var/www/celeste/strato/kirchhoff/models.py", line 61, in power_sources > power_source_current_type = models.CharField(max_length = 2, choices = power_source_current_type_choices) NameError: name > 'power_source_current_type_choices' is not defined What am I doing wrong? I reviewed the Django documentation, but there's no mention of variables inheritance. -
Bootstrap alert message giving me unexpected token <
I am working on a django project and in my html file, I have this code snippet. {% block content %} {% ifequal error False %} <script> <div class="alert alert-success"> <strong>Login Successful</strong> </div> window.location.href="{% url 'home' %}"; </script> {% endifequal %} {% ifequal error True %} <script> <div class="alert alert-success"> <strong>Wrong credentials! Try again</strong> </div> window.location.href="{% url 'login' %}"; </script> {% endifequal %} {% endblock content %} In the console, I am getting this message: Uncaught SyntaxError: Unexpected token '<' On line 500, it is saying. Basically, it points at the line where there is a div within the first script tags. The bootstrap alert is not showing and there is no redirection. If I put a simple alert,everything works! Any idea what is wrong? -
Django - Form used in editing data from extended user model doesn't show previous data as placeholder
I use following code: models.py class Profile(models.Model): location = models.CharField(max_length=300, blank=True) user = models.OneToOneField( User, on_delete=models.CASCADE, ) def __str__(self): return self.imie views.py def edit(request): if request.method == 'POST': profile = Profile.objects.get(user = request.user) profile_form = ProfileForm(request.POST, instance = profile) if profile_form.is_valid(): profile_form.save() messages.success(request, ('Your profile was successfully updated!')) return redirect('profile') else: messages.error(request, ('Please correct the error below.')) else: profile = Profile.objects.get(user = request.user) profile_form = ProfileForm(request.POST, instance = profile) return render(request, 'edit.html', { 'profile_form': ProfileForm }) forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('location') edit.html <div class="col-md-6 offset-md-3"> <form method="post"> {% csrf_token %} {{ profile_form.as_p }} <button type="submit" class="btn btn-secondary">Save changes</button> </form> </div> Following code should allow the user to edit data stored in Profile model and it does exactly that, however form is loaded empty (without placeholder) and I would like it to display previous values. -
How to set a single field of custom form in django in template
I have a custom Django Form # creating a form class PostForm(forms.ModelForm): # create meta class class Meta: # specify model to be used model = Post # specify fields to be used fields = [ "title", "slug", "author", "content", "status", "youtubeVideo", "category", "image", ] I have my view as follows: def create_post(request): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization user = get_user(request) form = PostForm(request.POST or None, initial={'author': user}) if form.is_valid(): form.fields["author"] = user form.save() return HttpResponseRedirect("/index") context['form']= form return render(request, "blog/create_post.html", context) How to set the django form template with only my current user? My django template is as follows: <div class="card-body"> {% load crispy_forms_tags %} <form method="POST" enctype="multipart/form-data"> <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ form | crispy}} <input type="submit" value="Submit"> </form> </div> -
How to disable dates on calendar if its reservated or book in Django?
I'm making a website with rezervation system in Django. But I want the reserved days not to appear in the calendar (datepickertime). I couldn't do what I tried, does anyone have an idea? How can I query if dates are booked? models.py class Reservation(models.Model): enter_date = models.CharField(max_length=250, db_index=True) out_date = models.CharField(max_length=250, db_index=True) -
SSL certificate for use with Celery/Redis - I don't understand 'keyfile','certfile' and 'ca_certs'
I have my Celery and Redis set up as the following - app.conf.update(BROKER_URL='rediss://:password@host:port', CELERY_RESULT_BACKEND='rediss://:password@host:port', broker_use_ssl = { 'ssl_cert_reqs': ssl.CERT_NONE }, redis_backend_use_ssl = { 'ssl_cert_reqs': ssl.CERT_NONE }) But I want to make the SSL certificate required as per the celery documentation - app.conf.update(BROKER_URL='rediss://:password@host:port', CELERY_RESULT_BACKEND='rediss://:password@host:port', broker_use_ssl = { 'keyfile': '/var/ssl/private/worker-key.pem', 'certfile': '/var/ssl/amqp-server-cert.pem', 'ca_certs': '/var/ssl/myca.pem', 'cert_reqs': ssl.CERT_REQUIRED }, redis_backend_use_ssl = { 'keyfile': '/var/ssl/private/worker-key.pem', 'certfile': '/var/ssl/amqp-server-cert.pem', 'ca_certs': '/var/ssl/myca.pem', 'cert_reqs': ssl.CERT_REQUIRED }) The issue is that I don't understand where I get my 'keyfile','certfile', 'ca_certs' from. Do I have to create these or can I use my SSL certificate from Heroku somehow?