Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saving data to the database in django
I am working on a website to recommend stocks on the stock market, based on historically reliable trading strategies. When running the server, I can't see any of the data which is supposed to be shown on the website. Looking into the db, it appears that most of the data is not being saved to the db. There is also another problem, which may be related: When running the code, I am getting the company name for the last stock which is being looped through, but for the others there it just says 'None'. I would be grateful if anyone can help me with this. Here is the code to loop through each stock: def compile_queue(self): from stock.models import Stock list_of_stocks = Stock.objects.prefetch_related("stock_data", "strategies", "recommendations").values('ticker')[0:101] for i in list_of_stocks.values(): try: #Update db with new data ticker = i.ticker stock_object = Stock_Class(ticker) self.list_of_operations.append(lambda i=i: stock_object.update_data(i)) # Get strategy objects moving_average_strategy = Moving_Average_Strategy(ticker) rsi_strategy = RSI_Strategy(ticker) bollinger_band_strategy = Bollinger_Bands_Strategy(ticker) # Add strategies to the queue self.list_of_operations.append(lambda:moving_average_strategy.apply_strategy()) self.list_of_operations.append(lambda:rsi_strategy.apply_strategy()) self.list_of_operations.append(lambda:bollinger_band_strategy.apply_strategy()) self.list_of_operations.append(lambda:stock_object.set_recommendations(i)) except Exception as e: print(f"(Trading_System.py) The required actions for {i} could not be run due to Error: {e}") Here is part of the code which gets the data for a given stock and … -
How to limit admin django session and renew time after user action
I am improving my django admin session security and I wanted to do 2 things: Limit my admin session time Renew my session time after every user action What is the best way to do? -
How can i use exiftool in django?
I bought my first VPS server and I have ubuntu system on it. I installed exiftool via ‘sudo apt install exiftool’ and when I say the command which exiftool everything is fine I get the response /usr/bin/exiftool. After that I try to make a function to change the tags of the photo in django, but django I think doesn't see exiftool and nothing is added. Anyone know what I can do? I've been trying to fix this for about 5 hours :D import subprocess def set_jpeg_metadata_exiftool(): exiftool_path = "exiftool" title = "Title" subject = "Subject" author = "Me" comment = "Comment" rating_val = 5 copyright_val = "Company name" keywords = 'test' cmd = [ exiftool_path, f'-Title={title}', f'-Subject={subject}', f'-Author={author}', f'-Comment={comment}', f'-Rating={rating_val}', f'-Copyright={copyright_val}', f'-Keywords={keywords}', '-overwrite_original', file_path ] subprocess.run(cmd, check=True, encoding='utf-8') -
Django with React using Vite and Inertia
Inspired by https://github.com/mujahidfa/inertia-django-vite-vue-minimalI created https://github.com/anjanesh/inertia-django-vite-react-minimalto use React (19.0.0) in Django (5.1.5) via Inertia (2.0) but : When I run npm run dev and python manage.py runserver and goto localhost:8000, I get in the browser : Uncaught (in promise) Error: @vitejs/plugin-react can't detect preamble. Something is wrong. See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201 at Index.tsx:1:26 Works in production though - npm run build and python manage.py collectstatic -
Django 5.1 + Postgresql (debian server)
Trying to connect to posgresql base as Django wrote in its docs: https://docs.djangoproject.com/en/5.1/ref/databases/#postgresql-notes DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "OPTIONS": { "service": "my_service", "passfile": ".my_pgpass", }, } } I've created 2 files in my home directory .pg_service.conf [my_service] host=/var/run/postgresql user=dbms dbname=dbms_db port=5432 .pgpass /var/run/postgresql:5432:dbms_db:dbms:my_password Such command as test of .pgpass: psql -h localhost -U dbms dbms_db is working. But the connect doesn't work: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "OPTIONS": { "service": "my_service", "passfile": ".pgpass", }, } } with such error Traceback (most recent call last): File "/home/www/projects/amodulesu/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 279, in ensure_connection self.connect() File "/home/www/projects/amodulesu/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/home/www/projects/amodulesu/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/www/projects/amodulesu/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/home/www/projects/amodulesu/venv/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 332, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/www/projects/amodulesu/venv/lib/python3.11/site-packages/psycopg/connection.py", line 119, in connect raise last_ex.with_traceback(None) psycopg.OperationalError: connection failed: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: Peer authentication failed for user "dbms" ... File "/home/www/projects/amodulesu/venv/lib/python3.11/site-packages/psycopg/connection.py", line 119, in connect raise last_ex.with_traceback(None) django.db.utils.OperationalError: connection failed: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: Peer authentication failed for user "dbms" whats wrong with my code? Trying to use export vars in debian - but … -
only works on first try with listening to keystrokes on input form field using jquery listener
Here is the basic situation: I want to be able to listen to user input on a text input box, the code will use ajax to check the entry after a pause of 5 seconds, against the cached answer. The check works just fine on the first try (after 5 seconds). But if the user blurs out to another field, then tries a second time to enter the correct answer, editing the same field, nothing happens, the ajax request is not performed. The listener seems to have disappeared or stopped working. Here's the code on the template side: let ajax_call = function (endpoint, request_parameters) { $.getJSON(endpoint, request_parameters) .done(response => { ...... }) //response handling }; answerInputs.on('keydown', function(){ answer = $(this); setTimeout(function(){ var answer_seq = answer.data("sequence"); answers[answer_seq] = answer.val(); var request_parameters = {'answers': JSON.stringify(answers), 'idList': JSON.stringify(idList)} // if scheduled_function is NOT undefined, cancel the execution of the function if (typeof(scheduled_function)!='undefined') { clearTimeout(scheduled_function); } // setTimeout returns the ID of the function to be executed scheduled_function = setTimeout(ajax_call, delay_by_in_ms, endpoint, request_parameters); }, 5000); }); -
The dynamically rendered inputs are not being pulled through to the post request?
Code is used to render the input fields based on the different expense types to the edit form // Clear previous fields dynamicFieldsContainer.innerHTML = ''; // Inject fields dynamically for (const [key, value] of Object.entries(data.fields)) { // Skip fields that are null or undefined if (value === null || value === undefined) continue; const field = ` <div class="mb-3"> <label for="${key}" class="form-label">${key.replace('_', ' ').toUpperCase()}</label> <input type="text" class="form-control" id="${key}" name="${key}" value="${value}" required> </div>`; dynamicFieldsContainer.insertAdjacentHTML('beforeend', field); } These are the hidden fields that are already present on the form and are populated by the JS script these, are the only fields present in the POST request // Set hidden ID field document.getElementById('expense-id').value = data.id; // Set hidden expense-type field document.getElementById('expense-type').value = data.type; The current html structure which shows the form and the post action as well as the hidden and dynamically render html tags <form id="editExpenseForm" name="editExpenseForm" method="post" action="{% url 'edit_expense' %}"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" id="editExpenseModalLabel">Edit Expense</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <input type="hidden" name="expense-id" id="expense-id"> <input type="hidden" name="expense-type" id="expense-type"> <div id="dynamic-fields"> <!-- Fields will be injected dynamically --> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button> <button type="submit" class="btn btn-primary">Save Changes</button> </div> </form> -
Getting errors when running automated test for my DRF APi
I’m performing some automated tests on my register/login APIViews (API endpoints) with DRF for my Django project. The trouble I’m running into, I’m not able to successfully run the tests with python manage.py test. I’m sure I set up everything for my APIViews/tests correctly, however I’m getting a traceback error suggesting something might be wrong with my response = self.client.post(url, data, format='json') in my UserRegisterTests from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from ..models import User class UserRegisterTests(APITestCase): def test_register_user(self): url = reverse('register') data = {'email': 'myemail@mail.com', 'password': 'mypassword123'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(User.objects.count(), 1) self.assertEqual(User.objects.post().email, 'myemail@mail.com') self.assertTrue(User.objects.check_password('mypassword1123')) And there might be something wrong with the if serializer.is_valid(): in my register APIView (views) # API endpoint for registration @authentication_classes([JWTAuthentication]) class RegisterView(APIView): def post(self, request): serializer = RegisterSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): serializer.save() return Response({ 'message': 'successfully registered', }, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This may be of some help, here is my RegisterSerializer class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = ['email', 'password', 'password2'] def validate(self, valid): if valid['password'] != valid['password2']: raise serializers.ValidationError({"password": "Passwords do not match."}) return valid def create(self, validated_data): user = User.objects.register_user( email=validated_data['email'], pasword=validated_data['password'] … -
Why the get request won't get data from connected models?
My GET request to list all the posts and comments and replies, doesn't get all the connected models. models.py from django.db import models from django.contrib.auth import get_user_model from django.conf import settings User = get_user_model() class Post(models.Model): id = models.AutoField(primary_key=True) text = models.TextField(max_length=165) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.author}: {self.text}' class Images(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to='images/') post_id = models.ForeignKey(Post, on_delete=models.CASCADE) class Comment(models.Model): id = models.AutoField(primary_key=True) text = models.CharField(max_length=165) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username') class CommentSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) replies = ReplySerializer(many=True, read_only=True) class Meta: model = Comment fields = "__all__" class ImageSerializer(serializers.ModelSerializer): class Meta: model = Images fields = ('image',) class PostSerializer(serializers.ModelSerializer): images = ImageSerializer(many=True, read_only=True) author = UserSerializer(read_only=True) comments = CommentSerializer(many=True, read_only=True) class Meta: model = Post fields = "__all__" views.py class PostsViewSet(ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer urls.py router = DefaultRouter() router.register('posts', PostsViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) So I created superuser and added some posts and images via admin panel. And after all that, I'm getting the following: @baseUrl = http://localhost:8000/ GET {{baseUrl}}/posts/ Content-Type: application/json HTTP/1.1 … -
During testing, Manager isn't available
I've swapped the User model with my own custom User model. It uses the standard UserManager. I also have a CustomUserChangeForm which is used in my UserAdmin. I've set AUTH_USER_MODEL = "accounts.User" in settings. This all works fine when using the site/admin site normally through the browser. Tests on my views that use the custom User model also work fine. Only when I try to run a test directly on the CustomUserChangeForm I get the error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'accounts.User'. What's going wrong here? The test: from .forms import CustomUserChangeForm from .models import User def test_admin_user_change_form(self): self.register_user() self.register_user("email2@site.com", "username2") user = User.objects.get(username="username") # Test valid change form = CustomUserChangeForm({ "username": "username3", "email": "email3@site.com" }, user) self.assertTrue(form.is_valid()) # Test case insensitive username change form = CustomUserChangeForm({ "username": "Username2" }, user) self.assertFalse(form.is_valid()) # Test case insensitive email change form = CustomUserChangeForm({ "email": "Email2@site.com" }, user) self.assertFalse(form.is_valid()) The form: class CustomUserChangeForm(UserChangeForm): def clean_username(self): username = self.cleaned_data.get("username") if username and self._meta.model.objects.exclude(id=self.instance.id).filter(username__iexact=username).exists(): self._update_errors(ValidationError({ "username": self.instance.unique_error_message(self._meta.model, ["username"]) })) else: return username def clean_email(self): return self.cleaned_data.get("email").lower() The answers at this question and this question do not seem to apply/work. -
Django migration from 3.1 to 3.2 error while copying models instances
I'm trying to upgrade Django from 3.1 to 3.2, and one of the error that I encountered was endpoints that I have that duplicate resources and their related models. In this example: @action( detail=True, methods=['POST'], name='Duplicate one resource', url_name='duplicate', url_path='duplicate', ) @transaction.atomic def duplicate(self, request, pk=None): foo = self.get_object() # gets foo foo_bars = foo.foo_bars.all() # gets a queryset of FooBar new_name = self.append_copy_suffix(foo.name) new_foo = foo.copy_instance(name=new_name) # code below print(foo, new_foo) FooBar.objects.bulk_create( [FooBar(foo=new_foo, bar=foo_bar.bar, stuff=foo_bar.stuff) for foo_bar in foo_bars] ) return Response(self.get_serializer(new_foo).data, status=status.HTTP_201_CREATED) def copy_instance(self, **kwargs): """ Method to copy a model instance More info here: https://docs.djangoproject.com/en/3.1/topics/db/queries/#copying-model-instances :param kwargs: additional parameters to update :return: the duplicated resource """ new_resource = self new_resource.pk = None for k, v in kwargs.items(): setattr(new_resource, k, v) new_resource._state.adding = True new_resource.save() return new_resource This works pretty well in Django 3.1, but in Django 3.2, the related resources are not created for some reason. Things that I noticed in debug and printing the values: When I print the foo and new_foo, they are the same one (new_foo). foo_bars is empty. Maybe because the foo and new_foo are the same one before the bulk_create and the foo_bars is just a queryset that was yet to be … -
ModuleNotFoundError: No module named 'django_invoice'
I get this error every time I try to do migrations or even run my py manage.py runserver. I installed the 'django_invoice' module, inserted it in INSTALLED_APP but still I get the same error over and over again. I installed the requested module hoping that the problem would be fixed but unfortunately it wasn't. -
Can I define an Alias to a foreign field in Django?
I'm looking to define an alias to a foreign key related set so that it can then be used in a generic filtering function. To explain with a little more detail here is a simplified example of my use case demonstrating what I'm trying to achieve: models.py from django.db import models class Family(models.Model): family_name = models.CharField(max_length=100) pets: models.Manager['Pet'] = ... members: models.Manager['Person'] = ... def __str__(self): return f'{self.id} - {self.family_name}' class Pet(models.Model): class PetType(models.TextChoices): CAT = 'cat' DOG = 'dog' LIZARD = 'lizard' name = models.CharField(max_length=100) type = models.CharField(max_length=100, choices=PetType) family = models.ForeignKey(Family, on_delete=models.CASCADE, related_name='pets') def __str__(self): return f'{self.id} - {self.name} {self.family.family_name} [{self.type}]' class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() family = models.ForeignKey(Family, on_delete=models.CASCADE, related_name='members') @property def pets(self) -> models.Manager[Pet]: return self.family.pets def __str__(self): return f'{self.id} - {self.name} {self.family.family_name}' If I have a Person entity, I can use it's pets property to get the pets from the family, what I'm looking for is a way to add an alias/annotation/whatever to a queryset of Person so that I can define: def has_a_cat(query_set): return query_set.filter(pets__type='cat') and then be able to use that for both Family and Person query sets. I know I can filter a Person queryset by the pet type … -
Django-filter with django-table
I've been stuck on this problem for a couple of weeks and can't seem to resolve it through self research. Scenario for testing: I have a 4 learners who are registered against different groups. Using tables2 I've created class GroupListView(SingleTableView), selecting the group takes me to class GroupDetailView(SingleTableView, FilterView). This should show a qs of LearnerInstances associated with that learner. However, when applying the f.qs to the learner queryset it shows all 4 learners on the detail page. views.py class GroupDetailView(SingleTableView, FilterView): table_class = LearnerGroupTable model = LearnerInstance template_name = "learner/group_detail.html" filterset_class = LearnerAimFilter # get all learners within the selected group def get_queryset(self): qs = super().get_queryset() qs = qs.filter( learner__group__slug=self.kwargs["slug"], ) return qs # a queryset of learners within the group from model learnerinstance def get_context_data(self, **kwargs): context = super(GroupDetailView, self).get_context_data(**kwargs) learners = self.get_queryset() context["learners_qs"] = learners f = LearnerAimFilter(self.request.GET, queryset=learners) learners = f.qs context["filter"] = f context["table"] = LearnerGroupTable(learners) context["learners"] = learners context["group"] = Group.objects.filter(slug=self.kwargs["slug"]).values() context["group_name"] = Group.objects.filter(slug=self.kwargs["slug"]).values( "short_name" ) return context If I # out the learners = f.qs the detail view shows the correct learner instances but does not filter. As soon as I undo the # it then shows all four learners but the filter … -
How to display users who are only included in the Group in django admin panel
I have an Author simple models in my Django project as below: class Author(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, default=None) def __str__(self): return self.user.username note: CustomUser is django's default User model which I added with a phone number In the Group models (in Django admin panel), I have created 'Author' group, to separate or differentiate ordinary users or authors. I want when I enter a new author name in the Author model, the only names that appear are those that belong to the 'Author' group. -
React Vite: npm run dev and npm run preview work but build shows TypeError on Render platform
I have a Django REST Framework (backend) + Postgresql + Vite React (frontend) Project which is working fine in local when I run the npm run dev command. Here is my package.json file: { "name": "frontend", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "lint": "eslint .", "preview": "vite preview" }, "engines" : { "node" : ">=21.6.2 <22.0.0" }, "dependencies": { "@ant-design/icons": "^5.5.1", "@emotion/react": "^11.13.3", "@emotion/styled": "^11.13.0", "@mui/material": "^6.1.0", "@reduxjs/toolkit": "^2.2.7", "axios": "^1.7.7", "dotenv": "^16.4.7", "leaflet": "^1.9.4", "react": "^18.3.1", "react-dom": "^18.3.1", "react-leaflet": "^4.2.1", "react-paginate": "^8.2.0", "react-redux": "^9.1.2", "react-router-dom": "^6.26.1", "react-router-redux": "^4.0.8", "react-social-icons": "^6.18.0", "redux": "^5.0.1", "styled-components": "^6.1.13" }, "devDependencies": { "@eslint/js": "^9.9.0", "@types/leaflet": "^1.9.16", "@types/react": "^18.3.3", "@types/react-dom": "^18.3.0", "@vitejs/plugin-react": "^4.3.1", "eslint": "^9.9.0", "eslint-plugin-react": "^7.35.0", "eslint-plugin-react-hooks": "^5.1.0-rc.0", "eslint-plugin-react-refresh": "^0.4.9", "globals": "^15.9.0", "vite": "^5.4.14" } } My vite.config.js file below: import { defineConfig, loadEnv } from 'vite' import react from '@vitejs/plugin-react' import dotenv from 'dotenv' dotenv.config() // https://vitejs.dev/config/ export default defineConfig(({ mode }) => { const env = loadEnv(mode, process.cwd()); const isDevelopment = mode === 'development' const baseURL = isDevelopment ? env.VITE_API_BASE_URL_LOCAL : env.VITE_API_BASE_URL_DEPLOY console.log("baseURL") console.log(baseURL) return { plugins: [react()], server: { proxy: { '/api': { target: baseURL, changeOrigin: true, }, }, }, } }) I deployed … -
Why is this image upload test failing?
I am trying to test an ImageField file upload. The test returns AssertionError: 400 != 200, but when I upload the same image manually it works as expected. def test_profile_pic_upload_png(self): self.register_user() self.login_user() with open("./test_files/test.png") as f: response = self.client.post("/upload_profile_pic/", {'profile_pic': f}, **{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}, content_type="multipart") self.assertEqual(response.status_code, 200) The view: @login_required def upload_profile_pic(request): if not request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' or not request.method == "POST": return HttpResponseNotAllowed(["POST"]) if not "profile_pic" in request.FILES: return JsonResponse({ "profile_pic": "No image selected." } , status=400) if not is_valid_image(request.FILES["profile_pic"]): ## Checks the MIME type with `magic` return JsonResponse({ "profile_pic": "Please select a valid image." } , status=400) if request.FILES["profile_pic"].size > 512000: return JsonResponse({ "profile_pic": "Filesize too large." } , status=400) form = UploadProfilePicForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() return JsonResponse({ "success": "Profile picture has been saved." }) else: return JsonResponse(dict(form.errors.items()), status=400) -
AttributeError: 'SimpleLazyObject' object has no attribute 'match'
I have a Django 3.2 application running with gunicorn 23 on Python 3.9. The app is in docker container with all other dependencies installed in virtualenv. I am getting this error: Traceback (most recent call last): File "/app/web/.venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/web/.venv/lib/python3.9/site-packages/sentry_sdk/integrations/django/middleware.py", line 175, in __call__ return f(*args, **kwargs) File "/app/web/.venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 116, in __call__ response = self.process_request(request) File "/app/web/.venv/lib/python3.9/site-packages/django/middleware/locale.py", line 21, in process_request language = translation.get_language_from_request(request, check_path=i18n_patterns_used) File "/app/web/.venv/lib/python3.9/site-packages/django/utils/translation/__init__.py", line 291, in get_language_from_request return _trans.get_language_from_request(request, check_path) File "/app/web/.venv/lib/python3.9/site-packages/django/utils/translation/trans_real.py", line 531, in get_language_from_request lang_code = get_language_from_path(request.path_info) File "/app/web/.venv/lib/python3.9/site-packages/django/utils/translation/trans_real.py", line 510, in get_language_from_path regex_match = language_code_prefix_re.match(path) AttributeError: 'SimpleLazyObject' object has no attribute 'match' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/web/.venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/web/.venv/lib/python3.9/site-packages/sentry_sdk/integrations/django/middleware.py", line 175, in __call__ return f(*args, **kwargs) File "/app/web/.venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 117, in __call__ response = response or self.get_response(request) File "/app/web/.venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner response = response_for_exception(request, exc) File "/app/web/.venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/app/web/.venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 153, in handle_uncaught_exception return callback(request) File "/app/web/.venv/lib/python3.9/site-packages/django/utils/decorators.py", line 126, in _wrapped_view result = middleware.process_view(request, view_func, args, kwargs) File "/app/web/.venv/lib/python3.9/site-packages/django/middleware/csrf.py", line 269, in process_view good_referer = request.get_host() … -
How to paginate ckeditor content in django?
I have ckeditor content as book content. I want to show the content in a fixed width and height container. Instead of scroll. there will be option to navigate pages. Next button and previous button for navigate pages. from django.db import models from django_ckeditor_5.fields import CKEditor5Field class Book(models.Model): title = models.CharField(max_length=255) slug = AutoSlugField(populate_from='title') description = models.TextField() content = CKEditor5Field(config_name="extends") At first I have tried this feature with the default models.TextField(). By counting the words I have splited as pages in javaScript. It was ok but for more text formatting I have to use ckeditor and the ckeditor saves content as html so I can't figure out how I will split the page. Because If I want to split with the previous approch it's possible to miss starting or ending tag in a page. I am using django-ckeditor-5 -
cleaned_data returns old value if submitted field is empty
I'm trying to validate an image upload form. I want to check if the submitted field is empty or not, but when it is, cleaned_data returns the currently stored value. class UploadProfilePicForm(ModelForm): class Meta: model = User fields = ( "profile_pic", ) def clean_profile_pic(self): # if not self.cleaned_data.get("profile_pic"): # self._update_errors(ValidationError({ "profile_pic": "No image selected." })) # The following returns the submitted filename when a file is selected, # but the currently stored filepath/filename when no file is selected: self._update_errors(ValidationError({ "profile_pic": self.cleaned_data.get("profile_pic") })) -
The code works on my network, but not on the university's network
I have a Django server with DRF and custom JWT cookies through middleware. The frontend is built in Next.js and consumes the server routes as an API. Everything works on my machine and network, as well as on some friends' machines who are involved in the project, with the cookies being created and saved correctly. The problem is that this doesn't happen on the university's network, even though it's the same machine (my laptop) and the same browser. At the university, the cookies are not saved, and the error "Cookie 'access_token' has been rejected because it is foreign and does not have the 'Partitioned' attribute" appears. Both codes are on GitHub, and the only thing hosted in the cloud is the database. I am aware of the cookie creation and saving configurations, as well as the CORS policies. I can't figure out where I'm going wrong... Can anyone help me? I can provide the links if possible! Thanks in advance! -
Django testing: find link in email message
I'm trying to test email activation and password reset. How do I filter the email body down to a usable link? def test_activation(self): self.register_user() mail.outbox[0].body.find_the_link() # Find the link here response = self.client.get(link) self.assertEqual(response.status_code, 200) -
Sending data to a form using data from previous GET request
I have a dictionary app where users can view the words (Lemma) filtered by their first letter. I would like for users to be able to then filter those results according to combinations of part of speech (each Lemma has exactly one part of speech) or tags (each Lemma can have 0 to many tags); e.g., select only Lemma that are nouns or verbs or are tagged as agricultural vocabulary. I currently have two forms, one for selecting the first letter and one for selecting the part of speech/tag (the facets). class LemmaInitialLetterForm(forms.Form): LETTERS = [ ... ] initial = forms.ChoiceField( widget=forms.RadioSelect( attrs={"class": "lem_init"} ), choices=LETTERS ) class FacetSideBarForm(forms.Form): poss = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, label='Parts of speech', choices=list() ) tags = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, label='Tags', choices=list() ) def __init__(self, poss=None, tag_list=None, *args, **kwargs): super(FacetSideBarForm, self).__init__(*args, **kwargs) if poss: self.fields['poss'].choices = [ (pos, pos) for pos in poss ] if tag_list: self.fields['tags'].choices = [ (tag, tag) for tag in tag_list ] I've been able to display a list of Lemma filtered by first letter with the following view: class LemmaListView(generic.FormView): template_name = "emedict/lemma_home.html" lemmalist = None def get(self, request, *args, **kwargs): form = LemmaInitialLetterForm(self.request.GET or None) if form.is_valid(): initial = request.GET["initial"] … -
Django Simple JWT + Axios, always getting 401. How can I fix this?
I’m using Nuxt and a pinia store to store the token (the token is present in the store). I've created a plugin for Axios as follows: import axios from "axios"; export default defineNuxtPlugin((NuxtApp) => { axios.defaults.baseURL = "http://127.0.0.1:8000/api/"; axios.defaults.withCredentials = false; axios.defaults.proxyHeaders = false; if (process.client) { let token = window.localStorage.getItem("authTokens"); if (token) { token = JSON.parse(token); console.log(token.access); axios.defaults.headers.common["Authorization"] = `Bearer ${token.access}`; } } return { provide: { axios: axios, }, }; }); The endpoint in Django REST Framework is defined like this: class CreateEvent(CreateAPIView): permission_classes = [IsAuthenticated] serializer_class = CreateEventSerializer def post(self, request, *args, **kwargs): data = request.data.copy() z = request.META.get('HTTP_AUTHORIZATION') data['creator'] = request.user print(request.user, '--------------------') data['types'] = get_type_by_int(request.data.get('type', None)) serializer = self.get_serializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The method I use to call this endpoint is as follows: async sendEvent(): Promise<void> { try { const { $axios } = useNuxtApp(); const response = await $axios.post("event/create/", { latitiude: this.latitiude, longitude: this.longitude, description: this.description, type: this.type, }); console.log("Event sent:", response.data); } catch (error) { console.error("Error while sending event"); } } No matter what I do, I keep receiving a 401 error with the message: Authentication credentials were not provided. However, the z = request.META.get('HTTP_AUTHORIZATION') line contains … -
Importing model classes from other apps in Django with cicular import Problem
Hi i Need to import a model into another app models that will raise the cicular import Error so i use the django.app like this : from django.apps import apps Order = apps.get_model(app_label="orders", model_name='Order') its raise AppRegistryNotReady Error : File "C:\Users\Pourya\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\Pourya\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\core\management\commands\runserver.py", line 126, in inner_run autoreload.raise_last_exception() File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Pourya\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\Pourya\Desktop\fapo\shop\models.py", line 17, in <module> Order = apps.get_model(app_label="orders", model_name='Order') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\apps\registry.py", line 201, in get_model self.check_models_ready() File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\apps\registry.py", line 143, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models …