Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
On Prem Django app login with Azure AD Credentials
I have a usecase, we have a Django application running in onprem and it has admin login page, we have few users in Azure AD, we dont have any onprem AD, i want users to be authenticate with Azure AD, Can someone guide me how can this be achieved. Thanks Niranjan. -
Redirect viewset to another viewset on Django Rest Framework after parsing data
Say I have a viewset A, where I will receive a bunch of data via querystring. I want to parse this querystring on viewset A, and then redirect the request with the parsed querystring to viewset B. How would I go about doing this? I've tried insatiating the viewset B inside of A and then calling the get method manually to no avail. -
ModuleNotFoundError: No module named 'project_calxr'
I tried to deploy my website on Render but I got an error. this is my project CALX This is my setting in render log pic1 log pic2 This is a log that I got from deploying my website I am very new to coding. This is my first project. Sorry if I do something bad. I searched and tried many ways but still can't fix this. I'm not good at English, but I will use grammar to make you all understand what I want. I hope I can find a way to solve this error. I checked my file many times. I ask chat get. I watched the whole clip I found on YouTube. I try to translate and read some websites. -
How to configure solr with django-haystack
I am running solr 9.3 from docker and trying to integrate with django-haystack. I am unable to configure solrconfig.xml and schema.xml and not sure where to add these files. I tried generating schema.xml using python manage.py build_solr_schema but again I don't know how/where to put these files. Thanks in advance. -
How To Host Multiple Vite Apps in One Django Project?
Problem How would I host multiple vite applications built on different architectures (vanilla and react) in the same Dango instance? I have a a django app that had a pre-es6 javascript front end that I converted to a vite vanilla javascript application, delivered using the wonderful Django-Vite plugin. The app is working fine, but now there's a request to add a new react-based vite app to the existing django project, and django-vite does not support hosting multiple vite applications out of the box. Thoughts Have a single vite app that would redirect to another vite app, one of the two I need to build (not sure how this would work) Merge both vite manifest.json files together at build time to be served from a single location (don't know what the ramifications would be) ~Host a NextJS app external to Django~ (insert unicorns and rainbows here) <-- Can't do this one because leadership thinks integration would be more effort than it's worth Thanks! -
error in migrating django project with mysql database
when i want to migrate my django project with mysql as database i get this error: django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[] NOT NULL, `source` varchar(200) NOT NULL)' at line 1") this is my models.py file : from django_mysql.models import ListCharField from django.db import models # Create your models here. class news(models.Model): title = models.CharField(verbose_name='title of the news', max_length=200) text = models.TextField(verbose_name='news text') tags = ListCharField(base_field=models.CharField(max_length=200), max_length=200) source = models.URLField(verbose_name='news source url') #class Meta: # ordering = ['?'] def __str__(self): return self.title what should o do to fix it? these are versions for packages: Django==4.2.4 django-mysql==4.11.0 PyMySQL==1.1.0 mysqlclient==2.2.0 and this is mysql version installed in my system. mysql Ver 8.0.33-0ubuntu0.22.04.4 for Linux on x86_64 ((Ubuntu)) i tried to upgrade mysql but i get this error: E: Unable to locate package mysql -
nginx media files not at the intended location
I am working on a Django-React project and all my media files are located in the frontend folder. I am trying to serve the media files with nginx this is my first time working with Docker and nginx and I can't figure out how to make it work. can anyone help please? my file struckture is -backend (django-project) -Dockerfile -backend -settings.py -fontend (react-project) -Dockerfile -src -assets (media root for django and react) -nginx -Dockerfile -nginx.conf -docker-compose.yml My backend Dockerfile: # Use the official Python 3.11 image FROM python:3.11 # Copy the Django application code COPY . /app # Set the working directory WORKDIR /app # Install the dependencies RUN pip install -r requirements.txt # Expose port 8000 EXPOSE 8000 My frontend Dockerfile: # Use the official Node.js 16.13 image FROM node:16.13 # Copy the React application code COPY . /app # Set the working directory WORKDIR /app # Install the dependencies RUN npm install # Expose port 3000 EXPOSE 3000 # Start the React development server CMD ["npm", "start"] My nginx Dockerfile: # ./nginx/Dockerfile FROM nginx:latest # Set working directory WORKDIR /app # Copy Nginx configuration COPY ./nginx.conf /etc/nginx/nginx.conf the nginx.conf: events { worker_connections 1024; } http { server { … -
How to fix this: Reverse for 'post_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<slug>[^/]+)/\\Z']
I am creating a Search filter for my blog. I have it working, but I am struggling to correctly link to a blog post in the search results. I can provide the results in simple text format. I followed this youtube tutorial . But how they built their project is a bit different to mine. The homepage of my blog already successfully links to specific blog posts, so I'm essentially trying to recreate elments of that in the search results page. I will paste my code below. The first and 2nd block quote are the 2 HTML pages, I use the same 'a href' in each one. But for some reason it won't work on my search results page, do I need to do something different to my def search_recipes(request): function in my views.py? search_recipes.html {% extends 'base.html' %} {% block content %} {% load static %} <center> {% if search %} <h1>You Searched For {{ search }}</h1> <br/> {% for recipe in recipes %} <a href="{% url 'post_detail' post.slug %}">{{ recipe }}</a> {% endfor %} {% else %} <h1>Hey! You Forgot to Search for a Recipe...</h1> {% endif %} </center> {% endblock %} Models.py from django.contrib.auth.models import User from … -
Django OnetoOne key insert on perform_update not working
in my models.py I've class Product(models.Model): code = models.CharField(primary_key=True, null=False) status = models.CharField(max_length=50, blank=True, null=True) class Price(models.Model): code = models.OneToOneField(Product, on_delete=models.CASCADE) price_tc = models.FloatField(blank=True, null=True) price_uc = models.FloatField(blank=True, null=True) price_bx = models.FloatField(blank=True, null=True) I want to insert the price after each insertion of product to ensure the one to one. So Implemented Django Perform Create in views.py class ProductView(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer ordering = ["code"] def perform_create(self, serializer): serializer.save() Price.objects.create(self.request.data["code"]) I get the error : Price.code must be a "Product" instance, so i swap to def perform_create(self, serializer): serializer.save() m = Product.objects.get(code=self.request.data["code"]) Price.objects.create(code=m) But still not working. -
I want to change the labels of the login form
I want to change the labels of the login form, but this does not happen. When running, these labels show their default state, "login" and "password". thanks for your guide from django import forms from django.contrib.auth.models import User from .models import Profile class LoginForm(forms.Form): username = forms.CharField(lable='نام کاربری') password = forms.CharField(widget=forms.PasswordInput, lable='پسورد') Custom change of labels -
Django template - for look iterate over variable
I am looking for a way to iterate over variable in django template. In template I do not know how to assign variable in for loop. In get_context_date of ListView i am assigning data of two files to two vars like: context[f"{t_name}_header"] = db_oper context[f"{t_name}_body"] = db_header Context is generated for two files which results with vars like: context["test1_header"] context["test1_body"] context["test2_header"] context["test2_body"]` test1 and test2 are names populated from model. I can access them with object_list in template. In template html file I would like to iterate over context like: {% for object in object_list %} {% for item in object.name|add:"_header" %} ...do stuff {% endfor %} {% for item in object.name|add:"_body" %} ...do stuff {% endfor %} {% endfor %}` In result in html template I got nothing. How to properly filter variable in for loop so it could go thru eq. test1_header ? -
user login problem after upgrading to Django 4.2 from Django 2.0
I upgraded my django project from 2.0 to 4.2 and now I am getting the following error on one page where I am using the login() function to log the user in. Error: The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. This was working without any problems in django 2.0 and I have been trying to find out the problem for hours but can't find anything related to it. I will attach the code below: def handle_no_permission(self): if self.request.user.is_authenticated and not self.test_func() and not self.is_source_email(): self.raise_exception = True if all(x in self.request.GET.keys() for x in ["token", "source"]): if self.is_source_email(): token_from_url = self.request.GET.get("token") deficiency_id = self.kwargs.get('deficiency_id') try: login_token = ProviderLoginToken.objects.get(key=token_from_url, deficiency_id=deficiency_id) if login_token.active: user = login_token.provider.user user.backend = "django.contrib.auth.backends.ModelBackend" print('BEFORE', self.request.user.is_authenticated) login(self.request, user, backend=user.backend) print('AFTER', self.request.user.is_authenticated) else: return render(self.request, "500_invalid_quick_amend_link.html") except ProviderLoginToken.DoesNotExist: return render(self.request, "500_invalid_quick_amend_link.html") return super().handle_no_permission() The user is able to still login because is_authenticated() returns False before and True after the login() function. -
Associating User with AWS Credentials in Django REST Framework | How to Store AWS Credentials per User in Django REST Framework
I'm building a Django API where users can input their AWS credentials, which are then verified and stored in the backend. I want to associate each set of credentials with the user who inputted them, and I want to use a unique UUID for each user. Here's my AWSCredentials model: from django.db import models from django.contrib.auth.models import User import uuid class AWSCredentials(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE) aws_access_key = models.CharField(max_length=200) aws_secret_key = models.CharField(max_length=200) aws_region = models.CharField(max_length=50) aws_bucket = models.CharField(max_length=200) def __str__(self): return str(self.id) And here's the view where I'm trying to save the credentials: class LoginVerification(APIView): @staticmethod def post(request): data = request.data aws_access_key = data.get('accessKey', '') aws_secret_key = data.get('secretKey', '') aws_region = data.get('region', '') aws_bucket = data.get('bucket', '') user = request.user aws_verification = verify_aws_credentials(aws_access_key, aws_secret_key, aws_region, aws_bucket) if aws_verification == 'Connected': aws_credentials = AWSCredentials( user=user, aws_access_key=aws_access_key, aws_secret_key=aws_secret_key, aws_region=aws_region, aws_bucket=aws_bucket ) aws_credentials.save() return Response({"verification": aws_verification}) However, when I try to save the credentials, I get this error: ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x000001009D0>": "AWSCredentials.user" must be a "User" instance. I understand this error is because request.user is an AnonymousUser, which happens when the user is not authenticated. But I'm not sure how to ensure the user … -
django python get only the first result from a queryset?
I am using signals to send an email to a respective user. I am getting more than one QuerySet from my query that is: orig_ordered_product = sender.objects.filter(id=instance.id) and as results (becouse a have two items in this case) is: <QuerySet [<OrderedProduct: Torta de Nozes>]> <QuerySet [<OrderedProduct: Café Expresso>]> Is there a way to get and do something else only with the first QuerySet as I only need the data from one of then? I tried to use .first() and .last() but it did not work. Thank you very much for any help os directions where to go from here! -
is there a way to order an Arabic text in reportlab python pdf generator
i'm creating an Arabic pdf using python report lab , the problem is the Arabic text is being displayed from the end to the beginning, it means that once the first line has finished its width it's appending the next line above it , note that every line is ordered correctly but the order of the lines as a group is reversed def arabic_text(doc, styles): arabic_text_style = get_arabic_text_style(styles) arabic_title_style = ParagraphStyle(name='Heading1',borderPadding=3,fontName="Arabic", alignment=2, fontSize=18, leading=16) storys = [] paragraphs = paragraph.objects.all() for para in paragraphs: title = Paragraph(get_display(arabic_reshaper.reshape(para.title)), arabic_title_style) text = Paragraph(get_display(arabic_reshaper.reshape(para.text)), arabic_text_style) paragraph_content = KeepTogether([title, Spacer(1, 30), text]) storys.append(paragraph_content) storys.append(Spacer(1, 60)) return storys -
Multible objects creation in Django Admin Panel
My desire is to create several objects in one django admin-panel creation window. Look: class ExampleModel(models.Model) field1 = models.CharField() field2 = models.CharField() field3 = models.CharField() date = models.DateField() In this case most important part is date, Often I create objects in admin-panel, where first 3 field are the same(at the moment of creation) and only date must be unique. So I wanna integrate some widget where I can choose all dates that i need, and by clicking submit button create number of objects. I found package named django-bulk-admin, which can solve my task. But it is not supported in Django 3. Also ChatGPT suggested me to create some actions in Admin class definition, but it is not works. I guess solution is redefine action of AdminForm of this model, but I don't know how? -
No Standard Found Matching That Query Django
I am working on a Django project, everything was working smoothly when I was on it but then when I opened the same project and running it in the server it throws errors of page note found yet its there in the code. Here is the code this is the urls.py page for my django app from django.urls import path from student import views from django.contrib.auth.views import LoginView app_name = 'student' urlpatterns = [ path('studentclick', views.studentclick_view), path('studentlogin', LoginView.as_view(template_name='student/studentlogin.html'),name='studentlogin'), path('studentsignup', views.student_signup_view,name='studentsignup'), path('student-dashboard', views.student_dashboard_view,name='student-dashboard'), path('student-exam', views.student_exam_view,name='student-exam'), path('take-exam/<int:pk>', views.take_exam_view,name='take-exam'), path('start-exam/<int:pk>', views.start_exam_view,name='start-exam'), path('calculate-marks', views.calculate_marks_view,name='calculate-marks'), path('view-result', views.view_result_view,name='view-result'), path('check-marks/<int:pk>', views.check_marks_view,name='check-marks'), path('student-marks', views.student_marks_view,name='student-marks'), path('standard-list', views.StandardListView.as_view(), name='standard-list'), #path('',views.StandardListView.as_view(),name='standard_list'), path('<slug:slug>', views.SubjectListView.as_view(), name='subject_list'), path('<str:standard>/<slug:slug>/', views.LessonListView.as_view(),name='lesson_list'), path('<str:standard>/<str:slug>/create/',views.LessonCreateView.as_view(), name='lesson_create'), path('<str:standard>/<str:subject>/<slug:slug>/', views.LessonDetailView.as_view(),name='lesson_detail'), path('<str:standard>/<str:subject>/<slug:slug>/update',views.LessonUpdateView.as_view(),name="lesson_update"), path('<str:standard>/<str:subject>/<slug:slug>/delete',views.LessonDeleteView.as_view(),name='lesson_delete'), path('student-notes',views.notes, name='student-notes'), path('delete_note/<int:pk>',views.delete_note,name='delete-notes'), path('notes_detail/<int:pk>',views.NotesDetailView.as_view(),name='notes-detail'), path('student-dictionary', views.dictionary, name='student-dictionary'), path('student-books',views.Books, name='student-books'), path('student-todos',views.todo, name='student-todos'), ] and this is my views.py file code def Books(request): if request.method == 'POST': form = Dashboardform(request.POST) text = request.POST['text'] url = "https://www.googleapis.com/books/v1/volumes?q="+text r = requests.get(url) answer = r.json() result_list = [] for i in range(10): result_dic ={ 'title': answer['items'][i]['volumeInfo']['title'], 'subtitle': answer['items'][i]['volumeInfo'].get('subtitle'), 'description': answer['items'][i]['volumeInfo'].get('description'), 'count': answer['items'][i]['volumeInfo'].get('pageCount'), 'categories': answer['items'][i]['volumeInfo'].get('catergories'), 'rating': answer['items'][i]['volumeInfo'].get('pageRating'), 'thumbnail': answer['items'][i]['volumeInfo'].get('imageLinks').get('thumbnail'), 'preview': answer['items'][i]['volumeInfo'].get('previewLink'), } result_list.append(result_dic) context = { 'form':form, 'results':result_list, } return render(request,'student/student_books.html',context) else: form = Dashboardform() context = {'form':form} return render(request,'student/student_books.html',context) def dictionary(request): if request.method == … -
How to get object from dropdown menu?
In my Django application I have these models: class BaseModel(ModelWithStamps): identifier = models.CharField(max_length=255) class Meta: abstract = True class Model(BaseModel): def __str__(self): name = self.name_type() return f'{name}: {self.identifier}' class Merch(Name): merch_id = models.CharField(blank=True, max_length=255, verbose_name="Merchant ID") class Term(Name): merch_fk = models.ForeignKey(Merc, on_delete=models.CASCADE, blank=True, null=True) And in the forms I have a Term dropdown. In the serializer in this part it giving me this error: Error: raise ValueError( ValueError: Cannot assign "'4545646'": "Term.merch_fk" must be a "Merch" instance. serializer.py # Update the model for (key, value) in field_value.items(): setattr(related, key, value) related.save() NOTE: if key == "merch_fk": split_line = value.split(':') value = Merch.objects.get(merch_id=split_line[1].strip()) It doesn't work because there can be multiple objects with the same merch_id How can I fix it? -
Django ORM query taking very long but Raw query runs as expected
I have a simple get query key = TenantKey.objects.get(pk=api_key) When I'm running a load test, for many requests the above query is taking multiple seconds (max 15s) which is very strange. So I ran a raw sql query equivalent to the above ORM like below with connection.cursor() as cursor: cursor.execute("SELECT app_tenantkey.key_id, app_tenantkey.name FROM app_tenantkey WHERE app_tenantkey.value=%s",[key]) row = cursor.fetchone() Surprisingly this query was way faster than the ORM which is what we were expecting as the table is very small and contains about 20 entries. I'm also attaching the max durations of both queries just FYI Raw Query ORM Query The ORM query is taking almost 100x when compared to time taken by the raw query in similar situation. I want to understand what's causing the ORM is taking so long while the raw is quick. -
How to add static files for a specific path in django
I am a noob when it comes to django or any backend related programs. i would like to add the same static files for a path which is not home in my django project. Here I am in my howe directory and there is no issues with loading static css and js file.home page but if i try to move to another pathother link static file are not loading. how can i load same static files but for different url other than the homepage I even added another folder named loading in my working dir but am still unsuccessful -
How to add a list of booleans per user to a django model?
In addition to the basic user model I have a second custom model in my django app. This model is called a challenge. I want this challenge object to contain a list of booleans for each user where I can store which users have completed this challenge. This list must be able to do the following things: Whenever a new user is added, each existing challenge object needs to get a new boolean which is set to false. Whenever a user is deleted the corresponding booleans in each challenge must be removed also. Whenever a user completes a challenge the list inside the challenge object must be updated. How do I do this? I think I need to use some sort of ForeignKey of ManyToOne relationship, but I really have no idea how to go about this. I added a ManyToMany field and gave it the paramter User, but that only gave me a list of all Users where I could’t remove any of the users. -
Admin page toggle button bug
Django admin page UI is like this when i added a custom user model. -
Django doesn't recognize my static folder
I just started my django project and i saw that i had to put my static folder in my project folder so i did, i think i did the necessary modifications to settings.py but when a ran my server, the css wasn't applying to my page, i looked at where my css file was looked for and it said "404 /store/static/css/carousel.css" ("store" is my app inside my project) while it should look for "myproject/static/css/carousel.css". So I moved my static folder inside my app folder ("store") at the location the server was looking for (store/static/css/carousel.css) but even if it is now looking at the right location it is still not working. settings.py BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = 'static/' STATICFILES_DIR = [os.path.join(BASE_DIR, '/static/')] html page referencing my css file {% extends 'store/base.html' %} {% load static %} {% block head %} <link href="{% static 'css/carousel.css' %}" rel="stylesheet" type="text/css"> {% endblock %} server response Not Found: /store/static/css/carousel.css [07/Aug/2023 10:00:27] "GET /store/static/css/carousel.css HTTP/1.1" 404 2378 i have these directories . ├── myproject │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py └── store ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── static │ … -
deployment diagram in insurance domain for python language
deployment diagram in insurance domain for python language Iam expecting a architecture diagram using django framework and SQL Server 2022 (Azure) and front end React JS unit tests and integration tests (PyTest) please help me to find out for full architecture diagram for tech stack in python language -
Celery beat with django
I have this code to run my django celery first here the settings.py file under app.app.settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'debug_toolbar', 'django_filters', 'django_extensions', 'corsheaders', 'rest_framework', 'auditlog', 'simple_history', 'drf_spectacular', 'django_celery_beat', 'logging', 'core', 'user', 'company', 'erp', 'treasury', ] CELERY_BROKER_URL = config('CELERY_BROKER_URL') CELERY_BROKER_BACKEND = "db+sqlite:///celery.sqlite" CELERY_CACHE_BACKEND = "db+sqlite:///celery.sqlite" CELERY_RESULT_BACKEND = "db+sqlite:///celery.sqlite" CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' now here the app.app.celery.py file import os from celery import Celery from celery.schedules import crontab os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") app = Celery("app") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() app.conf.beat_schedule = { 'generate_recurring_sale_documents_task': { 'task': 'erp.sale_document.tasks.generate_recurring_sale_documents_task', 'schedule': crontab(hour='11', minute='18'), 'args': ('celer_beat_security_key_to_access_to_tasks',) }, } and under app.erp.sale_document.tasks.py file I have this code import logging from celery import shared_task from .service import generate_recurring_sale_documents logger = logging.getLogger(__name__) @shared_task def generate_recurring_sale_documents_task(secret_key=None): # if secret_key != 'celer_beat_security_key_to_access_to_tasks': # logger.error("Unauthorized access attempt to generate_recurring_sale_documents_task") # return generate_recurring_sale_documents() I run my celery worker and celeyr beat like this python -m celery -A app.celery worker -l info -E --pool=gevent python -m celery -A app.celery beat -l debug here some logs for celery beat __ - ... __ - _ LocalTime -> 2023-08-07 11:22:08 Configuration -> . broker -> amqp://bimauser:**@localhost:5672// . loader -> celery.loaders.app.AppLoader . scheduler -> django_celery_beat.schedulers.DatabaseScheduler . …