Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save number of total search query count on models in Django
Below is my Django code to save user searches on database. How can I implement a function that when a same user searches same keywords for multiple time I need to record count of that keywords on database if its logged in user or session user def get_queryset(self): query = self.request.GET.get('q') if query: if self.request.user.is_authenticated: if not search_keywords.objects.filter(user=self.request.user, search_word=query).exists(): search_keywords.objects.create( user = self.request.user, search_word = query, session_id = session_id ) else: if not search_keywords.objects.filter(session_id=session_id, search_word=query).exists(): search_keywords.objects.get_or_create( session_id=session_id, search_word = query, ) search_vector = ( SearchVector('title', weight='A') + SearchVector('description', weight='B') + ) search_query = SearchQuery(query) return items.objects.annotate( rank=SearchRank(search_vector, search_query) ).filter(rank__gt=0.1).order_by('-rank') return items.objects.none() -
Token authentication not working in Django Rest Framework after passing the token
Session authentication is working correctly as I am getting "You are authenticated!" if I login from the Django admin, but token authentication isn't functioning and I am getting error "Authentication credentials were not provided." pip freeze Django==5.1.2 django-filter==24.3 djangorestframework==3.15.2 djangorestframework-simplejwt==5.3.1 Following are the project files views.py from django.shortcuts import render from rest_framework import generics, permissions from .models import Artist from .serializers import ArtistSerializer from rest_framework.authentication import TokenAuthentication class ArtistListCreateView(generics.ListCreateAPIView): queryset = Artist.objects.all() serializer_class = ArtistSerializer permission_classes = [permissions.IsAuthenticated] authentication_classes = [TokenAuthentication] def perform_create(self, serializer): serializer.save(user=self.request.user) class ArtistDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Artist.objects.all() serializer_class = ArtistSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): print("Authenticated user:", self.request.user) return Artist.objects.filter(user=self.request.user) serializers.py from rest_framework import serializers from .models import Artist class ArtistSerializer(serializers.ModelSerializer): class Meta: model = Artist fields = ['id', 'user', 'phone_country_code', 'phone', 'location', 'created_at', 'updated_at'] read_only_fields = ['id', 'user','created_at', 'updated_at'] models.py from django.contrib.auth import get_user_model from django.db import models User = get_user_model() class Artist(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='artist_profile') phone_country_code = models.CharField(max_length=10) phone = models.CharField(max_length=15) location = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username urls.py from django.urls import path from .views import ArtistListCreateView, ArtistDetailView urlpatterns = [ path('artists/', ArtistListCreateView.as_view(), name='artist-list-create'), path('artists/<int:pk>/', ArtistDetailView.as_view(), name='artist-detail'), ] I have tried updating the settings.py with following details … -
SSL is required, but the server does not support it (Django)
I was working on a test project as a practice and when I tried migrating it to the database (MariaDB PhpMyAdmin), I get this error "django.db.utils.OperationalError: (2026, 'TLS/SSL error: SSL is required, but the server does not support it')" This is how I wrote it in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'schooldb', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3307', # 'OPTIONS': {'init_command': "SET SQL_MODE='STRICT_TRANS_TABLES'"}, } } I already have mysqlclient installed. -
Python requests Session not passing cookies?
I have followed the documentation as far as I can tell, but it seems that the requests library Session object is not retaining cookies. Here is my simple code: with requests.Session() as s: url = '%s://'%http+serverStr+'/login/' s.get(url) payload = {'username': 'sfprod', 'password': <password>, 'csrfmiddlewaretoken': s.cookies['csrftoken'], 'next': '/'} login_resp = s.post(url, data=payload, headers=(dict(Referer=url))) This is connecting to a Django server. When I run the first s.get() call I see these cookies returned: <RequestsCookieJar[Cookie(version=0, name='csrftoken', value='Iw2k4RF5QIy6oNOA71681oq4kGVBxjzTmQCULicbWdr5ZfH1Kunrn30DNupQtFhF', port=None, port_specified=False, domain='gancho.local', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=True, expires=1761043315, discard=False, comment=None, comment_url=None, rest={'SameSite': 'Lax'}, rfc2109=False)]> However when the second call happens, no cookies are passed to the server. The COOKIES member of the request object received is empty and the server returns 403 Forbidden. I stepped through the csrftoken code in the debugger and it is rejecting the request because the cookie is not present (to be precise, because there is no CSRF_COOKIE value in the META member of the request, but I assume this is because the cookie is not present). I can log in with a browser, and in this case I see the cookie in the request, so I think it is not a setup problem with the server. Is there something I … -
Is it safe and ok to divide mp3 file like that?
I have an mp3 file and want to divide it into several files ("chunks"). I came up with this code (I stole the idea from django): from pathlib import Path class FileWrapper: def __init__(self, file) -> None: self.file = file def chunks(self, chunk_size): chunk_size = chunk_size try: self.file.seek(0) except (AttributeError, Exception): pass while True: data = self.file.read(chunk_size) if not data: break yield data with open("./test2.mp3", "rb+") as src: wrapper_file = FileWrapper(src) for chunk_ind, chunk in enumerate(wrapper_file.chunks(chunk_size=100 * 1024)): out_file_path = Path("./", f"test2_{chunk_ind}.mp3") with open(out_file_path, "wb+") as destination: destination.write(chunk) And, you know, it's working okay, but I'm scary and in doubt, that this approach can sometimes work, but sometimes it maybe can "brake" resulted "chunks". So, is this way - okay? Or I need to dive deeper into how mp3 files made? -
"GET /static/assets/css/plugins/something.css.map HTTP/1.1" 404
I am getting this error every time I reload my website. And for this error it's taking so much time to reload the website. but my stylings from .css and .js are working. I am getting this errors in my terminal - [22/Oct/2024 03:51:18] "GET /static/assets/css/demos/demo-6.css HTTP/1.1" 304 0 [22/Oct/2024 03:51:18] "GET /static/assets/css/custom-old.css HTTP/1.1" 304 0 **[22/Oct/2024 03:51:20] "GET /static/assets/css/plugins/jquery.countdown.css.map HTTP/1.1" 404 1989 [22/Oct/2024 03:51:20] "GET /static/assets/css/plugins/magnific-popup/magnific-popup.css.map HTTP/1.1" 404 2028 [22/Oct/2024 03:51:20] "GET /static/assets/css/style.css.map HTTP/1.1" 404 1932 [22/Oct/2024 03:51:20] "GET /static/assets/css/plugins/owl-carousel/owl.carousel.css.map HTTP/1.1" 404 2016 [22/Oct/2024 03:51:20] "GET /static/assets/css/demos/demo-6.css.map HTTP/1.1" 404 1953 [22/Oct/2024 03:51:20] "GET /static/assets/css/skins/skin-demo-6.css.map HTTP/1.1" 404 1968 [22/Oct/2024 03:51:20] "GET /static/assets/css/bootstrap.min.css.map HTTP/1.1" 404 1956 [22/Oct/2024 03:51:20] "GET /static/assets/js/bootstrap.bundle.min.js.map HTTP/1.1" 404 1971 [22/Oct/2024 03:51:20] "GET /static/assets/js/jquery.plugin.min.map HTTP/1.1" 404 1953 [22/Oct/2024 03:51:20] "GET /static/assets/js/jquery.countdown.min.map HTTP/1.1" 404 1962** I am using soome jquery plugins. Here's i am linking the files in my base.html CSS - <link rel="stylesheet" href="{% static 'assets/css/style.css'%}"> <link rel="stylesheet" href="{% static 'assets/css/skins/skin-demo-6.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/demos/demo-6.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css"> <link rel="stylesheet" href="http://dodsoftware.com/sotests/fancy/jquery.fancybox-1.3.4.css" type="text/css" media="screen" /> <link rel="stylesheet" href="{% static 'assets/css/custom-old.css'%}"> <link rel="stylesheet" href="{% static 'assets/css/custom.css'%}"> JAVASCRIPTS - <script src="{% static 'assets/js/jquery.elevateZoom.min.js' %}"></script> <script src="{% static 'assets/js/jquery.magnific-popup.min.js' %}"></script> <script src="{% static 'assets/js/jquery.plugin.min.js' %}"></script> <script src="{% static 'assets/js/jquery.countdown.min.js' … -
mysqlclient not found even after installed in Django on MacOS
I use pyenv to create a virtual-env, and install mysqlclient in it successfully. But when I python manage.py runserver, it shows 'Did you install mysqlclient?'. How to resoleve it? I try it both in terminal and PyCharm, all did not work. I also looked up a lot of technical forums and basically said that the virtual environment mismatch is the reason, and no one is in the same situation as me. -
How do I avoid a SuspiciousFileOperation when uploading a Django photo?
from django_resized import ResizedImageField class UserProfilePhoto(Model): photo = ResizedImageField(size=[128, 128], upload_to=MEDIA_ROOT) photo_hash = BigIntegerField( blank=True, null=True, help_text=_("an integer representation of the hexdigest hash of the photo"), ) def __str__(self): return f"{self.photo.name} ({self.photo_hash})" I used to have a save() operation in the model, which would do the resizing but now I'm using Django-resized because after all that figuring out how to resize the photo and generate a hash value it turns out there is a module to do it already. I'm adding a picture to the userprofilephoto in the admin. SuspiciousFileOperation at /admin/userprofile/userprofilephoto/add/ Detected path traversal attempt in '/app/mine/media/mendlebrot-lawn.jpeg' How do you turn off the error or the validation? To answer some questions in advance: No. I'm not going to go back to ImageField() It gave me the same problem with lots more code. -
how to fix my register view that generates a token and assigns it to a cookie? django error
Hello I am having trouble building a register view for my django homework assignment. I'm a beginner and trying to work on my register functionality and the views file is where I am having trouble. It's supposed to add a new user to user table in the database, and create a session key string and assign it to the cookie so the user can stay signed in. Whenever I submit a new user it redirects and gives me this error ValueError: Field 'id' expected a number but got 'pjtjtksydunpdysgxcxtmpazfyawvqzg' (my generated string) Here's my register view def register(request: HttpRequest): if request.method == 'POST': params = request.POST user = User( name = params.get("name"), email = params.get("email"), password_hash = params.get("password") ) hasher = hashlib.sha256() hasher.update(bytes(user.password_hash, "UTF-8")) user.password_hash = hasher.hexdigest() user.save() token = "" letters = string.ascii_lowercase for _ in range(32): token = "".join(random.choice(letters) for _ in range(32)) session_token = Session.objects.create(user=user, token=token) response = redirect("/") response.set_cookie('token', token) return response return render(request, "destination/register.html") here are my models in case if needed class User(models.Model): id = models.BigAutoField(primary_key=True) name = models.TextField() email = models.EmailField(unique=True) password_hash = models.TextField() class Session(models.Model): id = models.BigAutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) token = models.TextField() register.html <!DOCTYPE html> <html lang="en"> <head> <meta … -
Excel File Corrupted When Downloaded from Django Backend via Axios in Vue.js
I'm trying to download an Excel file from my Django backend to the frontend using Axios and FileSaver.js (also tried without this). The file is generated successfully on the backend, but when I download it through the frontend, the file becomes corrupted and cannot be opened by Excel. I am using pandas to create the Excel file in-memory and then return it as a response. Backend code - buffer = BytesIO() with pd.ExcelWriter(buffer, engine='xlsxwriter') as writer: for item in data_list: attributes = item['attributes'] attributes['ID'] = item['id'] df = pd.DataFrame([attributes]) sheet_name = f"Sheet_{item['id']}" df.to_excel(writer, sheet_name=sheet_name, index=False) buffer.seek(0) response = HttpResponse(buffer, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename="data_export.xlsx"' return response Frontend code - async function downloadFile() { try { const response = await axios.get('/api/export-excel', { responseType: 'blob', }); saveAs(new Blob([response.data]), 'data_export.xlsx'); } catch (error) { console.error('Error downloading file:', error); } } I know there are similar questions already asked and I have already tried those things (using arraybuffer, type - ms-excel, also tried using openpyxl) but none seems to work. What could be causing the file corruption during download via the frontend? How can I ensure that the file downloads correctly and opens in Excel without corruption? Any advice or suggestions would be greatly … -
Django problem cannot connect to PostgreSQL server in Docker container
I have this logs 2024-10-21 23:55:07 django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: Connection refused 2024-10-21 23:55:07 Is the server running on that host and accepting TCP/IP connections? 2024-10-21 23:55:07 connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused 2024-10-21 23:55:07 Is the server running on that host and accepting TCP/IP connections? but my PostgreSQL server is working proprely there are my postgres logs 2024-10-21 23:50:15 2024-10-21 18:50:15.916 UTC [29] LOG: database system was shut down at 2024-10-21 18:50:14 UTC 2024-10-21 23:50:15 2024-10-21 18:50:15.918 UTC [1] LOG: database system is ready to accept connections database setting inside django DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'pgdb', 'USER': 'postgres', 'PASSWORD': 'admin', 'HOST': 'localhost', 'PORT': '5432', } } compose file version: '3.8' services: web: build: . command: bash -c "python /app/manage.py migrate && python /app/manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 depends_on: - postgres volumes: - .:/app postgres: image: postgres:latest environment: POSTGRES_DB: pgdb POSTGRES_USER: postgres POSTGRES_PASSWORD: admin ports: - "5433:5432" dockerfile FROM python:3.11 WORKDIR /app COPY . /app RUN pip install -r requirements.txt && pip install psycopg2-binary COPY . . I want just run django server on docker, I have tried to run my friend's completed project … -
django-react basic system architecture required
I am trying to understand how a django react project operates? If someone can give me a rough system architecture it would be really helpful. I am creating a music room based on spotify API using django react as my pillars of the project. Help me create a system architecture for it -
gradual migration of django monolith to async
I have huge django2 app (without django ORM) and I want to make it asynchronous. Right now i've come up with two strategies: upgrade to django 3/4 and migrate to async view by view add separate app (fastapi), migrate each view to the new app, and while migration is in progress split traffic between apps on load balancer level. the problem with first approach is that django will switch between sync and async mode and I will not see any improvements before migrating most of the views. the problem with second approach is that it is somewhat complicated and will require more code migrations and infra tinkering. any suggestions? -
Django Environment Identifying the DEBUG as False while it is set to True
I get and error CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False Below are the edits I attempted seeing at stackoverflow's suggestion from various (queries)[https://stackoverflow.com/questions/66923320/why-it-doesnt-set-debug-true] around 5 of them were relevant and tried to edit accordingly. ... I also checked for views and urls for any filename mistyping and typo errors. Yet I am getting CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. I closed the session and changed the open .py file default from vscode and then with python. Yet this error is persistent PLEASE HELP My settings.py has DEBUG = TRUE ALLOWED_HOSTS = [] I have also tried ALLOWED_HOSTS = ['*'] then ALLOWED_HOSTS = ['localhost'] then ALLOWED_HOSTS = ['127.0.0.1'] then ALLOWED_HOSTS = ['localhost', '127.0.0.1'] once with DEBUG = FALSE and then with DEBUG = TRUE Alternately I Tried this TEMPLATE_DEBUG = DEBUG if not DEBUG: ALLOWED_HOST = ['0.0.0.0', '127.0.0.1','localhost','*'] ALLOWED_HOSTS = []``` The issue still persists despite Changing VS code settings .py extension change from VSCODE to Python interpreter and vice versa. -
Django circular import (models-views(-forms))
Watched all the previous related topics devoted to this problem, but haven't found a proper solution, so decided to create my own question. I'm creating a forum project (as a part of the site project). Views are made via class-based views: SubForumListView leads to a main forum page, where its main sections ("subforums") are listed. TopicListView, in its turn, leads to the pages of certain subforums with the list of active topics created within the subforum. ShowTopic view leads to a certain topic page with a list of comments. The problem manifests itself because of: Models.py: Method get_absolute_url in the model Subforum, which in its return section's reverse function takes a view as the 1st argument; I've tried to avoid a direct import of the view, but the program doesn't accept other variants; Views.py: most of the views have imported models either in instance arguments (model = Subforum), or in methods using querysets (like in get_context_data: topics = Topic.objects.all()); I can't surely say whether the change of instance argument model = Subforum to model = 'Subforum' really helps, as it's impossible to do with queryset methods and thus can't be proved; Forms.py: my form classes were created via forms.ModelForm and … -
Django: How to add objects to ManyToManyFields of multiple objects in a fast way?
We have models.py file : class Car(models.Model): brand = models.CharField(max_length=50 , null=True , blank=True) sub_brand = models.CharField(max_length=50 , null=True , blank=True) code = models.CharField(max_length=20 , unique=True) class Skill(models.Model): car = models.ForeignKey(Car , on_delete=models.CASCADE, null=True , blank=True) skill = models.CharField(max_length=50 , null=True , blank=True) class Provider(models.Model): name = models.CharField(max_length=100) skills = models.ManyToManyField(Skill , blank=True) and we want to add some skills based on cars to the provider model so I use views.py like this: def skills_add(request , id): provider = get_object_or_404(Provider , id=id) if request.method == 'POST': form = AddSkill(request.POST) if form.is_valid(): data = form.cleaned_data cars = Car.objects.filter(brand=data['brand']) for i in cars: for x in data['skills']: skill = Skill.objects.get(car=i , skill=x) provider.skills.add(skill) provider.save() else: return redirect("managers:dashboard_manager") return redirect(request.META.get('HTTP_REFERER')) the data["brand"] is a string of one brand of car and data["skills"] is a list of strings that each one of them are name of one skill that we have in out database. you send the data to form and then it's start to filter cars with that brand . after that , We start to loop over those cars and loop over the skills that sended . We add each one of them to skills field of the provider. But the problem … -
How can I handle multiple separate models in a single AJAX request using Django REST Framework?
In my Django project (version 5.1.2), I need to handle data from multiple models in a single AJAX request from the front end. For example, I have a form that collects user information and shipping addresses at the same time. I want to submit this data in a single request and have it saved in separate models in the database. I’m using Django REST Framework to manage the API, but I’m unsure how to properly validate and save multiple models at once in one request. Currently, I am using one ViewSet per model, but I don’t know how to combine them in a single AJAX request and ensure that if there’s an error in one of the models, none of the data is saved (i.e., I want proper transaction handling). Is there a recommended solution for this in Django 5.1.2? What is the best way to handle multiple models in a single AJAX request in Django REST Framework? Details: I'm using Django 5.1.2. Both user and address information need to be saved transactionally. What I Tried: I created two separate ViewSets for the user information and shipping address models. Then, I tried to send the form data via a single … -
Encoding problem when migrating postgresql database tables to models.py django
When performing table migration python manage.py inspectdb > example/models.py all Cyrillic strings are transposed as a set of unknown characters: 'id_шёїюф ∙хую' Encoding of the database server as well as python script is UTF-8. Is there any way to solve this problem? I tried show server_encoding; and got UTF8, tried set PYTHONIOENCODING=UTF-8 Also, I added 'OPTIONS': { 'client_encoding': 'UTF8', } into settings.py. All aforementioned methods didn't help and problem is still existing. I use psycopg package. -
swagger select a defintion for django
so, I've been working on my Django project Apis and i'm using drf-spectacular for the swagger view this is in my settings.py: SPECTACULAR_SETTINGS = { 'TITLE': 'Your Project API', 'DESCRIPTION': 'Resume Swagger API', 'VERSION': '1.0.0', 'SERVE_INCLUDE_SCHEMA': False, } and ofc this in my main urls.py: urlpatterns = [ # Swagger Url path('api/schema/', SpectacularAPIView.as_view(), name='schema'), # Optional UI: path('', SpectacularSwaggerView.as_view(), name='swagger-ui'), ] it has no drop down in order to select a definition, I mean i don't know if such thing exist for django: this is how my swagger looks like: enter image description here but i've seen this for as far as i know for an ASP.NET project that has such drop down to navigate between different api endpoints as below: enter image description here is this achievable in django? I've searched alot through docs and everything but i guess there is no such a guide to do this i hope someone comes up with a solution? -
bin/bash logs screw up after running django query create - ÄDEBUGÅ instead [DEBUG]
When running this django command: MyObjectBase.objects.create( ..., report_pdf=open(f"{REPORT_PATH}/{file_name}.pdf", "rb").read(), ... ) My log output in the bin/bash console of VS Code in WSL2 on Win11 gets screwed. Instead before the command: [2024-10-21 13:40:52 +0200] [923356] [DEBUG] this is a debug message I am getting logs like: Ä21/Oct/2024:11:47:18 +0000Å ÄDEBUGÅ Backticks turn into 'é'. It looks like that during the create-command the binaries of the file are printed to the log like (just thousands of chars longer than this sample) ÖxecoÖxc6Öxd2ÖxffÖxd6ÖxffKÖx00xyÖxchÖxfaÖxe66Öx7fÖx98Ö This does not happen for every report, using different base data does not cause this effect. Unfortunately it is impossible for me to detect differences. I can say that the base data only contains strings and doubles and so on but no nested blobs or strings like code, but special chars like # are possible. I tried another terminal. tmux was available by default. It does not face this problems, logs stay fine. But not using (one of) the most default terminals is not a valid solution for me. So I am looking after the cause and hope to get it solved somehow. As an alternative I could imagine to suppress the binaries from the log when running django create. … -
The code_verifier does not match the code_challenge supplied in the authorization request for PKCE. error
I'm trying to get access token and refresh token of Microsoft account. const loginAndGetAuthorizationCode = async () => { const code_verifier = generateCodeVerifier(); const code_challenge = await generateCodeChallenge(code_verifier); localStorage.setItem('code_verifier', code_verifier); localStorage.setItem('code_challenge', code_challenge); const loginRequest = { tenant: "common", scopes: ["User.Read", "Mail.Read"], response_type: "code", responseMode: "query", state: code_verifier, codeChallenge: code_challenge, codeChallengeMethod: "S256", }; try { const loginResponse = await msalInstance.acquireTokenRedirect(loginRequest); console.log("loginResponse => ", loginResponse); } catch (error) { console.error("Login failed: ", error); } }; This is config import { PublicClientApplication } from "@azure/msal-browser"; const msalConfig = { auth: { clientId: "ID", // client ID authority: "https://login.microsoftonline.com/tenantID", // tenant ID redirectUri: "http://localhost:3000/dashboard", }, cache: { cacheLocation: "sessionStorage", storeAuthStateInCookie: true, } }; const msalInstance = new PublicClientApplication(msalConfig); await msalInstance.initialize(); // await msalInstance.handleRedirectPromise(); export { msalInstance }; This are utils functions export function generateCodeVerifier() { const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"; const array = new Uint8Array(43); // Minimum length of 43 window.crypto.getRandomValues(array); return Array.from(array, (b) => characters[b % characters.length]).join(""); } // Generate the code challenge from the code verifier export async function generateCodeChallenge(codeVerifier: string) { const encoder = new TextEncoder(); const data = encoder.encode(codeVerifier); const digest = await window.crypto.subtle.digest("SHA-256", data); // Convert Uint8Array to an array using Array.from() before processing const base64Digest = btoa(String.fromCharCode(...Array.from(new Uint8Array(digest)))) .replace(/\+/g, … -
Issue with updating read-only fields in Django admin: flags not saving
I’m working on a Django admin interface where certain fields (specifically, review status flags such as is_pending_review_section_title_en and is_pending_review_section_title_uk) should be marked as read-only in the admin interface, but still be updated programmatically when content changes. I’ve implemented the logic to dynamically determine the fields as read-only using the get_readonly_fields method inside an inline admin class (SectionInline). Although the fields correctly display as read-only in the interface, the problem arises when I try to update these fields in the save_model method of the PageAdmin class (or even in forms). The flags appear to be set correctly in the code, but they do not persist in the database after saving. Here is a summary of what I’ve tried: 1. Marked fields as read-only using get_readonly_fields — This works for the admin UI. 2. Tried updating the fields programmatically inside save_model in the PageAdmin class and verified the values through logging. The flags are set to True, but after saving, the values in the database remain unchanged. 3. Commented out form save logic to check if it’s interfering with saving, but the issue persists. 4. Ensured flags are not present in forms to avoid user interaction. What could be causing the fields … -
Unable to exclude foreign keys in django
I'm failing to get Profiles whithout an Interaction. Does anybody see what I'm doing wrong? #models.py class Profile(models.Model): username = models.CharField(max_length=100) class Interaction(models.Model): user_id = models.ForeignKey(Profile,on_delete=models.CASCADE, null=True, blank=True) #test.py class TestQueries(TestCase): def test_get_profiles_without_interaction(self): profile_with_interaction = Profile.objects.get(username='foobar') interactions_from_profile = Interaction.objects.filter( user_id=profile_with_interaction) assert interactions_from_profile #####FAILS##### all_profiles_without_interaction = Profile.objects.exclude( pk__in=Interaction.objects.all()) assert profile_with_interaction not in all_profiles_without_interaction -
How to Send Authentication Token from Frontend using Both Fetch & Ajax to Restful API Backend?
I am currently working with django restframwork, I am on my training period. I created a api for lottery management system using DRF and in this restful api i added IsAuthenticated permission class. Now i am creating demo project for this api, now i am using ajax for requests & sending authorization using btoa. but i am sure that this is not a professional method. I wanted to learn how to send the authorization token to backend with username and password. & also how to achieve same in reactjs as i am little bit familiar with react js and working on it as well. function ajaxCall(type, url, data, callback) { /**Common Method to handle all the Ajax Requests */ $.ajax({ url: url, type: type, data: data, headers: { "Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD) }, success: function (response, status, xhr) { console.log(response); console.log(xhr); if (xhr.status != 204) { if (callback) { callback(response); } } }, error: function (xhr, status, error) { console.error("Error occurred:", xhr.responseText, status, error); }, }); } -
django rest-frame-work user_id related "violates not-null constraint"
I have this error jango.db.utils.IntegrityError: null value in column "user_id" of relation "defapp_actionlog" violates not-null constraint DETAIL: Failing row contains (13, "{\"action\":\"push\"}", 2024-10-21 06:11:30.43758+00, 2024-10-21 06:11:30.43759+00, null). What I want to do is push the actionlog from javascript and set the login user to model. I set the CustomUser object to user row, however it still requies user_id? my viewset,model,serializer is like this below. class ActionLogViewSet(viewsets.ModelViewSet): queryset = m.ActionLog.objects.all() serializer_class = s.ActionLogSerializer def perform_create(self, serializer): obj = serializer.save() return obj def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) request.data._mutable = True request.data['user'] = m.CustomUser.objects.get(id=request.user.id) try: serializer.is_valid(raise_exception=True) except Exception as e: logger.info(e) self.perform_create(serializer) return Response(serializer.data) class ActionLog(models.Model): user = models.ForeignKey(CustomUser,on_delete=models.CASCADE,related_name='action_user') detail = models.JSONField(default=dict,null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class ActionLogSerializer(ModelSerializer): id = serializers.IntegerField(read_only=True) user = CustomUserSerializer(read_only=True,source="actionlog_user") detail = serializers.CharField() class Meta: model = m.ActionLog fields = ('id','user','detail')