Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Unit Test Fixtures not loading in VSCode Debug Mode
I have written some unit tests with Django, with fixtures set up. I want to debug these tests and have a configuration on VSCode to do this... { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Django: Test Unit Case", "type": "debugpy", "request": "launch", "args": [ "test", "apps.students", "-v 2" ], "django": true, "autoStartBrowser": false, "program": "${workspaceFolder}\\server\\manage.py" }, ... ] } I have my FIXTURE_DIR configured correctly, as when I run the command py manage.py test apps.students, the fixtures load and give no error. However, when I try to run and debug, I get the following error... Found 6 test(s). Creating test database for alias 'default' ('file:memorydb_default?mode=memory&cache=shared')... Operations to perform: Synchronize unmigrated apps: corsheaders, django_extensions, messages, rest_framework, staticfiles Apply all migrations: admin, auth, ballots, contenttypes, election_count_strategies, polls, programme_groupings, programmes, sessions, students, token_blacklist, users, year_groups Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK ... System check identified no issues (0 silenced). setUpClass (apps.students.tests.YearRepresentiveTestCase) ... ERROR ====================================================================== ERROR: setUpClass (apps.students.tests.YearRepresentiveTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\fiona\AppData\Roaming\Python\Python312\site-packages\django\test\testcases.py", line 1389, … -
Why does django override css variable name from db?
I'm taking over a django+react project from a guy who left the company, but this is the first time I work with django so I'm somewhat clueless. The project is a status management page with calendar and stuff (sqlite3 as db). Possible statuses (like In Office, or Sick Leave) and their corresponding data is stored in db, including color for the status. The color was previously stored as a css hex string without the # (got prepended later by code). But the color values are used at multiple places, so they were copy-pasted many times. Since the colors might change, I wanted to get them all together, so I created css variables like '--in-office-color: rgb(whatever)', and changed db to contain the strings 'var(--in-office-color)' and so instead. Now when I want to return it in a view like this: class SomeView(APIView): def get(self, request): //... data = { /* other profile data here */ "statuses": {i.id: {"name":i.name, "color": i.color} for i in Statuses.objects.all()} } return Response(data) Then in the response some css variables are ok, and some got changed. The two problematic ones are "--in-office-color" which changes to "--in.office-color" and "--home-office-color" also changed to "--home.office-color" (whilst "--out-of-office-color" remains unchanged for example) … -
django category count, print can't filtered
i want to solve django category problem i want print out, counting as category data. for example python (3) html (2) but result python ({{ category.post_set.count }}) html ({{ category.post_set.count }}) how can i solve? i will send my codes # models.py from django.db import models from django.contrib.auth.models import User import os class Category(models.Model): name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=200, unique=True, allow_unicode=True) def __str__(self): return self.name def get_absolute_url(self): return f"/blog/category/{self.slug}/" # admin 단에서의 이름을 설정 class Meta: verbose_name_plural = "categories" class Post(models.Model): title = models.CharField(max_length=30) # 후킹해주는 메세지 100글자 한도로 노출 hook_text = models.CharField(max_length=100, blank=True) content = models.TextField() # auto_now=True를 해주면, 추가로 입력해줄 것 없이, 해당되는 내용이 자동 등록 된다. # settings에 MEDIA_URL, MEDIA_ROOT로 넣어주었던 주소 뒤로 어떻게 해줄지를 말해준다. head_image = models.ImageField(upload_to="blog/images/%Y/%m/%d/", blank=True) file_upload = models.FileField(upload_to="blog/files/%Y/%m/%d/", blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # CASCADE는 연결되어있는 값도 같이 삭제 해준다는 뜻 # SET_NULL은 해당 값을 삭제해도, 해당 pk 값은 공백으로 두되, 나머지 데이터는 살려두는 것 # blank=True를 해줘야 카테고리 미 추가시 오류가 뜨지 않는다. author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL) tags = models.ManyToManyField(Tag, blank=True) # 이걸로써, 관리자 단에서 내용을 보게 되면 작성된 텍스트로 표시된다. def __str__(self): return f"[{self.pk}]{self.title} :: {self.author}" def get_absolute_url(self): return … -
Better Web service framework [closed]
Which is the better framework between Django or Spring Boot in doing API calls especially where we require to convert SOAP request to JSON requests and vice versa. -
Hello sir, I am learning Django. The server was working fine till now but when I created the index.html file in the template, I am facing problem
My django server is not working properly. When I load my website it shows nothing. How can I fix this problem, I checked all my setting and views.py, and urls.py all are ok but when I save all these my server loads but when I go to the website and paste the url.. it shows nothing. I try all the things to fix this error but nothing happens. -
Forbidden (403) CSRF verification failed. Request aborted. while logging in in Label Studio
Once labelstudio is updated to version and run from commandline: LABEL_STUDIO_DISABLE_SIGNUP_WITHOUT_LINK=true CRYPTOGRAPHY_OPENSSL_NO_LEGACY=1 HOST='https://...' nohup label-studio -b --data-dir /label-studio/data/ -db /label-studio/db.sqlite --log-level INFO --internal-host localhost -p 8080 --host https://... --agree-fix-sqlite > label-studio.out 2> label-studio.err & On login attempt it results in an issue: Forbidden (403) CSRF verification failed. Request aborted. The setup is Python 3.11.11 with the following relevant modules: label-studio==1.15.0 label-studio-converter==0.0.59 label-studio-sdk==1.0.8 label-studio-tools==0.0.4 -
What is pytests equivalent to setUpTestData in Django?
I have seen TestCase.setUpTestData which improves test speed quite a bit in my case. I typically prefer pytest fixtures instead of the TestCase classes. However,when I make a session-scope fixture which does data preparation needed for all tests with the fixture, I get RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. I followed https://stackoverflow.com/a/72261942/29412366, but that had no effect. How can I store and re-use a DB state within a Django application when testing using pytest? I use an in-memory sqlite3 DB. I tried https://stackoverflow.com/a/72261942/29412366 : @pytest.mark.django_db @pytest.fixture(scope='session') def thing(django_db_setup, django_db_blocker): del django_db_setup # Cannot be used with usefixtures(..) it won't work with django_db_blocker.unblock(): print('sleeping') Thing.objects.create(thing='hello') and expected the test to run successfully + save time. Instead, I got the RuntimeError mentioned above. (function-scoped fixtures work fine, but then I don't save any test execution time) -
Django NFC Writing Issue on Production - HID Omnikey 5422 - "Service not available" Error
I am developing a Django web application to write to an NFC card using the HID Omnikey 5422 reader. Everything works fine on localhost, but when I deploy it to the production server, I get the following error: Console Error: jquery.min.js:2 POST https://demo.infoidz.com/portal/write-to-nfc/ 500 (Internal Server Error) Django Server Error: Error writing link to NFC card: Failed to establish context: Service not available. (0x8010001D) -
Advice on Choosing a Full Stack Development Stack for a STEM Student
I am a new STEM student with experience in machine learning projects. My academic curriculum now requires me to learn a full stack development stack. I would appreciate your advice on which stack to choose. I have prior knowledge of Python and a basic understanding of HTML, CSS, and JavaScript. Could you please recommend the most widely used stacks in the current industry? Thank you! -
Images not displaying after deploying Django app to Render, but they work locally
I’ve deployed my Django application on Render, and while everything works perfectly locally (including images), the images are not displaying after deployment. The other static files, like CSS and JavaScript, are loading fine, so I believe the issue might be specific to serving media files. Here’s what I’ve checked so far: MEDIA_URL and MEDIA_ROOT: I’ve configured the MEDIA_URL and MEDIA_ROOT in my settings.py as follows: python Copy Edit MEDIA_URL = '/media/' MEDIA_ROOT = '/mnt/data/media' # Path to Render persistent disk Persistent Disk: I’m using Render's persistent disk and confirmed that the images are correctly uploaded to the server. File Permissions: I’ve checked the file permissions, and they seem to be correct. However, despite all this, the images are not showing up on the live site. Can anyone help me figure out why the images aren’t displaying on Render? Do I need to adjust the configuration for serving media files, or is there something I missed in the deployment process? Thanks in advance! I’ve deployed my Django application on Render, and while everything works perfectly locally (including images), the images are not displaying after deployment. The other static files, like CSS and JavaScript, are loading fine, so I believe the issue … -
Is there any way to handle this error I'm facing with my Django project?
Refused to execute script from 'http://127.0.0.1:8000/static/js/register.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. I keep getting this error even thought I have the register.js file at the right place. I expected my javascript codes to function but it doesn't. -
Django imported database -- am I doing it wrong? Is Django not fit to purpose here?
So perhaps I'm missing something conceptually, or simply doing it wrong. Or, worst case scenario, "that's not what Django is for" :-/ I have set up my Django instance to fully take advantage of an external database which contains, amongst other things, all of my iTunes (no, not Music) data, with an extensive changelog. That's tangential to my question but I wanted to throw it out to show that I'm not a complete beginner (I even have it set so Django doesn't mess w/the external read-only database, which is a bit of a feat). What I'm trying to do is import this into Django models in my actual Django database, to take advantage of the Django admin, preparatory to creating a web app around all of this. I've set up the Django models, and created some (SQLAlchemy) routines to ETL my data into three tables (Songs, Artists, Albums). I have a lot of data (783122 songs from 59445 albums by 97562 artists), but that shouldn't overload a robust framework like Django, I wouldn't think. So the data's imported & I've set up a basic admin which should simply show the songs inline when I go to the admin page for … -
how to get django-response on django-request
How to send a django.http.HttpRequest object and receive a django.http.HttpResponse object inside a view? In other words, whats the analogue of python-requests-: response = requests.request(**data) using django.http.HttpRequest and django.http.HttpResponse accordingly -
Error: "405 Client Error: Method Not Allowed" while connecting to IPFS using ipfshttpclient in Django project
I’m working on a Django project where I’m using IPFS to store and retrieve files. However, I’m encountering an issue when trying to use the ipfshttpclient (or ipfsapi) library to connect to the IPFS daemon. When I run the migrate command in my Django project, I get the following error: 405 Client Error: Method Not Allowed for url: http://localhost:5001/api/v0/version?stream-channels=true (env) root@LAPTOP-SEOPFS2E:~/project/EMS/env/project/clgproject# python manage.py migrate /root/project/EMS/env/project/clgproject/EMS/views.py:12: FutureWarning: The `ipfsapi` library is deprecated and will stop receiving updates on the 31.12.2019! If you are on Python 3.5+ please enable and fix all Python deprecation warnings (CPython flag `-Wd`) and switch to the new `ipfshttpclient` library name. Python 2.7 and 3.4 will not be supported by the new library, so please upgrade. import os, requests, ipfsapi , ipfshttpclient #added by DD 'ipfshttpclient' Traceback (most recent call last): File "/root/project/EMS/env/lib/python3.8/site-packages/ipfshttpclient/http.py", line 266, in _do_raise_for_status response.raise_for_status() File "/root/project/EMS/env/lib/python3.8/site-packages/requests/models.py", line 940, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 405 Client Error: Method Not Allowed for url: http://localhost:5001/api/v0/version?stream-channels=true The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/root/project/EMS/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/root/project/EMS/env/lib/python3.8/site-packages/django/core/management/__init__.py", line … -
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 …