Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Return many forms in one view - Django Project
I'm not advanced in Django yet, so please be understanding. I'm currently working on creating my portfolio app. The idea is to build something similar to https://track.toggl.com. I frequently use this tool, and I thought that replicating this project could be an interesting challenge and a valuable addition to my CV as a beginner programmer. In the Home View, I aim to return a couple of forms: One blank form for creating a new Time Entry record in the project. Multiple forms pre-filled with data from the database. In the template of the Home View, I intend to display a list of all pre-filled forms to the user. This way, users can edit the data according to their preferences without the need for separate views/templates for editing. Now, my question is as follows: is the solution I've prepared suitable? Of course the most important is logic behind create_forms_for_user_data method, and is it properly used in get method. views.py class HomeView(view): template_name = 'pages/home.html' def get(self, request, *args, **kwargs): """ Should return : - User's all time entries - A form to create a new time entry - A list of forms to edit time entries """ user_data = self.get_user_data() blank_form … -
Django-cors-headers not working with Django and Vue
When I try to access my Django rest framework from the frontend I get this error and the data is not passed along Access to fetch at 'http://localhost:8000/api/students' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I tried using django-cors-headers and every setting for it that I could find online; absolutely nothing worked. Here are the settings from my settings.py file (currently commented out) ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'students' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'project.middleware.CustomCorsMiddleware', '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', ] # clickjacking not compatible with corsheaders? CORS_ORIGIN_ALLOW_ALL = True # CORS_ALLOW_CREDENTIALS = True # CORS_ORIGIN_WHITELIST = [ # "http://localhost:8000", # "http://127.0.0.1:8000", # "http://localhost:5173", # "http://127.0.0.1:5173", # ] # CORS_ALLOW_HEADERS = ['*'] # # CSRF_TRUSTED_ORIGINS = [ # "http://localhost:8000", # "http://127.0.0.1:8000", # "http://localhost:5173", # "http://127.0.0.1:5173", # ] I also tried using custom middleware that I found here on stack overflow. class CustomCorsMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, … -
I'm a beginner in django and I'm trying to create a django project "portfolio" and I'm getting this error can someone help me
i have already done these steps python -m venv ./venv .\venv\Scripts\activate pip install django django-admin startproject portfolio and when i did python manage.py startapp portfolio it shows this error (venv) PS C:\Users\Dell\OneDrive\Desktop\portfolio> python manage.py startapp portfolio C:\Users\Dell\AppData\Local\Programs\Python\Python311\python.exe: can't open file 'C:\\Users\\Dell\\OneDrive\\Desktop\\portfolio\\manage.py': [Errno 2] No such file or directory -
Handling JSON user input in a Django Form
This is a part of a school assigment where we have to use a JSON field in a model for our simple Django project. In this "book club" website, the user must have the ability to new submit books to the server. I would like the user input to not require knowing JSON syntax. The model for the book is as follows: class Book(models.Model): #book information name = models.CharField(default='title', max_length=100) #Name of the book authors = models.JSONField() #Author of the book year_published = models.IntegerField() #Year the book was published in date_added = models.DateTimeField(auto_now=True) #Date added (automatic) date_modified = models.DateTimeField(auto_now_add=True) #Date modified (automatic) def __str__(self): #Return the full title of the book with its author and publish year. fullname = f"{self.authors}.{self.name};({self.year_published})" return fullname I'm concerned about the 'authors' field in this case. Now the form into which the user would submit new books: class AddBook(forms.ModelForm): class Meta: model = Book fields = "__all__" And the view for add book functionality: def addbook(request): if request.method != 'POST': #no data submitted form = AddBook() else: form = AddBook(data=request.POST) print(form.errors) if form.is_valid(): form.save(commit=True) return redirect('cbc:books') context = {'form': form} return render(request, 'cbc/addbook.html', context) Now, this all works, but since the "authors" field in in … -
ValueError at watch
This code gave me this error. what's the problem? Field 'id' expected a number but got 'Watchlist object (1)'. thanks for any idea:) @login_required(login_url="login") def watchlist(request, username): products = get_object_or_404(Watchlist, pk=username) return render(request, 'auctions/watchlist.html', {'products': products}) @login_required(login_url="login") def add(request, productid): item = get_object_or_404(List, pk=productid) #user = get_object_or_404(Watchlist, user) user_Watchlist, __ = Watchlist.objects.get_or_create(user=request.user) user_Watchlist.watchitem.add(item) return redirect('watchlist', Watchlist.user) urls.py: path("watchlist/<str:username>/", views.watchlist, name="watchlist"), path("add/<int:productid>/", views.add, name="add"), -
Why are there problems with the django application (database, styles) when running on nginx?
I am practicing running django from luck on the nginx server, I wrote all the necessary configurations to run the application in which the production and developer versions are located and faced the problem that in the developer version everything works fine for me and in the production version the styles on the entire project are not loaded for me ( I have seen many similar questions, but I have everything written down as in the answers to them), and also my Postgres database does not work on production and gives me an error that it does not exist I provide code fragments settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') docker-compose.yml: version: '3.8' services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:15 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=hello_django - POSTGRES_PASSWORD=hello_django - POSTGRES_DB=hello_django_dev volumes: postgres_data: Dockerfile: # pull official base image FROM python:3.11.4-slim-buster # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install system dependencies RUN apt-get update && apt-get install -y netcat # install dependencies RUN pip install … -
Django models - Set an Foreign key attribute from a Many to Many in an antribute on the same level
AttributeError: type object 'type' has no attribute 'subtipos' I know that isnt working cause the object attribute isnt declared before assigning the attribute subtipo. I would like to know how to get a single subtipo to the Asset class selecting from the subtipos of the AssetType class. class SubAssetType(models.Model): name = models.CharField(max_length=50) slug = models.SlugField() descripcion = models.TextField(null=True, blank=True) class AssetType(models.Model): name = models.CharField(max_length=50) slug = models.SlugField() descripcion = models.TextField(null=True, blank=True) subtipos = models.ManyToManyField(SubAssetType, blank=True) class Asset(models.Model): # Atributos nominales name = models.CharField(max_length=50) slug = models.SlugField() descripcion = models.TextField(null=True, blank=True) # Atributos de valor type = models.ForeignKey(AssetType, on_delete=models.CASCADE) subtipo = models.ForeignKey(type.subtipos, on_delete=models.CASCADE) -
django view not passing context dict to html template
Trying to pass a dict which has various fields from a main table with additional data from the media table. The context is not getting to the html page, cant see why, any help would be appreciated. I have a very similar view using POST request which works without issue. Both test prints in the view return the correct values so must be an issue with the way the context is being passed to the html template. views.py def listing(request, listing_id): if listing_id: print(f"listing id: {listing_id}") results = ListingDetail.objects.filter(listing_id=listing_id).prefetch_related('media_set').all() print(results) return render(request, 'members/listing_detail.html', {'listing': results}) else: return render(request, 'general/search.html', {'listing': 'no data'}) html <div class="card"> listing_id = {{ listing.listing_id }} <div class="card-header"> <div id="carousel_main" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> {% for media_item in listing.media_set.all %} <div class="carousel-item {% if forloop.counter == 1 %}active{% endif %}"> <img src="{{ media_item.media_url }}" class="d-block" alt="" width="100%"> </div> {% endfor %} </div> urls.py urlpatterns = [ path('listing/<int:listing_id>', views.listing, name='listing'), ] -
Nextjs not sending csrf token to my django server
My code is working on localhost and I can see csrf by console log but when deploy on my server https I don't see csrf token and it's null I don't know why I am struggling to solve this problems from past few days and still now don't have any solution. I am not understanding why it's not working on production when deploy on my server but same code working on localhost. here is my react code for axois post const handleClickComment = (main_comment_id)=>{ const csrfToken = cookies.get("csrftoken") axios.post(url,comment_data,{ withCredentials:true, headers: { 'X-CSRFToken': csrfToken, // Adding the CSRF token to the request headers }, my django settings.py AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by email 'allauth.account.auth_backends.AuthenticationBackend', ] CORS_ALLOWED_ORIGINS = [ "http://*", "https://*", "http://localhost:3000", "https://localhost:3000", "http://127.0.0.1:3000", "https://127.0.0.1:3000", ] CORS_ORIGIN_WHITELIST = [ 'http://*', "https://*", "http://localhost:3000", "https://localhost:3000", "http://127.0.0.1:3000", "https://127.0.0.1:3000", ] CSRF_TRUSTED_ORIGINS = [ 'http://*', "https://*", "http://localhost:3000", "https://localhost:3000", "http://127.0.0.1:3000", "https://127.0.0.1:3000", ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = default_headers + ( 'xsrfheadername', 'xsrfcookiename', 'content-type', 'x-csrftoken', ) CSRF_COOKIE_SAMESITE = 'Strict' SESSION_COOKIE_SAMESITE = 'Strict' CSRF_COOKIE_HTTPONLY = False # False since we will grab it via universal-cookies SESSION_COOKIE_HTTPONLY … -
How to query (request) Yahoo Finance API in Django + Python for stock quotes?
What is other alternative to IEX Cloud for free stock quotes?! Shall i use yahoo_fin or yfinance?! I just want free stock quotes for a simple Stock Market API (beginner level). How do i write a query using yahoo_fin or yfinance?! Here is how i´m using IEX Cloud... from django.shortcuts import render, redirect from .models import Stock from .forms import StockForm from django.contrib import messages def home(request): import requests import json if request.method == 'POST': ticker = request.POST['ticker'] api_request = requests.get("https://cloud.iexapis.com/stable/stock/" + ticker + "/quote?token=<your_token>") try: api = json.loads(api_request.content) except Exception as e: api = "Error..." return render(request, 'home.html', {'api': api}) else: return render(request, 'home.html', {'ticker': "Enter a Ticker Symbol Above or Stock Quote..."}) -
Preventing sending some trace logs to Azure with Open-telemetry
I'm sending logs to Azure AppInsights by using Open-telemetry. The library keeps sending trace data constantly not only when the log occurs as shown in the picture. Is there an any way to close this or prevent it to write on trace table? -
weaspyrint does not render uploaded image from database
So here is my html code for the pdf <div class="cont"> <img class="logo1" src="{% static 'upload/' %}{{ wmsu_logo.img_name }}" /> <div> <p>Republic of the Philippines</p> <p>Western Mindanao State University</p> <p>{{ syllabus.college }}</p> <p class="title">DEPARTMENT OF {{ syllabus.department }}</p> </div> <img class="logo2" src="{% static 'upload/' %}{{ course_logo.img_name }}" /> <img class="logo3" src="{% static 'upload/' %}{{ iso_logo.img_name }}" /> </div> and this is the view where it processes things. def pdf(request, id): # ---------- SYLLABUS ---------- syllabus = get_object_or_404(Syllabus, user_id=request.user, id=id) # ---------- SYLLABUS TEMPLATE ---------- syllabus_template = get_object_or_404(Syllabus_Template, user_id=request.user, id=syllabus.syllabus_template_id.id) wmsu_logo = Logo.objects.get(syllabus_template_id=syllabus_template, name='wmsu_logo') course_logo = Logo.objects.get(syllabus_template_id=syllabus_template, name='course_logo') iso_logo = Logo.objects.get(syllabus_template_id=syllabus_template, name='iso_logo') total_term_percentage = midterm.term_percentage + finalterm.term_percentage template = loader.get_template('PDF_template/template.html') # Load HTML template html_string = template.render({ 'wmsu_logo': wmsu_logo, 'course_logo': course_logo, 'iso_logo': iso_logo, }) # Render the template # Generate the PDF using WeasyPrint pdf = HTML(string=html_string, base_url=request.build_absolute_uri()).write_pdf() # Create an HttpResponse with the PDF content response = HttpResponse(pdf, content_type='application/pdf') # Display in the browser response['Content-Disposition'] = 'inline; filename=Syllabus' + str(datetime.datetime.now()) + '.pdf' return response I need the uploaded image in the pdf conversion in weasyprint. I already deployed this in pythonanywhere. When I use the local file the image renders but when I deploy it, it does not render the … -
ProgrammingError: relation does not exist. Django postgresql
What's up some guys! I am trying to fetch data from my postgresql database, but it does not seem to find it. Basically I'm getting "ProgrammingError: relation does not exist" but I will let the errors and code speak for itself, so let's cut to the chase immediately (sorry in advance for a long post, I didn't want to leave any information out). This is the error I'm getting: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\filip\Desktop\WebNutrition\backend\NutriCalc\tests.py", line 13, in test_fetch_nutrition_values print(result) File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 374, in __repr__ data = list(self[: REPR_OUTPUT_SIZE + 1]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 398, in __iter__ self._fetch_all() File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 1881, in _fetch_all self._result_cache = list(self._iterable_class(self)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 208, in __iter__ for row in compiler.results_iter( ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\compiler.py", line 1513, in results_iter results = self.execute_sql( ^^^^^^^^^^^^^^^^^ File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\compiler.py", line 1562, in execute_sql cursor.execute(sql, params) File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 84, in _execute with self.db.wrap_database_errors: File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … -
Start gunicorn wiht django and show No module named 'fastapi'
During handling of the above exception, another exception occurred: Nov 28 03:51:54 PM Nov 28 03:51:54 PM Traceback (most recent call last): Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner Nov 28 03:51:54 PM response = get_response(request) Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/sentry_sdk/integrations/django/middleware.py", line 175, in call Nov 28 03:51:54 PM return f(*args, **kwargs) Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/htmlmin/middleware.py", line 21, in call Nov 28 03:51:54 PM response = self.get_response(request) Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/django/core/handlers/exception.py", line 49, in inner Nov 28 03:51:54 PM response = response_for_exception(request, exc) Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception Nov 28 03:51:54 PM response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/django/core/handlers/exception.py", line 152, in handle_uncaught_exception Nov 28 03:51:54 PM callback = resolver.resolve_error_handler(500) Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/django/urls/resolvers.py", line 615, in resolve_error_handler Nov 28 03:51:54 PM callback = getattr(self.urlconf_module, 'handler%s' % view_type, None) Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/django/utils/functional.py", line 48, in get Nov 28 03:51:54 PM res = instance.dict[self.name] = self.func(instance) Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/django/urls/resolvers.py", line 595, in urlconf_module Nov 28 03:51:54 PM return import_module(self.urlconf_name) Nov 28 03:51:54 PM File "/usr/local/lib/python3.10/importlib/init.py", line 126, in import_module Nov 28 03:51:54 PM return _bootstrap._gcd_import(name[level:], package, … -
Wait until subtask is ready (celery + unittest)
I have a task which called by parent task. @shared_task def task1(): if condition: task2.apply_async() @shared_task def task2(): pass I want to test all flow starting by calling task1 with unittest: class NewTestCase(TestCase): def test_tasks(self): celery_task = task1.apply() celery_task.get() self.assertEqual(celery_task.state, "SUCCESS") But in that case subtask task2 goes into my local celery worker and executes there. Is there any way to execute all task in test enviroment and wait until subtask is ready? P.S. CELERY_ALWAYS_EAGER=True isn't a solution. -
Django and two telegram bots
I want to make 2 telegram bots with a common admin panel in Django. The question is how best to implement this. The first bot will be for sellers, let's call it “seller bot”. The second one will be for "buyer bot" buyers. I already have sketches for the first bot, a model in Django telegram_bot. There should also be a chat so that you can communicate from the first to the second bot. How can I best create a database to store users from two bots? make one table and separate the data there by chat_id? Then how can I determine which bot I am a member of? I was thinking of creating two separate applications telegram_bot_seller and telegram_bot_buyer. Please tell me which approach would be better. I've never worked with two bolts at the same time .. Each bot will have its own separate functions. But some, such as the technical support chat, are common (just don’t interfere with each other) -
Post request do Django app deployed with Gunicorn and Nginx retuns 405 code
I am sorry that my question is not quite suitable for Stack overflow community, but I am desperate to find the solution to my issue and hope that somebody will be able to please help me. My Django application is deployed on AWS. EC2 UBUNTU. I used Nginx and Gunicorn. Socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target Service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/home-admin ExecStart=/home/ubuntu/home-admin/.venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ home_admin.wsgi:application [Install] WantedBy=multi-user.target Nginx server conf: server { listen 80; server_name XX.170.235.232; location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_pass http://unix:/run/gunicorn.sock; } } This configuration serves Get requests perfectly, but when I send POST request I receive 405 code. Besides, I see that on some stage the url is augmented by unnesessary domain. This is response error: POST http://127.0.0.1:5500/XX.170.235.232/ 405 (Method Not Allowed). -
Using Django Allauth without allauth urls?
I want to use django allauth package without its built in urlpatterns. Main reason for that is that I want to have the ulrs in different language. Also I dont want to have the allauth url available even if there is no redirectons to those pages in my site. Main reason I started to use allauth was the social login but I noticed that the regural account logic was nice and fast to implement. Is it neccesary to include allauth url to project if you want to use only the views and forms functionality? Or is there a better way to do it? I have made custom views and forms all of the views and forms that I use but they all inherit allauth views and forms. I have also custom ulrs to all those views. Example of my custom view: class LogInView(AllAuthLoginView): template_name = 'accounts/log_in.html' form_class = SignInForm I have tested that it works well when allaut urls are included. But if exlude allauth url I get this error when loading login page: Reverse for 'account_signup' not found. 'account_signup' is not a valid view function or pattern name. I noticed that it comes from this function in allauth LoginView … -
allauth providers not present in user details
I am trying to setup SSO in my django project using Allauth which I have previously done, but for some reason my defined provider is not present in the user section to link the user to an external provider. This is the config: ACCOUNT_ADAPTER = "myproject.users.adapters.AccountAdapter" ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True) ACCOUNT_AUTHENTICATION_METHOD = "username_email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGOUT_ON_GET = True ACCOUNT_USERNAME_REQUIRED = False # Username is not required ACCOUNT_UNIQUE_EMAIL = True SOCIALACCOUNT_AUTO_SIGNUP = True SOCIALACCOUNT_EMAIL_AUTHENTICATION = True SOCIALACCOUNT_EMAIL_AUTHENTICATION_AUTO_CONNECT = True SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' # None because we trust azure SOCIALACCOUNT_LOGIN_ON_GET = True SOCIALACCOUNT_ADAPTER = "myproject.users.adapters.SocialAccountAdapter" OIDC_CLIENT_ID = env("DJANGO_SOCIALACCOUNT_OIDC_CLIENT_ID", default="") OIDC_CLIENT_SECRET = env("DJANGO_SOCIALACCOUNT_OIDC_CLIENT_SECRET", default="") OIDC_CLIENT_URL = env("DJANGO_SOCIALACCOUNT_OIDC_CLIENT_URL", default="") SOCIALACCOUNT_PROVIDERS = { "openid_connect": { "APPS": [ { "provider_id": "keycloak", "name": "Keycloak SSO", "client_id": OIDC_CLIENT_ID, "secret": OIDC_CLIENT_SECRET, "settings": { "server_url": OIDC_CLIENT_URL, }, } ] } } MIDDLEWARE += ["allauth.account.middleware.AccountMiddleware"] And the errorlog -
Design Strategies for Integrating Enroll Plan-Specific Features in a Django Project
I am working on a Django project that comprises three main components: nkb_assessment_backend: Handles assessments and exams, featuring apps like nkb_exam and nkb_exam_extensions. nkb_learning_backend: Manages learning-related functionalities including user enroll plans, with apps such as nkb_auth_v2. nkb_backend: Serves as an overarching layer that possibly integrates or orchestrates functionalities of the above two components. Requirement: We need to introduce functionality for enroll plan-specific exam slots in the nkb_assessment_backend, where these slots are dependent on user enroll plans managed in the nkb_learning_backend. The challenge is to implement this feature without creating direct dependencies or coupling between the two backend components. Constraints: Avoid modifications to the nkb_assessment_backend, particularly its database schema or existing models. Maintain a loosely coupled architecture. Ensure the solution is scalable and maintainable. Question: What are the best practices or strategies to implement this feature within the given constraints and architecture? I am looking for insights or alternative approaches that could efficiently integrate this functionality while maintaining the structural integrity of our Django project. -
Bad format after converting a JSONField to a TextField
I encountered an issue with a Django project where a JSONField was initially used to store data. To maintain the order of the data as it was saved, I implemented a sorting functionality. However, I found that this sorting operation, although necessary for display, seemed inefficient when the data was accessed. To address this, I decided to convert the JSONField to a TextField and use json.dump to ensure the order is preserved without the need for sorting each time the data is accessed. Unfortunately, the conversion process didn't work as expected. Django successfully converted some fields to the correct JSON string format, but others were not handled correctly. An example of the incorrect format is as follows: '{'is_valid': True, 'name': 'John Doe'}' As seen above, Django converted the data to a string, but boolean values, such as True, were not handled correctly. I am seeking suggestions on how to address this issue. Currently, I am considering replacing the single quotes with double quotes and converting boolean values like this: data = '{'is_valid': True, 'name': 'John Doe'}' formatted_data = data.replace("'", '"').replace('True', '"true"') However, I believe there might be a more elegant or efficient solution. I would appreciate any insights or recommendations. … -
Django SMTPServerDisconnected: Connection unexpectedly closed
I have everything set up, gmail using app password EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'emailtam1231@gmail.com' EMAIL_HOST_PASSWORD = "appp pass word some" EMAIL_USE_SSL = False EMAIL_DEBUG = True Here is my send email func: def send_price_drop_notification(product, latest_item): favorite_users = Favourite.objects.filter(product=product) if favorite_users: subject = f'Price Drop Alert for {product.name}' message = f'The price for {product.name} has dropped to {latest_item.current_price}.\nCheck it out now!' from_email = 'emailtam1231@gmail.com' recipient_list = [favorite.user.email for favorite in favorite_users] print(f"Subject: {subject}") print(f"Message: {message}") print(f"From: {from_email}") print(f"To: {recipient_list}") try: send_mail(subject, message, from_email, recipient_list, fail_silently=False,) except smtplib.SMTPServerDisconnected as e: print(f"SMTPServerDisconnected: {e}") # Handle this specific exception (e.g., reconnect to the SMTP server, or log the issue) except smtplib.SMTPException as e: print(f"SMTPException: {e}") # Handle SMTP exceptions in a specific way except BadHeaderError as e: print(f"BadHeaderError: {e}") # Handle BadHeaderError or other exceptions except Exception as e: print(f"Exception occurred while sending email: {e}") The output i getting: Subject: Price Drop Alert for Fake Product Message: The price for Fake Product has dropped to 120.53. Check it out now! From: emailtam1231@gmail.com To: ['ntd8466@gmail.com'] And when i check, the app password was never been use. -
Redshift serverless - Django connection active all the time
I have Django application running which connects to postgres for basic django functionality/setup. But this application also connects to Redshift serverless using psycopg2 library. The problem is that the RS serverless is always up and running which is costing a lot. Digging into the issue, I found that psycopg2 is executing below query every 5-6 seconds: "SET datestyle TO 'ISO'" Looking at the psycopg library file, every time the connection is setup, a function is called conn_is_datestyle_ok. For reference: https://github.com/psycopg/psycopg2/blob/5fb59cd6eebd96e2c8a69a3a9d606534eb95abf0/psycopg/connection_int.c#L678 Is there a way we can set the parameter or any option for library not to execute this query? -
Unable to update the data in python
I'm unable to update the organisation details in the singleuser file a python project using the framework django. the value is not updating in the database. enter code here {% extends "caas_apps/layouts/base.html" %} {% load static %} {% block content %} {% include 'caas_apps/layouts/sidebar.html' %} {% include 'caas_apps/layouts/header.html' %} Organization Details {% csrf_token %} {{ org_form.as_p }} {{ formset.management_form }} {% for form in formset.forms %} {{ form.as_table }} {% endfor %} Organization Name: {{ organization.orgname }} License Type: {{ organization.license }} Certification Settings: {{ organization.certification }} Security Framework: {{ organization.framework }} Contact Person Name: {{ organization.cpname }} Email: {{ organization.orgemail }} Phone: {{ organization.phone }} Address: {{ organization.address }} Third Party Contact Details: {% for contact in third_party_contacts %} Name: {{ contact.thirdpartyname }} Email: {{ contact.thirdpartyemail }} Phone: {{ contact.thirdpartyphone }} {% endfor %} Submit Reset {% endblock content %} {% block scripts %} $(document).on("click", "label.orgdetails", function () { var $label = $(this); var txt = $label.text(); var fieldName = $label.attr('id'); $label.replaceWith(<input class='orgdetails' type='text' name="${fieldName}" value='${txt}'>); $(input[name="${fieldName}"]).focus(); }); $(document).on("blur", "input.orgdetails", function () { var $input = $(this); var txt = $input.val(); var fieldName = $input.attr('name'); $input.replaceWith(<label class='orgdetails' id="${fieldName}">${txt}</label>); $(input[name="${fieldName}"]).val(txt); }); $("#reset-btn").on("click", function () { $("#org-details-form")[0].reset(); $("label.orgdetails").each(function () { var … -
What difference between AdminSiteOTPRequired and OTPAdminSite?
What difference between AdminSiteOTPRequired and OTPAdminSite? couldn't understand at first glance almost identical I use authorization by email, I changed the class in the code to another one, but I didn’t see the difference in the documentation. The only thing I deducted was that one class is specifically for administering admin users, but the second one too? from two_factor.urls import urlpatterns as tf_urls from two_factor.admin import AdminSiteOTPRequired from django_otp.admin import OTPAdminSite admin.site.__class__ = AdminSiteOTPRequired urlpatterns = [ path('', include(tf_urls)), ]