Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to get each client video frame on django server in agora
Here is the scenario that I want to do with agora. Assume that there are N users connected on the same channel in the agora. I want to access the video frame of each user on the server-side so that I can apply AI and process that frame on the server and save their activity log into the database. How can I achieve this? I tried with https://github.com/AgoraIO-Community/Agora-Python-QuickStart but nothing seems to work for me. -
How to get queryset in django?
I am trying to send an email to those orders that is created 5 minutes before the datetime.now(). I try to filter the orders but it is not working, it is not giving me any queryset. How to do this? I am sharing my code. def my_email(): now = datetime.now() - timedelta(minutes=5) # 11:55 now = now.replace(tzinfo=pytz.utc) print(now) order = Order.objects.filter(createdAt__gt = now) print(order) for o in order: print(o._id) -
how to change herkou region from us to eu
i have pre deployed app on heroku but b default it region is us and i am from india so my load time is very much then expected so i want to change region to eu which exactly half of distance from us so my load time will improved i also tried the documentation https://devcenter.heroku.com/articles/app-migration but i falied to migrate if someone did it before please guide me step by step it would be very helpful for me and other future reader thank you for your time -
Django: Non-primary Foreign Key object can't access related model instance
I'm new in Django. I have 2 class tech_system adn equiptment in models.py class tech_system(models.Model): id_tech_system = models.BigAutoField(db_column='ID_tech_system', primary_key=True) system_descript_short = models.CharField(max_length=255, blank=True, null=True) #More field here tech_system_code = models.CharField(unique=True, max_length=40) class Meta: managed = False db_table = 'tech_system' def __str__(self): return self.system_descript_short class equiptment(models.Model): id_thietbi = models.BigAutoField(db_column='ID_thietbi', primary_key=True) tech_system_code = models.ForeignKey('tech_system', models.DO_NOTHING, db_column="tech_system_code", blank=True, null=True) class Meta: managed = False db_table = 'equiptment' I use python shell, equiptment model object can't access to related tech_system model instance. I got the error matching query does not exist. I want to get the value obj1.equiptment.tech_system_code.system_descript_short. How can I do? Thank you. >>> obj1 = equiptment.objects.first() >>> obj1.tech_system_code_id '530' >>> obj1.tech_system_code Traceback (most recent call last): File "D:\Dev1\env1\lib\site-packages\django\db\models\fields\related_descriptors.py", line 173, in __get__ rel_obj = self.field.get_cached_value(instance) File "D:\Dev1\env1\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'tech_system_code' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> File "D:\Dev1\env1\lib\site-packages\django\db\models\fields\related_descriptors.py", line 187, in __get__ rel_obj = self.get_object(instance) File "D:\Dev1\env1\lib\site-packages\django\db\models\fields\related_descriptors.py", line 154, in get_object return qs.get(self.field.get_reverse_related_filter(instance)) File "D:\Dev1\env1\lib\site-packages\django\db\models\query.py", line 437, in get self.model._meta.object_name app.models.tech_system.DoesNotExist: tech_system matching query does not exist. -
Django ORM - Primary key not available after save while using UUIDField and RandomUUID In Postgres
For a project I'm working on, in one of the models i am using models.UUIDField for primary key with the default value set to django.contrib.postgres.functions.RandomUUID Here's my model. from django.contrib.postgres.functions import RandomUUID from django.db.models import JSONField class NewsItem(models.Model): id = models.UUIDField(primary_key=True, default=RandomUUID()) title = models.ForeignKey(RichText, models.DO_NOTHING, related_name='+', null=True) subtitle = models.ForeignKey(RichText, models.DO_NOTHING, related_name='+', null=True) excerpt = models.ForeignKey(RichText, models.DO_NOTHING, related_name='+', null=True) text = models.ForeignKey(RichText, models.DO_NOTHING, related_name='+', null=True) image = models.ForeignKey(ImageObject, models.DO_NOTHING, related_name='+', null=True) priority = models.IntegerField(null=True, default=0) frequency = models.IntegerField(null=True, default=1) text_effects = JSONField(blank=True, null=True, default=dict) scroll_speed = models.IntegerField(null=True, default=1) scroll_direction = models.IntegerField(null=True, default=0) created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) updated_at = models.DateTimeField(blank=True, null=True, auto_now=True) class Meta: managed = True db_table = 'news_items' The issue here is that i need to immediately access the primary key after the object has been inserted into the database, however trying to access pk or id after calling save simply returns a literal string RandomUUID() In [1]: from media.models import NewsItem In [2]: n = NewsItem() In [3]: n.save() In [4]: n.id Out[4]: RandomUUID() In [5]: str(n.id) Out[5]: 'RandomUUID()' However, if i issue a query like model.objects.first() or model.objects.last() and then access the id or pk of the returned instance, it works as expected. In [6]: … -
Django how do I run a backend python function using GraphQL
I am using ariadne for graphql and Django in the backend with Vue in the front. How do I send the variables from vue to run a function in the backend? I am trying to do this REST API example except in GraphQL: Run Python script from rest API in django -
How to avoid to_representation to not be used in Child class from parent class using python and django?
i want to not use a to_representation method defined in Parent class to be used in child class. i have a Parent class AccessInternalSerializer and child class AccessSerializer. below is my code, class AccessInternalSerializer(AccessBaseSerializer): private_key = serializers.FileField( allow_null = True, required=False) ca_cert = serializers.FileField( allow_null = True, required=False) class Meta(AccessBaseSerializer.Meta): model = Access extra_kwargs = { 'password': { 'trim_whitespace': False } } class AccessSerializer(AccessInternalSerializer): private_key = serializers.FileField( write_only=True, allow_null=True, required=False) ca_cert = serializers.FileField( write_only=True, allow_null=True, required=False) class Meta(AcessInternalSerializer.Meta): extra_kwargs = { **AccessInternalSerializer.Meta.extra.kwargs, 'private_key': { 'write_only': True } 'ca_cert': { 'write_only': True } } the above code works. but the AccessusernameInternalSerializer wasnt returning private_key and ca_cert fields in the output hence i used to_representation in the AccessInternalSerializer like below, class AccessInternalSerializer(AccessBaseSerializer): private_key = serializers.FileField( allow_null = True, required=False) ca_cert = serializers.FileField( allow_null = True, required=False) def to_representation(self, obj): data = super().to_representation(obj) data['private_key'] = obj.private_key data['ca_cert'] = obj.ca_cert return data class Meta(AccessBaseSerializer.Meta): model = Access extra_kwargs = { 'password': { 'trim_whitespace': False } } the above code works. it returns private_key and ca_cert fields in the output. but it also returns these fields private_key and ca_cert fields in the AccessSerializer class (child class) i think its because of to_representation in AccessInternalSerializer (that … -
Invoking a function everytime when django server is closed
I am using yield function and want to store its state everytime the server is closed. Is there any method to do it ? -
what i wrote in admin.py didnt appear , i dont have idea what happening here? i think there is not problem [closed]
https://github.com/Angelheartha/tera this is my github i wrote before i dont have idea why after writting at admin.py it cant reflect as if i didnt write any code when i do http://127.0.0.1:8000/admin ? i thought because i missed something at setting.py but it seems not the case... in admin.py something too ,but is seems not i dont know what is the problem here i did python manage.py migrate but not change so what can be the problem?