Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Separating translated Django URL patterns in apps
This is Django's way of translating URL patterns: https://docs.djangoproject.com/en/3.1/topics/i18n/translation/#translating-url-patterns The example works, however, it seems to go against one of Django's main design principles, i.e., keeping apps as reusable and independent as possible from the project in which they are. How can I take the news_patterns variable from the example above and decentralize it in an app/urls.py file? -
How to return two different error messages when querying the same model in Django
Take a look at the following: def mutate(self, info, first_id, second_id): try: first = Model.objects.get(pk=first_id) second = Model.objects.get(pk=second_id) except Model.DoesNotExist: return Exception('Object does not exist.') else: ... How can I return a custom error message depending on which of the ids actually does not exist? It's be nice to have something like: {first_id} does not exist I can't have two different except blocks because it's the same Model. What to do? -
how to get the status of running tasks with TaskResult
I have a running celery task. I want to get the status of the task with django_celery_results. But I noticed that the model only gets updated once the task completes running. How do I get the status of a running task with TaskResult? Example views def test(request): task_id = test_task.delay() status = TaskResult.objects.filter(task_id=task_id) print(status) When I run the above view this is the result I get <QuerySet []> -
Pyinstaller django Issue
Please, I have an issue with Pyinstaller and Django App (Django 3) with mongodb as database. the Exe is generated with a manage.spec file but when I run manage.exe runserver "settings.pyc" file is unfound.. It seems that settings.py is not detected . Please could you help me? Here is my manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys import django.test from django.conf import settings def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Test_Project.settings') print(settings.GDAL_LIBRARY_PATH) try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() and here is my manage.spec # -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis(['test_project\\manage.py'], pathex=['C:\\Users\\SFadili\\Documents\\\\Django\\help\\Test_Project'], binaries=[], datas=[ ('test_project/test_app/templates', 'templates'), ], hiddenimports=[ 'test_app.apps', 'test_app.urls', ], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='test', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, upx_exclude=[], runtime_tmpdir=None, console=True ) -
compare database table rows in Django
I want to populate data from a database in a table. And each row will have a checkbox, And on the top a compare button. So basically i want to compare all the fields of the selected row with other selected rows on a new page -
Django 3 update value of a ManyToMany field Boolean
I'm creating an exam app Many Questions to Many Exams. One of the parameters is 'is_correct', which is a bool. for some reason, when i save the 'is_correct' on a question, the field changes globally (on the Question model) and become 'True' / 'False' to every one. How can i update the specific question for the specific exam only? Current code: exam_data = Exam.objects.get(exam_token=exam_token) if request.method == 'POST': choice = request.POST.get('answer') question_id = request.POST.get('question_id') correct_answer = exam_data.questions.get(id=question_id).answer if choice == correct_answer: question = exam_data.questions.get(id=question_id) question.is_correct = True # Change to True question.save() # After saving here, it changes for the model globally else: ...same but for False... -
Django Apscheduler execute at specific time each day
I would like to execute some code at a 11:59 PM each day (Africa/Johannesburg) time. from apscheduler.schedulers.background import BackgroundScheduler from updateRoot import updateApi scheduler = BackgroundScheduler() scheduler.add_job(updateApi.main, 'interval', days=1) scheduler.start() The code only executes a day after I start the server, which is not what I want to accomplish. Any ideas how to include the functionality into this code snippet? Thanks -
How to create Object in Django based on MySQL query conditions?
For single "id" in table there are multiple "companyid's", want to create an object, for these group of multiple companyid for single id. Q. How can i write similar conditions shown in below query (condition in where clause)into Object shown below. Below is the MySQL query: SELECT ID, company, group_concat(companyid), count() FROM organization where comapany in ("ABC") and ID is not null group by comapany, ID having count() > 1; This is how i tried to create object:(please correct this object according to above MySQL query conditions) Idmap_Obj = organization.objects.using("default").filter(comapany="ABC").values('id','comapany').annotate(Sum('companyid')).filter(cnt__gte=2) Note: organization is table name, default is database name -
Why can't i display my model foreign key instance in Django?
This worked just fine in my other project but now it doesn't work. Is there something wrong with my code? I followed these but nothing worked for me: How to display Foreign key Data in Django view page?, How to access foreign key in a django template? (DetailView), Django foreign key query, why it returns None? models.py class Author(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author_name') description = models.TextField(blank=True, null=True) class Post(models.Model): author_info = models.ForeignKey(Author, on_delete=models.SET_NULL, related_name='author_info', default=None, null=True) html template (this one is a generic.DetailView) {{ post.author_info.description }} EDIT: views.py class PostDetail(generic.DetailView): model = Post template_name = 'blog/blog_detail.html' -
Gitlab CI set up django postgres service
I am facing this service for hours but still I do not have solutions. My gitlab.yml looks like this image: python:3.6 services: - postgres:latest variables: POSTGRES_DB: test POSTGRES_USER: postgres POSTGRES_PASSWORD: "" POSTGRES_HOST_AUTH_METHOD: trust job:on-schedule: only: - schedules script: - export DATABASE_URL=postgres://postgres:@postgres:5432/test - apt-get -yq update - apt-get -yq install python-pip - pip install -r requirements.txt - python manage.py test and settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'postgres', 'PORT': '5432' } } at first I have come about a connection error like is it listening to 5432 and locally etc. Now I am facing time out. All processes passed when it comes to the python manage.py test it does not run next. I do not know why. Please anybody can help??? Thanks in advance -
Uncaught TypeError: Cannot read property 'then' of undefined problem
the update works after i send it to the API const UpdateClick = () =>{ API.updateMovie(props.editdMovie.id,{title,description}).then(resp => console.log(resp)) } but when I get to the then part its fall the api part export class API{ static updateMovie(mov_Id,body){ fetch(`http://127.0.0.1:8000/api/movies/${mov_Id}/`,{ method : 'PUT', headers : { 'Content-Type' : 'application/json', 'Authorization' : `Token ${TOKEN}` }, body : JSON.stringify( body ) }).then(resp => resp.json()) } } -
Occasional 404 error in aws nginx django app (restframework)
Hi I am using aws server with average cpu load of 60-70% made in django(restframework) with nginx server and flutter frontend. The problem is sometimes it gives occasional 404 error but on refreshing the page (api) it works fine. How should I debug this? I was thinking of cpu overload but in monitoring section of aws ec2 , it shows the max load is around 80% and average load is aroung 60-70%. This problem has started recently with no changes in the code. What are the steps I should take to debug this? -
Why Django List Iterator's item doesn't return?
In my database, I have 2 table Spider Table: id, spider_name Market Table: market_timezone, market_location, market_year, market_day, market_month I have list iterator like this: @register.filter def getSpiderItem(datas, spider_id): return iter(datas.filter(spider=spider_id)) @register.filter def market_timezone(iitem): return next(iitem)['market_timezone'] @register.filter def market_location(iitem): return next(iitem)['market_location'] @register.filter def market_year(iitem): return next(iitem)['market_year'] And my Django-template like this: <td>{{markets|getSpiderItem:spider.id|market_timezone}}</td> <td>{{markets|getSpiderItem:spider.id|market_location}}</td> <td>{{markets|getSpiderItem:spider.id|market_year}}</td> The First 2 function works well and the outputs don't have any problem but when I try to get the third one it returns: Exception Type: KeyError Exception Value: 'market_year' It works by itself and my database doesn't have any NULL element. I also try market_month, market_day, or another table. However, it gives me "Key Error" all the time at third return. -
Django ORM: Join two tables using a linked table
I want to integrate a function has_permission(self, permission_name) in the class Profile. For this I want to do make a ORM statement which returns a list of permission names. The data model is: 1 User has 1 Profile (extends Django's User model) Each Profile is assigned to one ProfileGroup. However, different Profiles can belong to the same ProfileGroup. Each ProfileGroup can have one or more ProfilePermissions. Groups can have the same subsets of ProfilePermissions. The Link-Table GroupPermissions handles this using two ForeignKeys instead of a ManyToMany relation. My models.py looks like this: class ProfileGroup(models.Model): name = models.CharField(max_length=64) class ProfilePermission(models.Model): name = models.CharField(max_length=64) class GroupPermissions(models.Model): group = models.ForeignKey(ProfileGroup, on_delete=models.RESTRICT) permission = models.ForeignKey(ProfilePermission, on_delete=models.RESTRICT) class Meta: constraints = [ models.UniqueConstraint(fields=['group', 'permission'], name='Unique') ] def __str__(self): return f'Group "{self.group.name}" has permission "{self.permission.name}"' class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) group = models.ForeignKey(ProfileGroup, on_delete=models.RESTRICT) def __str__(self): return f'Profile of {self.user.username}' def has_permission(self, permission_name): return True The function has_permission (in the Profile class) should check if the permission permission is included in the list of Permissions. I tried it with list_of_permissions = GroupPermissions.objects.filter(group=self.group) But this returns a list of ProfilePermission. What I want is a list of names of the permission (permission.name). So I have to … -
Forms DateField with automatic separators
If i create a form with a standard forms.DateField() the user has to manually type "01-01-2001". How can i create an input such as the user types in "01012001" straight and the "-" separators will still be there as a default? Is this a django thing or javascript? If i could get some examples that would be great. -
Update Profile model that extends default User with middleware (last_activity field) DRF
I'm trying to update Profile model, which extends the default User model. But something clearly off because Profile displays no entries. Could you please suggest how to properly update model in middleware that extends another one? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) last_activity = models.DateTimeField() # filled in by middleware def __str__(self): return str(self.id) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' view.py class ProfileList(ListAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer middleware.py from django.utils import timezone class UpdateLastActivityMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_response(self, request, response): if request.user.is_authenticated(): # Update last visit time after request finished processing. # I'm trying to create record - in case user had no activity before Profile.objects.filter(user__id=request.user.pk).update_or_create(last_visit=timezone.now()) return response settings.py MIDDLEWARE = [ ... 'core.middleware.UpdateLastActivityMiddleware', ] -
Configuring existing django project on a linux shared hosting using cpanel
I want to make my django project live. I am having trouble in uploading and running my existing Django project on cpanel. -
Django, Sqlalchemy: Cannot drop table ganalytics_article because other objects depend on it
I have this models in my Django ganalytics app: class Article(models.Model): id = models.IntegerField(unique=True, primary_key=True) article_title = models.CharField(max_length=250) article_url = models.URLField(max_length=250) article_pub_date = models.DateField() def __str__(self): return "{}".format(self.article_title) class Company(models.Model): company_name = models.CharField(max_length=250) class Meta: def __str__(self): return "{}".format(company_name) class Author(models.Model): author_sf_id = models.CharField(max_length=20, null=True) author_name = models.CharField(max_length=250) class Meta: def __str__(self): return "{} - {}".format(self.author_name, self.author_sf_id) class AuthorArticleCompany(models.Model): author = models.ForeignKey(Author, to_field="id", on_delete=models.CASCADE, related_name='authorarticle_author_id') company = models.ForeignKey(Company, to_field="id", on_delete=models.CASCADE, related_name='authorarticle_company_id') article = models.ForeignKey(Article, to_field="id", on_delete=models.CASCADE, related_name='authorarticle_article_id') class Meta: def __str__(self): return "{}-{}-{}".format(self.author, self.article, self.company) class Ganalytics(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='ganalytics_author_id') totalview = models.IntegerField() totalinteractions = models.IntegerField() class Meta: def __str__(self): return "{}".format(self.article) class Unsubscribers(models.Model): email = models.EmailField() reasonwhy = models.CharField(max_length=90) class Meta: def __str__(self): return "{}".format(self.email) I am getting this error message: DETAIL: constraint ganalytics_ganalytic_article_id_d37f2464_fk_ganalytic on table ganalytics_ganalytics depends on table ganalytics_article constraint ganalytics_authorart_article_id_7f4ff374_fk_ganalytic on table ganalytics_authorarticlecompany depends on table ganalytics_article HINT: Use DROP ... CASCADE to drop the dependent objects too. [SQL: DROP TABLE ganalytics_article] I have tried to change the on_delete field to different values but it wont help. What am I doing wrong? -
Video group conference using Django
How to use Webrtc with Django ?? I think That I shall use django-webrtc module for this but i havee already tried this with node js or directly use rtcmulticonnection javascript library for room connection. Can anyone recommend me how to use Django for peer to peer mesh networking model or star networking model -
404 on a link and no idea why
I generate a link using javascript that assigns devices to a location. The underlying information comes from a product and I am using a TemplateView which redirects after it is done: class AssociateView(TemplateView): model = Product template_name = "app/product_all.html" def get(self, request, *args, **kwargs): device_ids = request.GET["device_ids"] page = request.GET["page"] ... some logic ... return redirect("product-all") the corresponding url pattern: path(r'link/<int:pk>', views.AssociateView.as_view(), name="link"), Error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/link/8/?device_ids=659252%2C659260%2C743044%2C743045&page=2 The current path, link/8/, didn't match any of these. -
How can I verify user and password using Python ldap3 via OpenLdap?
For a django project, I designed a different login page. The users here will log in via openldap. I can access users' full information with their uid id, but I could not find how to verify the password. Do I need to hash the user's password and compare it with the password on ldap? Isn't there any other method? Thank you from ldap3 import Server, Connection, ALL, SUBTREE from ldap3.core.exceptions import LDAPException, LDAPBindError, LDAPSocketOpenError from ldap3.utils.conv import escape_filter_chars ldap_server_uri=f"ldap://xxx:389" ldap_base = 'dc=xx,dc=xx,dc=xx' def ldap(uid,password): try: ldap_server = Server(ldap_server_uri, get_info=ALL) ldap_connection = Connection(ldap_server, user = 'uid=admin,ou=xx,dc=xx,dc=xx',password='adminpassword') if ldap_connection.bind() == True: if ldap_connection.search(search_base=ldap_base, search_filter=f'(uid={uid})',search_scope = SUBTREE, attributes=['uid']) == True: ent = ldap_connection.entries[0] entry = {'uid': ent['uid']} ldap_connection.unbind() return entry else: return None except LDAPSocketOpenError: print('Unabled to connect to the LDAP server!') return None -
django cannot overwrite STATIC_URL
I want to upload my static files to my azure blob, and I changed the default static url to STATIC_URL = "https://myazurestorage.blob.core.windows.net/static/" STATIC_ROOT = os.path.join(STATIC_URL, 'staticfiles') and I have this settings in my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'adminrestrict', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] 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', 'adminrestrict.middleware.AdminPagesRestrictMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.static', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', if I print out {{STATIC_URL}} in my html files, it always shows /static/ I have been stuck in this problem for a few hours, can anyone give me a hint, please. -
override __str__ method that allow display conditionnal string based on browser language
I have a Django project that is internationalized I have a model Pays that contain 2 fields (french and english) to manage translation In my form, I have a ModelChoice Field that display a list of country in french How can I manage language in Pays model str method ? def __str__(self): return f"{self.pay_nom_eng}" ... self.language = request.session.get('language') PAYS = Pays.objects.filter(pay_ran = 1).order_by('pay_ide') ... self.fields["pay_ide"] = forms.ModelChoiceField(queryset = PAYS, label = _("Country"), widget = forms.Select) -
Django static file href incorrectly formatted
So I have the following static loading in Django with DEBUG=True: {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}"> Now in my settings.py I have the following: STATIC_URL = "/static/" When I run the server python manage.py runserver and inspect my webpage in the console, the sources appear correctly, but the href attribute points to /static/css/styles.css, rather than static/css/styles.css (notice the omission of the leading /). Notice that the href on line 18 points to the wrong folder, but static/css appears correctly in the sources. So, clearly django, behind the scenes, just replaces {% static 'css/styles.css' %} with STATIC_URL + 'css/styles.css'. If I now change STATIC_URL to STATIC_URL = "static/" The href is correct (points to the right file) but the files themselves are not present!! So in order for the css file to appear, STATIC_URL needs to be /static/, but the href references a non-existent directory. If I change STATIC_URL to static/ the href is correct, but the files don't appear! Does anyone know how to fix this? I feel like it's such a basic problem, but it's doing my head in... -
How can I print the respnse json format datat in a table format in jinja template? Every time when I hit url I got 'Could not parse the remainder:'
"I want to print these response in template in table format using django but it gives "could not parse".I tried to resolve but failed. Someone please help.Below is the response which I am getting and want to print in template.I get this data when I hit an url in views.py file." { "display_free": 1, "display_paid": 1, "free": [ { "city": "", "confEndDate": "19 Feb, 2020", "confName": "AWS Innovate Online Conference", "confRegUrl": "https://aws.amazon.com/events/aws-innovate/machine-learning/", "confStartDate": "19 Feb, 2020", "confUrl": "https://aws.amazon.com/events/aws-innovate/machine-learning/", "conference_id": 1579503272, "country": "", "emailId": "", "entryType": "Free", "imageURL": "https://storage.googleapis.com/konfhub-bd9c9.appspot.com/54497.jpg?Expires=4733103270&GoogleAccessId=firebase-adminsdk-r3qh4%40konfhub-bd9c9.iam.gserviceaccount.com&Signature=GSihzq4Vf8koeEGcawKXeQmwT%2FQLZhooWUS%2BqJeNtPXtJqnNfky%2F5RgeOTEWKYCEjqAGFLSEx02cCdZ8CBTO7T2HlMjAZl6yTmDRMTH5mNawUHOrxqjsiNzSwCj4KLqHo8KlEqQrgE%2FTbxmWpT28zKfoOS20C88HrDXFMELmj5aHi4f0V%2BTF30rIlQJkNlFy6fkko2ipkLLxtYOMh0i%2B0tV1vZ0gI21mlpyNzfn6hC%2BGtN1BIz4BciB4IpMkkw7FUydFbXwJOVNm2FJs9AafozJdwdy0gOCtFDrMB2wY8JiPL2oSa%2BkBFlhIgjnIg3LaCPlfj%2Bqn9FTT%2FP5TrOioSg%3D%3D", "keywordSupport": " Artificial Intelligence ,Machine Learning,Cloud", "lat": "", "long": "", "searchTerms": " AWS Innovate Online Conference, Artificial Intelligence ,Machine Learning,Cloud, Online, February, Free, 1579503272, India", "state": "", "twitter_handle": "", "user_id": "1578287153", "venue": "Online" }, { "city": "Bangalore", "confEndDate": "22 Jan, 2020", "confName": "Redis Day Bangalore", "confRegUrl": "https://connect.redislabs.com/redisdaybangalore", "confStartDate": "21 Jan, 2020", "confUrl": "https://connect.redislabs.com/redisdaybangalore", "conference_id": 1578891826, "country": "India", "emailId": "", "entryType": "Free", "imageURL": "\"https://storage.googleapis.com/konfhub-bd9c9.appspot.com/5887.jpg?Expires=4732491826&GoogleAccessId=firebase-adminsdk-r3qh4%40konfhub-bd9c9.iam.gserviceaccount.com&Signature=JF33AcXB854Ndqw4VRN29NTQow51wGfuCSnAMIvmUUuZcmUEto3eREIrNYgqKqUpuRvGG8NIw3or6Jj8uTtl5dWVNaI93S5heRFhl3NJ1fj9zETiNE9tp6gcv1BiIkyJGCEJzXWxgUpNuqrq%2BUPzQGq4o6w1bQ0izgFP%2Fe5XhvOQmYvWDpnvsltvdppY8%2FFuVm3G13xZH3h5utMleXXqcKjGkf%2FqXHf4gSrMESrfbAZ0MPXRhZS9mGxiE2hg7DHcOweZkEY6spfLrVS2%2BEIePF4ZeXNDeDxv3bgOH6hX3VlyQFKcRCvvDzVWpvYubr0d8PJ7DK9OuMZWMmXe96BK9A%3D%3D\"", "keywordSupport": " Redis, Redis Clustering, Probabilistic Data Structures", "lat": "13.0291377", "long": "77.540708", "searchTerms": " Redis, Redis Clustering, Probabilistic Data Structures, Redis Day Bangalore, Bangalore, January, Free, 1578891826, India", "state": "Karnataka", "twitter_handle": "@redislabs", "user_id": "1578287153", "venue": "Taj Yeshwantpur, Bengaluru, 2275, Tumkur Road, Yeshwanthpur Industrial Area, Phase 1, Yeshwantpur, Bengaluru, Karnataka …