Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django for-loop to calculate laon repyament and interest for a period only displaying the last iteration
Am building a loan system to calculate the repayment period. am having this issue when i run the code it only display the last row. below is my view.py please i need it to display all the rows not only the last row def sveloan(request): if 'userid' in request.session: if request.method == 'POST': balance = 120000 annual_interest_rate = 42 monthly_payment_rate =0.3 monthly_interest_rate = annual_interest_rate / 12 monthly_payment = monthly_payment_rate * balance new_balance= (balance - monthly_payment) * (1 + monthly_interest_rate) for month in range(1, 6): monthly_payment = 20000 balance = (balance - monthly_payment) rateint = (balance / 100 * monthly_interest_rate) mydist = ('Month: %d \n Minimum monthly payment: %g \n Remaining balance: %g \n Minimum Interest payment: %g'\ % (month, round(monthly_payment, 2), round(balance,2), round(rateint, 2))) context={ 'mylist': mydist } return render(request,'loantest.html',context) else: return render(request,'index.html') else: return render(request,'index.html') in my template: {% for p in mylist %} {{p}} {% endfor %} -
Removing a non-nullable Django field with SeparateDatabaseAndState
Let's say I have the following model: class Product(models.Model): name = models.CharField(max_length=128) is_retired = models.BooleanField(default=False) I want to remove the is_retired field. I'm using blue-green deployments to release changes to production so I'm using SeparateDatabaseAndState in my migration. My initial migration to remove the field from the application state is simple: class Migration(migrations.Migration): dependencies = ... operations = [ migrations.SeparateDatabaseAndState( state_operations=[ migrations.RemoveField( model_name="product", name="is_retired", ), ], database_operations=[], ), ] I can successfully run the migration. However, I'm getting the following error when I attempt to create a new product with Product.objects.create(name="Wrench"): self = <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x106bf4050> query = 'INSERT INTO "core_product" ("name") VALUES (?) RETURNING "core_product"."id"' params = ('Wrench',) def execute(self, query, params=None): if params is None: return super().execute(query) # Extract names if params is a mapping, i.e. "pyformat" style is used. param_names = list(params) if isinstance(params, Mapping) else None query = self.convert_query(query, param_names=param_names) > return super().execute(query, params) E django.db.utils.IntegrityError: NOT NULL constraint failed: core_product.is_retired Looks like the INSERT query is failing because the is_retired field is defaulting to null, instead of its correct default of False. I've fixed it by making Product.is_retired nullable before removing it from the state: class Migration(migrations.Migration): dependencies = ... operations = [ migrations.AlterField( … -
Method Not Allowed (GET): /accounts/logout/
there is an issue in Django with the LogoutView. when I put the link 'accounts/logout' it prompts in the cmd "GET /accounts/logout/ HTTP/1.1" 405 0 Method Not Allowed (GET): /accounts/logout/ Method Not Allowed: /accounts/logout/. this is the urlpatterns: urlpatterns = [ path('', include('django.contrib.auth.urls')), path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'), path('profile/', showProfile, name='profile'), path('logout/', auth_views.LogoutView.as_view(template_name='registration/logged_out.html'), name='logout'), ] and this is the 'registration/logged_out.html' file content: {% extends "generic_base.html" %} {% block content %} <form method="post" action="{% url 'user:logout' %}"> {% csrf_token %} <button type="submit">Logout</button> </form> {% endblock content %} I saw a lot of ways to fix this. but none of them worked. -
Hosting django with celery and redis
I want to host my django project.But i donot know which hosting site will support celery and redis.Can someone suggest me some website for hosting. -
How do I make my test behave as expected when my model is updated?
My view class MovieUpdateView(UpdateView): model = Movie template_name = "movie_update.html" fields = [ 'movie_name', 'movie_year', 'movie_director', 'movie_rating', 'movie_cover_image' ] def get_success_url(self): return reverse_lazy('movie_detail', kwargs={'pk': self.object.pk}) My test update def setUp(self): self.movie = Movie.objects.create( movie_name='Avengers - Endgame', movie_year= 2019, movie_director='Anthony Russo, Joe Russo', movie_rating=10.0, movie_cover_image = '\movies\images\movies_covers\1f8373201516a4657649d61e97b1f91a_WhvCLCe.jpg' ) def test_movie_update_view(self): self.assertEqual(self.movie.movie_name, 'Avengers - Endgame') movie_update = { 'movie_name' :'Title Updated', 'movie_director' :'New Director', } response = self.client.post( reverse('movie_update', kwargs={'pk': self.movie.pk}), data=movie_update ) self.movie.refresh_from_db() self.assertEqual(self.movie.movie_name, 'Title Updated') File "E:\\Users\\Santiago\\Desktop\\web-projects\\personal_blog\\reviews\\tests.py", line 99, in test_movie_update_view self.assertEqual(self.movie.movie_name, 'Title Updated') AssertionError: 'Avengers - Endgame' != 'Title Updated' - Avengers - Endgame + Title Updated I want to test my MovieUpdateView view based on the UpdateView generic class, but when I try to update through the test, I can't, but manually through the site, everything is fine, when I update it's ok, I'm still starting with the tests, maybe I did something wrong! -
Django Django administration shows more objects then the actual datapoints
I have created a Django model and uploaded some data, around 90 data point. I deleted and uploaded these data points multiple times for testing purposes. I notice my Django admin showing object number much higher then the actual data point present in the database. PeptideSeq object (695) While the total data point I have around 90. Is these normal behavior or is there a way to correct this issue and start the count from zero when you delete all objects. I used Django admin GUI to delete objects. Thanks! -
failed to solve: process "/bin/sh -c pip install -r requirements.txt" did not complete successfully: exit code: 1
I am using this Dockerfile for my Django + React(Vite) application. Its giving the same error every time when I am running it with docker-compose build GitHub: click here Dockerfile (Django) FROM python:3.10-slim ENV PYTHONUNBUFFERED=1 ENV EMAIL_HOST_USER=email ENV EMAIL_HOST_PASSWORD=password WORKDIR /backend RUN apt-get update && apt-get install -y libpq-dev build-essential RUN pip install -r requirements.txt COPY . . EXPOSE 8000 Dockerfile (React) FROM node:20.6-buster-slim WORKDIR /frontend COPY . . RUN npm install EXPOSE 5173 CMD ["npm", "run", "dev"] docker-compose.yml services: backend: build: ./backend ports: - "8000:8000" volumes: - ./backend:/backend command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" frontend: build: ./frontend ports: - "5173:5173" volumes: - ./frontend:/frontend I would appreciate if anyone can help me with solving the issue and make the build successful with dockerizing the whole application. -
Dynamic chat page on django channel
At the moment my chat room functions through 2 simple pages: home.html (chat list) and chat_room.html with input field and connection to a web socket: <!DOCTYPE html> <html> <head> <title>Chat Rooms</title> </head> <body> <div> <h1>Chat Rooms</h1> <ul> {% for room in chat_rooms %} <li><a href="{% url 'chat_room' room.id %}">{{ room.name }}</a></li> {% endfor %} </ul> </div> </body> </html> chat_room.html: <!DOCTYPE html> <html> <head> <title>{{ room.name }}</title> <script> var room_id = {{ room.id }}; var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + room_id + '/'); chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data['message']; var sender = data['sender']; var chatMessages = document.querySelector('#messages'); var messageElement = document.createElement('p'); messageElement.innerHTML = '<strong>' + sender + ':</strong> ' + message; chatMessages.appendChild(messageElement); }; function sendMessage() { var messageInputDom = document.querySelector('#id_content'); var message = messageInputDom.value; var sender = "User"; chatSocket.send(JSON.stringify({ 'message': message, 'sender': sender })); messageInputDom.value = ''; } </script> </head> <body> <h1>{{ room.name }}</h1> <div id="messages"> {% for message in messages %} <p><strong>{{ message.sender }}:</strong> {{ message.content }}</p> {% endfor %} </div> <form id="message-form" onsubmit="event.preventDefault(); sendMessage()"> {% csrf_token %} {{ form }} <button type="submit">Send</button> </form> </body> </html> Both pages are received by the user through the view renderer: def home(request): … -
Error occurred during python3.7 pip install mysqlclient
When I tried to use pip install mysqlclient, I encountered the error shown in the screenshot. My Python version is 3.7, and I attempted to install mysqlclient version 2.1.1. I'm using MacOS with Anaconda. Initially, I executed brew install mysql-connector-c and then brew install mysql-client in the macOS terminal. I configured the environment variables according to the official documentation, but I still encountered installation errors later on. I downloaded the compressed source code files, extracted them, and moved them to the site-packages directory of Anaconda. However, when I tried pip install mysqlclient, I encountered the following error. How can I resolve this issue?Installation error I need to resolve these issues before I can install it. -
Phone won't vibrate when receiving firebase push notification
I am sending firebase push notification using the python sdk but I am having an issue. Even though the notifications are being delivered, however it doesn't vibrate the phone. Below is my code. message = messaging.Message( token=token, notification=messaging.Notification( title=title, body=body, ), ) messaging.send(message) I have tried everything, used data message also but no difference. I have also tried some examples on here but still the same thing. I would really appreciate any help. Thank you -
Is Postgres good for long text?
I designed a corporate website with Django and Postgres. I made a blog section for him. I am uploading the contents that I wrote in WordPress to the blog of the new site. But I get an error OperationalError at /en/admin/blog_app/blog/add/ index row size 3144 exceeds btree version 4 maximum 2704 for index "blog_text_key" DETAIL: Index row references tuple (24,1) in relation "blog". HINT: Values larger than 1/3 of a buffer page cannot be indexed. Consider a function index of an MD5 hash of the value, or use full text indexing. I researched about this error and found out that the WordPress content is too big for the Postgres database. What is your suggestion? Should I change the database? Or can the problem be solved? Thank you for your guidance. -
Switching from directory-based URL to subdomain-based URL in ReactJS and Django
I have developed a web application using ReactJS and Django, allowing users to create custom websites. Currently, these websites are stored in the website.com/applicationname directory. However, I want to switch to a subdomain-based URL structure, where each user's custom website is accessible via applicationname.website.com. How can I achieve that? My application is hosted in Heroku. -
Django link table row to detail view with buttons to other views
Hey thanks in advance for any help its always much appropriated. So I found this post on here that help do this and it worked great. So i have my table and when you click a row it goes to the right detail view for that row. What i would also like to do is have a column in the table with a button for delete and one for edit for each row. I was able to add the buttons but it looks like the JS code that makes the rows clickable is overriding the buttons. without the JS code the buttons work. Any guidance on what to look up or helpful terms to make the rows clickable and and buttons not be lumped into it. Sorry I've very new to this in general and especially inexperienced in javascript I tested with the rows not clickable (no javascript) and the buttons that are in work and go to the intended view. I also tried moving data-href="{% url 'detail' part.pk %}"the tag in the html the Table tag. this made a single cell clicked as expected (not what i want) but the buttons become clickable again but don't route properly. I … -
Error: The invalid form control is not focusable
I'm encountering an issue with my Django form where I'm getting the following error messages in my browser console: The invalid form control with name=‘content’ is not focusable. An invalid form control is not focusable. I'm not sure what's causing this error or how to resolve it. I've checked my HTML form and Django view, but I can't seem to find any obvious issues. Btw, I'm kind of new to both CKEditor and Django, excuse me for any "dumb" requests - I just couldn't find a fix to this. Here's a snippet of my HTML form: create.html: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Create Post</title> <link rel="stylesheet" href="{% static 'django_ckeditor_5/dist/styles.css' %}"> </head> <body> <div class="container"> <div class="card"> <h1>Create Post</h1> <form action="" method="POST" enctype="multipart/form-data"> <!-- Other fields, removed for simplicity reasons. --> <div class="input"> {{ form.content }} </div> <button type="submit">Create Post</button> </form> </div> </div> <script src="{% static 'django_ckeditor_5/dist/bundle.js' %}"></script> </body> </html> views.py(only the function required for create.html: def createPost(request): if request.user.is_authenticated: if request.method == "POST": form = forms.CreatePostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.slug = slugify(post.title) post.save() messages.success(request, 'Post created successfully.') return redirect('home') else: messages.error(request, 'Error creating post. … -
How can I deploy a Django project with a pickled model in Railway app?
I would like to deploy my Django project on a Railway app, but the server does not find the pickled model. Although I made sure that the file exists in the github repository that I am deploying, Railway app continuously displays this error: from core import views File "/app/core/views.py", line 37, in binary_clf = joblib.load(os.path.abspath('binary_classifier.pkl')) File "/opt/venv/lib/python3.8/site-packages/joblib/numpy_pickle.py", line 650, in load with open(filename, 'rb') as f: FileNotFoundError: [Errno 2] No such file or directory: '/app/binary_classifier.pkl' The thing is, I don't have any static files except for this pickled ML model. But, I tried including the pickled model in a 'static' folder like it was described here, in which case I got this error: from core import views File "/app/core/views.py", line 37, in binary_clf = joblib.load("static/binary_classifier.pkl") File "/opt/venv/lib/python3.8/site-packages/joblib/numpy_pickle.py", line 650, in load with open(filename, 'rb') as f: FileNotFoundError: [Errno 2] No such file or directory: 'static/binary_classifier.pkl' How are we supposed to deploy Django apps when we have pickled files in it? -
Operational Error in Django: Migrating a Python Web Application to a mariadb database
I am trying to connect a mariadb database that I created in a Linux VM and have my python web application migrate the files over. When I use the python manage.py migrate command, I come across this error: django.db.utils.OperationalError: (2002, "Can't connect to server on '127.0.0.1' (36)") When connecting to the database in my terminal, I end up with this error: mysql -h '127.0.0.1' -P maxdj2k polls_db ERROR 2002 (HY000): Can't connect to server on '127.0.0.1' (36) I'm trying to connect via unix_socket, and have already routed the file to the correct path in my my.cnf file. (/tmp/mysql.sock) is not correct and I'm not entirely sure why it designates that as the path outright. Here is my DATABASES section in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'NAME': 'polls_db', 'USER': 'maxdj2k', 'PASSWORD': 'M24i21F27*', } } I've also included an options parameter under 'PASSWORD' to specify where the actual path for my socket file is. Here is my my.cnf file In linux: # # This group is read both both by the client and the server # use it for options that affect everything # [client-server] socket=/var/lib/mysql/mysql.sock port=3306 # # include all files from the config directory # … -
cannot get token and store it is local storage
I want to while logging user to send post request to http://127.0.0.1:8000/auth/token/login to get auth user token, store it i local storage and then log in user i need this token in local storage for sending post request and getting api response back in my vue cuz now it hardcoded <template> <div> <div v-if="question">{{ question }}</div> <div v-else>Loading...</div> </div> </template> <script> import axios from 'axios'; export default { name: 'QuestionView', props: { slug: { type: String, required: true, }, }, data() { return { question: null }; }, methods: { async getQuestionData() { const endpoint = `http://localhost:8000/api/v1/questions/${this.slug}`; try { const response = await axios.get(endpoint, { headers: { 'Authorization': 'token (here is my token) ' }s }); this.question = response.data; // Assuming your API response is an object containing question information } catch(error) { console.log(error.response); alert(error.response.statusText); } } }, created() { this.getQuestionData(); } } </script> this login.html logging user but doesn't save token {% extends "auth_layout.html" %} {% load widget_tweaks %} <script> async function loginUser(event) { event.preventDefault(); var username = document.getElementById("username").value; var password = document.getElementById("password").value; console.log('a') try { console.log("s") const response = await fetch("http://127.0.0.1:8000/auth/token/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username: username, password: password }) }); if … -
I created a Babylon with meshes loaded in a X Django app template, now I need to rotate it by clicking buttons located a dash-board on a y Django app
I'm using a Babylon in a Django project, created a app template that I have few meshes loaded and I did set buttons to rotate the meshes using addEventListener, it are working well when the UI buttons is located in the same HTML template where the canvas is loaded, APP X. My main goal is to have the UI buttons located in a template that will be a dash-board created on a different APP, APP Y on my Django project. When I place the UI buttons in the Y APP (dash-board template) I get the error: Uncaught TypeError: Cannot read properties of undefined (reading 'trackUbosInFrame') at new e (uniformBuffer.ts:256:36) at t.createSceneUniformBuffer (scene.ts:2405:26) at Ar.createSceneUniformBuffer (engine.multiview.ts:203:12) at t._createUbo (scene.ts:1933:41) at new t (scene.ts:1690:14) at HTMLDocument. (jackpot.js?v=:7:17). My JS rotation setup located in my Django JS file inside X APP: javascript function createRotationLogic(mesh, axis, speed) { var rotationAxis; switch (axis) { case "X": rotationAxis = BABYLON.Axis.X; break; case "Y": rotationAxis = BABYLON.Axis.Y; break; case "Z": rotationAxis = BABYLON.Axis.Z; break; default: rotationAxis = BABYLON.Axis.Y; } return function () { scene.unregisterBeforeRender(mesh); scene.registerBeforeRender(function () { mesh.rotate(rotationAxis, speed, BABYLON.Space.LOCAL); }); setTimeout(function () { scene.unregisterBeforeRender(mesh); }, 30000); // Stop after 30 seconds }; } // Function to … -
Javascript request to Python Django not found
I am new to Django and Javascript. Now totally stuck with this error, probably a really small thing, but I can not figure out what can be the problem. I would like to delete a document through my form using Javascript and send it to my Django backend through a request. At the terminal I get this error message: "Not Found: /delete_document/7/ [23/Feb/2024 13:26:53] "DELETE /delete_document/7/ HTTP/1.1" 404 2371" The request color is yellow and it happens as I see, it just can not find my view function. views.py @require_http_methods(['DELETE']) def delete_document(request, document_id): document = get_object_or_404(Document, pk=document_id) document.delete() return JsonResponse({'message': 'Document deleted successfully'}, status=204) urls.py from django.urls import path from . import views # Define namespace app_name = 'advice' urlpatterns = [ ... path('delete_document/<int:document_id>/', views.delete_document, name='delete_document'), ] index.html relevant parts <form id="documentForm" action="" method="post" data-base-action="{% url 'advice:gpt_base' %}"> {% csrf_token %} <input type="hidden" name="firstQuestion" value="True"> <select id="documentSelect" class="form-select" aria-label="Select form"> <option selected>Select a file</option> {% for document in documents %} <option value="{{ document.id }}">{{ document.title }}: {{ document.uploaded_file.url }}</option> {% endfor %} </select> <button type="button" class="btn btn-danger" id="deleteButton">Delete</button> <br> <button type="submit" class="btn btn-primary">Submit</button> </form> <script> document.getElementById('deleteButton').addEventListener('click', function() { var selectedDocumentId = document.getElementById('documentSelect').value; if (selectedDocumentId === 'Select a file') { alert('Please … -
Slow response from Django Rest Framework with annotated queryset
I am using Django Rest Framework and simply trying to filter out objects which have more than 0 related items but as soon as I add in a filter to my annotation that includes a datetime, the response time goes from milliseconds to 90 seconds or so. Here is the code that takes ages:- class EventVenueViewSet(viewsets.ReadOnlyModelViewSet): queryset = EventVenue.objects.annotate( num_slots=models.Count( "eventblock__eventslot", filter=Q(eventblock__status='active') & Q( eventblock__eventslot__start_time__gt=timezone.now() + timedelta(days=2) ) ) ).filter(num_slots__gt=0) If I remove the filter that includes the DateTimeField (start_time)... class EventVenueViewSet(viewsets.ReadOnlyModelViewSet): queryset = EventVenue.objects.annotate( num_slots=models.Count( "eventblock__eventslot", filter=Q(eventblock__status='active') ) ).filter(num_slots__gt=0) it is very fast. But the presence of that datetime filter slows it down to the point of being useless. It's nothing to do with db lookups - it's doing 8 of those so that's fine. The SQL query looks fine and the results are correct - it's just taking soooooo long! Any ideas? -
Could not translate host name "db" to address: Name or service not known
I'm using Django + Docker and when building the image of one of my projects I'm facing problems when running the command: docker-compose run web python manage.py makemigrations error: root@debian:/home/suportenpd1/Documentos/setorT# docker-compose run web python manage.py makemigrations [+] Creating 1/0 ✔ Container setort-db-1 Created 0.0s [+] Running 1/1 ✔ Container setort-db-1 Started 1.1s /usr/local/lib/python3.12/site-packages/django/core/management/commands/makemigrations.py:160: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "db" to address: Name or service not known warnings.warn( No changes detected docker-compose.yml: services: db: image: postgres:15.6 volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=setorT - POSTGRES_USER=setorT - POSTGRES_PASSWORD=setorT@2024$ ports: - "5432:5432" web: build: . command: ["./wait-for-it.sh", "db:5432", "--", "python", "manage.py", "runserver", "0.0.0.0:8000"] volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=setorT - POSTGRES_USER=setorT - POSTGRES_PASSWORD=setorT@2024$ depends_on: - db setting.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('POSTGRES_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': 'db', 'PORT': 5432, } } -
Got "No Books matches the given query" error even though the object exist on Django
I got this problem where Django return "No Books matches the given query", even though the object exist in database. For context, I want to create an update page without relying the use of URL. First, here is my model : User = get_user_model() class Books(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=50) author = models.CharField( max_length=40, ) author_nationality = models.CharField(max_length=20, default='Japanese') author_medsos = models.CharField(max_length=30, default='None') book_type = models.CharField( max_length=10, null=True, choices=BOOKS_TYPES ) tl_type = models.CharField( max_length=20, null=True, choices=TRANSLATION_BY ) series_status = models.CharField( max_length=20, choices=SERIES_STATUS, default=ONG ) source = models.CharField(max_length=100) # source can refer to downloage page, example = https://www.justlightnovels.com/2023/03/hollow-regalia/ reading_status = models.CharField( max_length=20, choices=READING_STATUS, default=TOR ) current_progress = models.CharField( # For tracking how many chapter have been read max_length=30, null=True ) cover = models.FileField(upload_to='cover/', default='cover/default.png') genre = models.CharField(max_length=40, null=True) class Review(models.Model): books = models.ForeignKey('Books', on_delete=models.CASCADE, null=True) volume = models.IntegerField() review = models.TextField() Before the user get to the update page, they first have to visit /library page, {% for book in user_books %} <div class='lib-item'> <form method='POST' action="{% url 'core:update_library' %}"> {% csrf_token %} <input type='hidden' name='book_id' value='{{ book.id }}'> <button type='submit'> <img src={{ book.cover.url }} width='185'> <span> {{ book.title }} </span> </button> </form> </div> {% endfor … -
In Django Rest Framework how to make a function base view roll back every change made if somethings fails
I have a api endpoint that the user will send a key pair of file_field: File in the multipart content type. The function need to update every document and create a history about the change. Then It should complete the session that the user used to do this change. If a document couldn't be updated or a historic couldn't be created all the operations and changes should roll back how to archive this. This is my current function base view: @transaction.atomic @api_view(['POST']) @parser_classes([JSONParser, MultiPartParser]) @permission_classes([HasSpecialSessionPermission]) def update_documents(request): user = request.user special_session = SpecialSessionConfiguration.objects.filter(user=user, completed=False).first() lot = DefaultLotModel.objects.filter(user=user, call__active=True).first() for key, uploaded_file in request.FILES.items(): try: validate_file_size(uploaded_file) if key != 'financial_form' and key != 'power_point': validate_file_extension(uploaded_file) except ValidationError as e: return Response({'message': str(e)}, status=status.HTTP_400_BAD_REQUEST) if special_session.special_session_fields.filter( field_name=get_field_number(SPECIAL_SESSION_FIELD, key)).exists(): if hasattr(lot, key): current_file = getattr(lot, key) if current_file: setattr(lot, key, uploaded_file) LotDocumentHistory.objects.create( lot=lot, old_file=current_file, field_name=key, ) setattr(lot, key, uploaded_file) lot.save() else: for child_field in ['first_lots', 'second_lots', 'third_lots']: child_lot = getattr(lot, child_field, None) if child_lot and hasattr(child_lot, key): current_file = getattr(child_lot, key) if current_file: LotDocumentHistory.objects.create( lot=lot, old_file=current_file, field_name=key, ) setattr(child_lot, key, uploaded_file) child_lot.save() elif special_session.extra_files: try: data = {'name': key, 'file': uploaded_file, 'lot': lot.pk} serializer = ExtraFileSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() except ValidationError as ve: error_dict … -
Difficulty Using gettext_lazy in Django 4 Settings with django-stubs, Resulting in Import Cycle and mypy Type Inference Error
Problem: Mypy Error: The mypy error encountered is as follows: error:Import cycle from Django settings module prevents type inference for 'LANGUAGES' [misc] I'm encountering challenges with the usage of gettext_lazy in Django 4 settings while utilizing django-stubs. The recent update in Django 4 brought changes to the typing of gettext_lazy, where the old return type was str, and the new type is _StrPromise. The issue arises from the fact that _StrPromise is defined in "django-stubs/utils/functional.pyi," and within this file, there is also an import of django.db.model which imports settings. This creates a circular import. current module-version: typing mypy = "1.7" django-stubs = "4.2.7" Django dependencies Django = "4.2.10" Seeking advice on a cleaner and more sustainable solution to the circular import issue and mypy error in the context of Django 4 settings with the updated gettext_lazy typing. Any insights or alternative approaches would be greatly appreciated. possible Solutions: Several solutions have been considered, but none of them are ideal: Disable Mypy Typing for Settings: Disabling Mypy typing for settings is a workaround, but it might compromise the benefits of static typing. Remove gettext_lazy from Settings: Another option is to remove gettext_lazy from settings. However, this contradicts the current recommendations in … -
Django - CSRF Failed: CSRF cookie not set
I want to create a API that has login / logout / signup / edit etc, but when I try it in Postman i get the error: CSRF Failed: CSRF cookie not set I've noticed that if the user is not logged in, The API works fine but after the login I get the CSRF error when using any url from it ( /logout/, /login/ etc) views.py `@csrf_exempt @api_view(['POST']) def login_user(request): if request.user.is_authenticated: return JsonResponse({"detail": "User is logged in!"}) body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) nickname = body['nickname'] password = body['password'] user = authenticate(nickname=nickname, password=password) if user is not None: login(request, user) logout(request) return JsonResponse({"response": "Login success!"}) else: return JsonResponse({"error": "Nickname or Password are incorrect!"})` settings.py `MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]` I've seen that I should get a CSRF token in the cookies section in Postman, but the only thing i get is a sessionId