Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access Heroku config variables inside Django settings
I am trying to push my code on Heroku, I have hidden my secret key using environ package but now Heroku is not able to access it since I have ignore my .env files using gitignore, I have read about config vars in Heroku but I am having trouble understanding how do I make Django access those values import os import environ # from .secret import key env = environ.Env() environ.Env.read_env() SECRET_KEY = env('KEY',default=env('SECRET_KEY')) -
How can I order only some specific objects randomly in django?
I have a model with is_random_sortable boolean field and position integer field, I want to sort queryset randomly when is_random_sortable is true, otherwise, I want to order by position field. Imagine I have an object with is_random_sortable=False and position=3. I want to have sorted results like this: (numbers are positions) [15, 6, 9, 3, 11, 7, 10,...] object with position 3 always is on index 3 of the list. And other objects with is_random_sortable=True are sorted randomly. -
Safe way to validate file extension in serializer Django
I created an application where I can store images of products. In the database I store just directions to images which are held in designated folder. In my serializer I need to validate the files names and check if the extensions are photo extensions. I wrote something like this below, is it the best way to checking it? Is there maybe more safe method? ALLOWED_IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "bmp", "gif"] class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImage fields = [...] class ProductSerializer(serializers.ModelSerializer): images = ProductImageSerializer(many=True, read_only=True) class Meta: model = Product fields = [..., 'images'] def create(self, validated_data): ... for file in self.context['request'].FILES.getlist('images'): validate_extension(file.name) ... return item def validate_extension(filename): extension = os.path.splitext(filename)[1].replace(".", "") if extension.lower() not in ALLOWED_IMAGE_EXTENSIONS: raise serializers.ValidationError( (f'Invalid uploaded file type: {filename}'), code='invalid', ) -
How to remove loading logo in elastic search?
I add my project an elastic-search <iframe>. When page reloads there are a logo and a loading elastic sentence appears. How can I remove it? -
Django REST Framework, Serializers: Additional data?
Good day, I would like to ask, if there's a possibility to gain additional data inside my serializers? These are my models... models.py class Chair(models.Model): name = models.CharField(max_length=100, null=False, blank=False, unique=True) bookable = models.BooleanField(default=False) user_created = models.CharField(max_length=100) date_created = models.DateField(auto_now_add=True) class Booking(models.Model): chair = models.ForeignKey(Chair, on_delete=models.CASCADE) day = models.DateField() user_name = models.CharField(max_length=100) user_created = models.CharField(max_length=100) date_created = models.DateField(auto_now_add=True) and these my serializers... serializers.py class BookingSerializer(serializers.ModelSerializer): class Meta: model = Booking fields = '__all__' class ChairSerializer(serializers.ModelSerializer): class Meta: model = Chair fields = '__all__' When making a request inside js like this... views.py @api_view(['GET']) def bookings_by_date(request, pk): bookings = Booking.objects.filter(day=pk) serializer = BookingSerializer(bookings, many=True) return Response(serializer.data) script.js let url = '...here's my url for Booking...'; fetch(url) .then((resp) => resp.json()) .then(function(data) { // do something here }); ...I would like to get not only the id of the Chair (models.Foreignkey), but also it's name. My first thought was doing something like this... class ChairSerializer(serializers.ModelSerializer): class Meta: model = Chair fields = [ ... 'chair', 'chair__name', ... ] ...but this doesn't seem to work! Does anyone know a solution for my problem? Thanks for all your help and have a great weekend! -
Should i continue learning django i reached intermediate and go with docker and kubernetes or should i start learning react (i am beginner)
What should i learn Learning django with more than a year and made several projects in django. should I continuing django and dig deep into it or should i start learning react as it is emerging. to meet standard -
Django SMTP Send Email Configuration
I already setup the email. It was working perfectly but after sometime it is not working and sending the mail. I don't know where the problem was created. Can someone help me out with this?? EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail' EMAIL_HOST_PASSWORD = 'mypass' this is my email function code: def my_email(): order = Order.objects.filter(createdAt__gt=Now()-timedelta(minutes=1)) p = str(settings.BASE_DIR) with open(p + '/templates/email.html') as f: order_message = f.read() for o in order: print(o._id) email = EmailMultiAlternatives(subject='Thank you', body=order_message, from_email='laksura.com.bd@gmail.com', to=['sohanur.shanto@northsouth.edu'] ) html_template = get_template('email.html').render() html_template = render_to_string('email.html', {'name': o.user, 'order_id': o._id, 'total': o.totalPrice, 'created': o.createdAt}) email.attach_alternative(html_template, "text/html") email.send() I am getting this error new_conn_created = self.open() File "C:\Python39\lib\site-packages\django\core\mail\backends\smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "C:\Python39\lib\smtplib.py", line 255, in __init__ (code, msg) = self.connect(host, port) File "C:\Python39\lib\smtplib.py", line 341, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Python39\lib\smtplib.py", line 312, in _get_socket return socket.create_connection((host, port), timeout, File "C:\Python39\lib\socket.py", line 843, in create_connection raise err File "C:\Python39\lib\socket.py", line 831, in create_connection sock.connect(sa) TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has … -
Python passing dynamic value to decorator arguments
Is there a way to pass a dynamic value on the decorator's argument from the function that decorates? For example, @cached_property_with_ttl(ttl=authenticate['expires_in']) def authenticate(self): response = requests.post( self.token_url, data={ "client_id": self.__client_id, "client_secret": self.__client_secret, "audience": self.audience, "grant_type": self.grant_type, }, ) return response.json() I want to get the JSON response from the authenticate() function and pass the "expires_in" from the JSON as a value to the decorator's ttl argument which decorates the authenticate function. -
postgis.control is not found on github actions
In my github actions yml, it can't find postgis.control. But, if find /usr -name postgis.control did, it can find postgis.control. I don't know why test can't find postgis.control.. Any idea? name: Django CI on: push jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.7] services: postgres: image: postgres:12 ports: - 5432:5432 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: ghostlabs_localhost options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: psycopg2 prerequisites run: | sudo apt-get update && sudo apt remove -y postgis* postgresql* && sudo apt-get install -y libpq-dev gdal-bin postgresql-12 postgresql-12-postgis-3 postgresql-12-postgis-3-scripts postgresql-contrib-12 echo "-----" find /usr -name postgis.control - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements/localhost.txt - name: Run Tests run: | python manage.py migrate && python manage.py test Log shows ----- /usr/share/postgresql/12/extension/postgis.control But, test has Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.7.11/x64/lib/python3.7/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.UndefinedFile: could not open extension control file "/usr/share/postgresql/12/extension/postgis.control": No such file or directory -
Serverside debug Django "Not Acceptable"
When calling an URL on my Django API it returns: [04/Sep/2021 08:14:47] WARNING [django.request:224] Not Acceptable: /api/calendar/test.ics Calling the same URL from PostMan (or curl) returns a simple iCal file so the URL is valid and returning. What I found was that the cause is the "Accept" headers sent by the client. The problem is that the request never actually hits my view so I cannot inspect request.META for the value of the received accept header. How can I discover, serverside, what headers were sent and what their values are? -
Django Rest Framework Permissions with firebase auth
I have backend with django-rest-framework, and frontend with react. And I have one endpoint which returns all users list. I want only admin be able to see all users list, so I put permission_classes = [IsAdminUser] in my view. I tested it with browsable api and everything works fine. Authentication system is with firebase in frontend, so every time when I send get request to server it returns authentication credentials were not provided because I don't use DRF endpoint to login, I use firebase login instead. So my question is how can I make only admin user see the data? -
How to create multi logins in django
How to create multiple user logins with different users with same browser address with different devices only using login page on django. I want all templates and pythons files. -
Django form - what's the right form/template to create a many to many object inline
I have to two models Directors and JobProject. A JobProject can have multiple directors through a many-to-many relationship. Currently, when I create a new JobProject I choose from the directors I have saved who the director will be. However, I am trying understand how can I code a form/view for creating a JobProject where I can also create a director in-line (in case I don't have the director already saved in the DB). Ideally the users'flow would be: 1) Start entering a JobProject details. 2) If the director already exist in the DB, pick it. 3) If the director doesn't exist, allow users to enter the details of a new director object in-line 4) Users go ahead and finish entering JobProject details. 5) Users click save and the BE first save the new director and then save the new project with director pointing at the newly created director. I basically have 1,2,4,5 figured out but I can't understand how to do 3. Any help? These is my code right now. Model class Director(models.Model): ... name_surname = models.CharField(max_length=60) class JobProject(models.Model): ... director = models.ManyToManyField(Director, blank=True, ) Form class DirectorForm(forms.ModelForm): class Meta: model = Director fields = '__all__' exclude = ('id', 'owner', … -
How to add block ip functionality to Django Website?
i'm trying to add block user IP functionality to my website. So if user is declined after registration, i have a choice to block user ip. I wrote a code which shows me the user IP. But could not figure out how to write a block user ip function. I am very new to Python/Django. Thanks in advance. -
How to detect lack of specific parameter in payload and go to except in Django?
I have a method like this: @csrf_exempt def my_method(request): if request.method == 'POST': try: name = payload['name'] return HttpResponse("YES", content_type='text/json') except payload['name'].DoesNotExist: return HttpResponse("NO", content_type='text/json') But i have getting several errors. Please help me to fix this as well i receive better way. -
Django NoReverseMatch at /services/ 'services' is not a registered namespace
I'm trying to display a group of images classified by category. When the user clicks on a category name, the page should display the images that belongs to that category. I'm getting the the next browser error: NoReverseMatch at /services/ 'services' is not a registered namespace . . . Error during template rendering The models belongs to different apps, one (that contains the Category model) works fine, and this other (That contains the Services model) just works if I delete the html content that I need. Help me please. Here are my files: home_app/models.py from django.db import models from django.urls import reverse class Category(models.Model): name=models.CharField(primary_key=True, max_length=50) slug=models.SlugField(unique=True, blank=True, null=True) image=models.ImageField(upload_to='category_home') description=models.CharField(max_length=100) content=models.TextField(max_length=500, default="Service") created=models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('services:services_by_category', args=[self.slug]) services_app/models.py from django.db import models from home_app.models import Category class Services(models.Model): category=models.ForeignKey(Category, on_delete=models.CASCADE) title=models.CharField(max_length=50) completed=models.DateField(auto_now_add=False, null=True, blank=True) content=models.CharField(max_length=50, null=True, blank=True) image=models.ImageField(upload_to='services_services') created=models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Service' verbose_name_plural = 'Services' def __str__(self): return '%s de %s' % (self.category, self.title) services_app/views.py from django.shortcuts import render, get_object_or_404 from .models import Services from home_app.models import Category def service_list(request,category_slug=None): category = None categories = Category.objects.all() services = Services.objects.all() if category_slug: category = get_object_or_404(Category,slug=category_slug) … -
Filtering multiple models in Django
I want to Filter across multiple tables in Django. q = json.loads(request.body) qs = Search.objects.filter(keyword__icontains=q['q']).all() data = serialize("json", qs, fields=('keyword', 'user')) That's one, secondly, the user field is returning an integer value (pk) instead of maybe the username. -
why cant import Celery from celery
When i putted my project on production even with runserver test this error did not raised but when i used gunicorn --bind for test this happens import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sqh.settings.dev') app = Celery('sqh',broker_url = 'redis://localhost:6379/0') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks() #@app.task(bind=True) #def debug_task(self): # print(f'Request: {self.request!r}') ImportError: cannot import name Celery -
Django ERROR: Reverse for 'jobs' not found. 'jobs' is not a valid view function or pattern name
I have been trying to display the list of jobs in the template and when i call archived or current jobs url .i am getting the following error only when there is some jobs available Thanks in Advance Traceback Environment: Request Method: GET Request URL: http://localhost:1000/customer/jobs/current/ Django Version: 3.2.6 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4', 'social_django', 'core.apps.CoreConfig'] Installed 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', 'core.middleware.ProfileMiddleware'] Template error: In template C:\Users\Subash A\venvdelivo\delivo\core\templates\base.html, error at line 0 Reverse for 'jobs' not found. 'jobs' is not a valid view function or pattern name. 1 : <!DOCTYPE html> 2 : <html lang="en"> 3 : <head> 4 : <meta charset="UTF-8"> 5 : <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 : <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 : <title>Home</title> 8 : {% load bootstrap4 %} 9 : {% bootstrap_css %} 10 : {% bootstrap_javascript jquery='full' %} Traceback (most recent call last): File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Subash A\venvdelivo\delivo\core\customer\views.py", line 145, in current_jobs return render(request,'customer/jobs.html', { File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\shortcuts.py", line 19, in render content … -
How to show list data in Django Template?
I have a field receiver_address in my Booking Model I am storing list of address details as Road number, House number and Others. For example ['25 jalan', '35','Others'] Now i want to show data in my booking list. My Django template code {% for adress in booking.receiver_address %} address {% endfor %} But it's not working. I am willing to see as like 25 jalan,35,others in my booking list. My present result in this . How can i get full address as 25 jalan,35,others. -
How to Run Crontab within a Django Virtual Environment?
I'm running into issues when running a cron (using Crontab) within my Virtual Environment. If I do: python manage.py crontab add Terminal returns: sh: line 1: /usr/bin/crontab: No such file or directory (but it does recognise the details of the cronjob): /bin/sh: line 1: /usr/bin/crontab: No such file or directory adding cronjob: (325473fff5b0bfd8ec611f26efe10e43) -> ('*/1 * * * *', 'core.cron.my_scheduled_job') If I do: which crontab Terminal returns: which: no crontab in (/......../venv/bin:/app/bin:/usr/bin) It seems pretty clear this is a file routing problem, I just can't figure out a way to resolve, and there doesn't seem to be any similar cases I can find online. If relevant, I'm running this locally on Linux currently -
app[web.1]: Not Found: /static/js/index.js
This is my settings file from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) SECRET_KEY = '...' DEBUG = True ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'game' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'reverenz.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'game', 'templates', 'game')], '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', ], }, }, ] AUTH_USER_MODEL = 'game.User' WSGI_APPLICATION = 'reverenz.wsgi.application' DATABASES = { 'default': { 'ENGINE': '..', 'NAME': '..', 'USER': '..', 'PASSWORD': '..', 'HOST': '..', 'PORT': '..', } } 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', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") MEDIA_URL = '/img/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' Here is my folder structure The project works fine on localserver but whenever I try to host it on Heroku, the js, css and img files don't get linked and in the heroku logs i see-> app[web.1]: Not Found: /static/js/index.js Any assistance in this … -
AttributeError: 'MigrationLoader' object has no attribute 'items' django migration error
i had sqlite conflict error, after merging i got another sqlite regex match error so i deleted migrations and sqlite files. when i run 'python manage.py makemigrations' i got this error and i don't know how to solve. File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/manage.py", line 22, in <module> main() File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py", line 125, in handle for app, names in conflicts.items() AttributeError: 'MigrationLoader' object has no attribute 'items' -
error loading data when deploying django with apache2
I have a django app working fine with runserver, but when I deployed it with apache2 and mod_wsgi I got this weird error: [Sat Sep 04 11:16:12.218713 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] 2021-09-04 11:16:12,217 WARNING load Error occurred during loading data. Trying to use cache server https://fake-useragent.herokuapp.com/browsers/0.1.11 [Sat Sep 04 11:16:12.218795 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] Traceback (most recent call last): [Sat Sep 04 11:16:12.218805 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] File "/home/stockenv/lib/python3.8/site-packages/fake_useragent/utils.py", line 154, in load [Sat Sep 04 11:16:12.218825 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] for item in get_browsers(verify_ssl=verify_ssl): [Sat Sep 04 11:16:12.218842 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] File "/home/stockenv/lib/python3.8/site-packages/fake_useragent/utils.py", line 99, in get_browsers [Sat Sep 04 11:16:12.218850 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] html = html.split('<table class="w3-table-all notranslate">')[1] [Sat Sep 04 11:16:12.218870 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] IndexError: list index out of range I don't understand the error at all! -
pip freeze raises an error cannot import name 'SCHEME_KEYS' pip._internal.models.scheme import SCHEME_KEYS, Scheme
In Django app on ubuntu, I tried to use pip freeze, it suddenly raises an error from pip._internal.models.scheme import SCHEME_KEYS, Schem, it cannot import 'SCHEME_KEYS'. Any clue?