Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I define multiple URL patterns in Django?
Could anyone tell me how to define multiple URL patterns in Django? On YouTube, I watched a few videos, but they didn't help me and I found a lot fo mistakes in it. Thank you for helping to define multiple URL patterns in Django. -
Create a watch list feature
The user can add that product to the watch list by clicking on the add button, and then the add button will change to Rimo. And this time by clicking this button, the product will be removed from the list. There should be a link on the main page that by clicking on it, all the products in the watch list will be displayed, and by clicking on the detail button, you can see the details of the product, and by clicking on the remove button, you can remove them from the list. models.py class User(AbstractUser): pass class List(models.Model): choice = ( ('d', 'Dark'), ('s', 'Sweet'), ) user = models.CharField(max_length=64) title = models.CharField(max_length=64) description = models.TextField() category = models.CharField(max_length=64) first_bid = models.IntegerField() image = models.ImageField(upload_to="img/", null=True) image_url = models.CharField(max_length=228, default = None, blank = True, null = True) status = models.CharField(max_length=1, choices= choice) active_bool = models.BooleanField(default = True) views.py: def product_detail(request, product_id): product = get_object_or_404(List, pk=product_id) comments = Comment.objects.filter(product=product) if request.method == 'POST': # comment if 'comment' in request.POST: user = request.user if user.is_authenticated: content = request.POST.get('content') comment = Comment(product=product, user=user, content=content) comment.save() context = { 'product': product, 'comments': comments, } return render(request, 'auctions/product_detail.html', context) from .forms import AddWatchlist def … -
Retrieving files using django rest Framework and postman
I am making a secure file storage system In this for the decryption process user is giving the file_id and key as an input. The program finds the file, reads it's data and decrypts it using the key and rewrites the file data of the file with the new encrypted data and return the file. I'm using django rest framework for this. The code for the view is given below: class Decryption(APIView): def post(self, request, *args, **kwargs): file_id = request.data.get('file_id') key = request.data.get('key') try: if not key: return Response({"error": "Key is required"}, status= status.HTTP_400_BAD_REQUEST) try: encrypted_file = EncryptedFile.objects.get(id = file_id) except EncryptedFile.DoesNotExist: return Response({'detail': "The requested File doesn't exist"}, status= status.HTTP_404_NOT_FOUND) encrypted_data = encrypted_file.file.read() cipher = Fernet(key) decrypted_data = cipher.decrypt(encrypted_data) encrypted_file.file.seek(0) #encrypted_file.file.write(decrypted_data) response = Response() response['Content-Disposition'] = f'attachment: filename = {encrypted_file.file_name}' response.write(decrypted_data) return response except Exception as e: return Response({'details': e}, status= status.HTTP_400_BAD_REQUEST) I was expecting a file as a result. But I got a blank screen when I made an API call using postman -
Failed authentication for Google Sheet and Django running in Apache server
I'm implementing a Django application that uses a Google Sheet as database, and is hosted with Apache in a Rocky Linux server. To test the integration between Django and Google Sheet, I have followed Tom Dekan Tutorial. And to configure the Django application to run with Apache, I have followed the official Django Tutorial. However, when I try to access the page, I receive an Internal Server Error. Checking the error logs, I receive the following message: [Thu Nov 16 11:44:34.203173 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] mod_wsgi (pid=150297): Failed to exec Python script file '/opt/dashbea/TesteGSheet/core/core/wsgi.py'. [Thu Nov 16 11:44:34.203297 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] mod_wsgi (pid=150297): Exception occurred processing WSGI script '/opt/dashbea/TesteGSheet/core/core/wsgi.py'. [Thu Nov 16 11:44:34.203791 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] Traceback (most recent call last): [Thu Nov 16 11:44:34.203866 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] File "/opt/dashbea/TesteGSheet/core/core/wsgi.py", line 22, in <module> [Thu Nov 16 11:44:34.203876 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] application = get_wsgi_application() [Thu Nov 16 11:44:34.203885 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] File "/opt/dashbea/TesteGSheet/my_env/lib64/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Thu Nov 16 11:44:34.203893 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] django.setup(set_prefix=False) [Thu Nov 16 11:44:34.203902 2023] [wsgi:error] [pid 150297:tid … -
Pytest and Selenium in Docker : wrong database used for the test suite?
I'm struggling to setup my test runner for a new Django project. I want to use these libraries : Django 4.2 pytest-django 4.6.0 pytest-splinter 3.3.2 And I want it to work with Docker. I got a head start with that answer : https://stackoverflow.com/a/58447497/3219759 but I can't make it work. Here is my docker-compose.yml : version: '3.3' services: web: build: jam restart: always command: python manage.py runserver 0.0.0.0:8000 environment: - USE_DOCKER=True env_file: - .env ports: - "127.0.0.1:8000:8000" volumes: - .:/code links: - db depends_on: - db - selenium db: image: postgres environment: - POSTGRES_USER=xxx - POSTGRES_PASSWORD=xxx - POSTGRES_DB=xxx ports: - "127.0.0.1:5432:5432" volumes: - pg_data:/var/lib/postgresql/data selenium: image: selenium/standalone-firefox:4.9.1 ports: - "4444:4444" # Selenium - "5900:5900" # VNC volumes: pg_data: And to finish the setup, I have these fixtures in the conftest.py file : @pytest.fixture(scope='session') def test_server() -> LiveServer: addr = socket.gethostbyname(socket.gethostname()) server = LiveServer(addr) yield server server.stop() @pytest.fixture(scope='session') def splinter_webdriver(): return 'remote' @pytest.fixture(scope='session') def splinter_remote_url(): return 'http://selenium:4444/wd/hub' and this in settings.py: if env('USE_DOCKER') == 'yes': import socket ALLOWED_HOSTS = [socket.gethostbyname(socket.gethostname())] I have a basic view that list all the profiles, and a template to match. This feature is working on my local server. The corresponding test: @pytest.mark.django_db class TestIndexPage: def test_profile_list(self, browser, … -
Email simulation with Django
This project should be able to simulate email. The program runs successfully and I can write the email, but the email is not sent and it gives this error. what is the problem؟ in terminal: [16/Nov/2023 17:35:46] "GET /emails/inbox HTTP/1.1" 200 2 in console: MLFormElement. (inbox.js:10:7) code: document.addEventListener( "DOMContentLoaded",function () { const form = document.querySelector("#compose-form"); const msg = document.querySelector("#message"); form.addEventListener("submit", (event) => { event.preventDefault(); to = document.querySelector("#compose-recipients"); subject = document.querySelector("#compose-subject"); body = document.querySelector("#compose-body"); if (from.length == 0 && to.length == 1000) return; fetch("/emails", { method: "POST", body: JSON.stringify({ recipients: to.value, subject: subject.value, body: body.value, }), }) .then((response) => response.json()) .then((result) => { console.log(result.status); if (result.status == 201) { load_mailbox("sent"); } else { msg.innerHTML = `<div class="alert alert-danger" role="alert"> ${result.error} </div>`; } }); }); }, false ); -
How do I change the default buttons in django?
In django admin, models have default buttons, how can I change the name of these buttons? enter image description here -
how to create djagno notification system like instagram?
I am creating APIs for an Instagram-like application using Django (Celery). I have implemented a notification system for whenever a like is performed on a post, but I want notification aggregation similar to Instagram ('user1 and 23 others liked your post'). I tried to create it, but I couldn't wrap my head around it. -
Load variables from a virtual env for a cron task on Azure web app server
I have a python (Django) web app running on Azure App Service. Despite everything I tried from other SO threads, I can't figure out how to have the environment variables accessed from my cron tasks. It may be caused by how Azure duplicates the venv into a weird antenv. More on that later. What I really want is to use Django commands in cron, like ./manage.py some_command. However, I quickly realized that the Django virtual env is not loaded properly in cron. So I decided to go step by step and see how to access the virtual env from cron. What I have tried Initial implementation I am testing my setup using Azure App Service SSH console available at https://{my-app-name}.scm.azurewebsites.net/webssh/host. Script I created a script /home/scripts/log-env.sh to test the water: #!/bin/bash trace=/home/scripts/trace path=$(...) # Some command that locates the venv directory echo "src path: ${path}" > ${trace} # I can see ${path} is set correctly echo "MY_VAR before source: [${MY_VAR}]" >> ${trace} source ${path}/antenv/bin/activate; echo "MY_VAR same command line as source: [${MY_VAR}]" >> ${trace} echo "MY_VAR after source: [${MY_VAR}]" >> ${trace} Output When I run the script in the terminal, it shows that I don't even need to source the … -
How to split development env file and production env file with docker compose?
I have dockerized django application with nginx. And I have two env files: one for development and one for production. The contents of the env files are the credentials of the database. But apparently, the credentials that are inside the prodduction env file are not executed. My folder structure looks like this: root - welzijn -admin So when I put the env files with names: .env and prod.env in the root folder, it doesn't work. But when I put the .env file with the credentials of production in the welzijn folder it works. And even when I put the file prod.env in the folder welzijn it also doesn't work I really scratch my head over this. So this is the dockerfile: # pull official base image FROM python:3.9-alpine3.13 # ENV PATH="/scripts:${PATH}" # set work directory # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./scripts /scripts WORKDIR /usr/src/app EXPOSE 8000 # install psycopg2 dependencies ARG DEV=false RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache postgresql-client jpeg-dev && \ apk add --update --no-cache --virtual .tmp-build-deps \ build-base postgresql-dev musl-dev zlib zlib-dev linux-headers && \ /py/bin/pip install -r … -
OperationalError: (1317, 'Query execution was interrupted') during migration
I'm encountering a problem with Django migrations, specifically encountering an OperationalError (1317, 'Query execution was interrupted') during the migration process. This issue arises when executing the python manage.py migrate command. It's worth noting that this problem doesn't occur locally; rather, it's specific to the production environment during migration. The process seems to get stuck at the migration for approximately 1 minute before ultimately raising the error outlined below. Applying accounts.0049_userprofile_description... Traceback (most recent call last): File "/home/ubuntu/venv/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ubuntu/venv/lib/python3.11/site-packages/django/db/backends/mysql/base.py", line 75, in execute return self.cursor.execute(query, args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ubuntu/venv/lib/python3.11/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) ^^^^^^^^^^^^^^^^^^ File "/home/ubuntu/venv/lib/python3.11/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/home/ubuntu/venv/lib/python3.11/site-packages/MySQLdb/connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb.OperationalError: (1317, 'Query execution was interrupted') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/ubuntu/****/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/ubuntu/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/venv/lib/python3.11/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/venv/lib/python3.11/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ubuntu/venv/lib/python3.11/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ubuntu/venv/lib/python3.11/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state … -
Can I force Django to load images with space in the filename?
I have a folder with image files. Unfortunately, some files contain a space in their name. Django is able to load these images if I run the app on the development server (via python manage.py runserver) but not if I run it in production. The reason is that Django converts " " to "%20". For example, if my folder contains the following files: image1.png image2 test.png image3%20test.png (just to understand what is happening) ... then this code will have the following result: # In settings.py MEDIA_URL = '/media/' MEDIA_ROOT = ('D:/Data/Images') # In the HTML template <img src="/media/image1.png"/> # image loads on the development and production server <img src="/media/image2 test.png"/> # image loads only on the development server <img src="/media/image3 test.png"/> # image loads only on the production server I could of course rename all image filenames that contain space characters by replacing the spaces with underscores. But that's a bit awkward as a chemical analysis system is constantly feeding new image files to the folder and the system's software will occasionally introduce spaces in the filenames. I do not have control over this. So is there a way to force Django to load images even if they contain space … -
Django update method for incrementing is super slow
I have a model using json fields, while this works like a charm 99% of times I now have a kinda annoying issue, execution time. I need to increment a LOT of records using Django's ORM update method, I don't know how fast it should be if the db was using something else than json fields, but basically here's some examples of time I'm facing: 4000 records update for just a +1 in a json field took 20 seconds 6000 records update took almost 2 minutes Those were small ones, I expect some update to have more than 100000 records, could even reach a million. For the technical side of what I am exactly doing: I use filter on a range inside the jsonfield values to extract records that requires an update, this runs perfectly fine, after getting the queryset I use update to increment one of the jsonfield value by 1. This behavior is very specific and probably not the most optimal but this is what I have for now, to do it I make a raw sql query using RawSQL, for reference here is the function that generate the said query: def jsonfield_increment(field_name: str, key: str, increment_by: int … -
How to find out the Python representation of Django fields?
For example I have this code: class SomeModel(models.Model): instance_name = models.UnknownField(max_length=255) instance_id = models.IntegerField() I want to have the model name (SomeModel) and field name (for ex. instance_name) as an input, and the, and the output will be the python representation of that field (for ex.: srt, int, float...) So it will be something like this: def find_out_the_field_python_type(model: Model, field_name: str) -> type: # For example model = SomeModel, field_name = instance_id # return int return I have tried this: instance_id_field = SomeModel._meta.get_field('instance_id') # Determine the Python representation of the field python_representation = instance_id_field.get_internal_type() print(python_representation) # returns 'IntegerField' But the problem that it returns not the python representation, but the type of Django field. -
How to get unique data for each column from the database in one query (Django ORM)?
I need to get UNIQUE data from EACH column I have a list of fields: MY_FIELDS = ['id', 'created', 'And_more_28'] My HORRIBLY INEFFECTIVE code that produces the correct result qs = Sheets.objects.all() v = [] v += [list(qs.values(v).distinct()) for v in MY_FIELDS] I get what I need.... But at what cost? (28 requests is painful) Tell me how to make one query out of this.... This is how it produces non-unique data for EACH column (tried it) qs = Sheets.objects.all().values(*MY_FIELDS).distinct() -
Increasing span limits in Sentry python
I tried to increase the limit of span by setting up _experiments: {"max_spans": 5000} in the sentry_sdk.init() but the trace doesn't appear on the sentry server if i try to capture a small trace it works. Any ideas if there is any limit enforced on server side too? -
show two different models as the foreign key
There's two models Groups and Sub_groups. How can I show both models in particulars field as foreign key? models.py class Groups(models.Model): name = models.CharField(max_length=255) under = models.CharField(max_length=255) def __str__(self): return self.name class Sub_groups(models.Model): name = models.CharField(max_length=255) under = models.ForeignKey(Groups, on_delete=models.CASCADE, null=True, blank=True, related_name='sub_groups') def __str__(self): return self.name class Voucher(models.Model): particulars = models.ForeignKey(Groups, on_delete=models.CASCADE, null=True, blank=True, related_name='vouchers') #how to add both groups and sub_groups data in particulars here? What I have done so far: forms.py class PaymentVoucherForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PaymentVoucherForm, self).__init__(*args, **kwargs) # Populate the choices for the 'particulars' field with both groups and subgroups group_choices = [("g_" + str(group.id), group.name) for group in Groups.objects.all()] subgroup_choices = [("sg_" + str(subgroup.id), subgroup.name) for subgroup in Sub_groups.objects.all()] # Concatenate the group and subgroup choices all_choices = group_choices + subgroup_choices # Set the choices for the 'particulars' field self.fields['particulars'].choices = all_choices class Meta: model = Voucher fields = ['particulars',] template: <form method="POST"> {% csrf_token %} {{form|crispy}} <input class="btn btn-info btn-block" type="submit" value="Submit"> </form> It gives following error: Select a valid choice. That choice is not one of the available choices. P.S g_ and sg_ are added to the ids of groups and sub_groups respectively since both the models has same ids like … -
Django Throws 302 error when I call API written on Questions app and redirects to /login/?next=/api/questions/tags-list/
I have written an API URL on questions model for retrieving a 1st 10 tags, its a get call. When I call it from the react app, i am getting 302 to that api and redirects to http://localhost:8093/login/?next=/api/questions/tags-list/ with 200 responses as html code for django admin pannel login. I have not implemented the authentication and it's not required. Django - 4.2.7 I tried working on adding middlewares for the restframework and is still having the same issue The below shown is the base app urls, urlpatterns = [ path('jet/', include('jet.urls', 'jet')), path('', admin.site.urls), path(r'/api/questions/', include('question.urls')), path(r'user_auth/', include('user_auth.urls')) ] The questions urls is as follows: urlpatterns = [ path('/tags-list/', TagsView.as_view(), name='tags-list' ), path('match-tags/', MatchTags.as_view(), name='matching-tags'), path('presigned-urls/', PresignedURL.as_view(), name='presigned_url'), path('question-submission/', QuestionSubmission.as_view(), name='question-submission') ] this is the view called. class TagsView(APIView): def get(self,request): print("HI", flush=True) tags = Tag.objects.all()[:10] # Get first 10 tags serializer = TagSerializer(tags, many=True) return Response(serializer.data) on settings.py INSTALLED_APPS = [ 'jet', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'user_auth', 'corsheaders', 'question', 'storages', 's3direct', 'file' ] AUTH_USER_MODEL = 'user_auth.User' SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=1000), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1000), 'AUTH_USER_MODEL': 'user_auth.User' } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
DRF requires the user to be logged in to use login_user api
I am trying to create a CustomUserViewset, and add a login_user api to it. The problem is that although I set the permission_classes to AllowAny, still when calling the login_user api, it says: {"detail":"Please login to perform this action"}. Here is my API: class CustomUserViewset(AutoPermissionViewSetMixin, viewsets.ModelViewSet): queryset = User.objects.none() serializer_class = CustomUserSerializer permission_type_map = { "create": "add", "destroy": "delete", "partial_update": "change", "retrieve": "view", "update": "change", "register": "view", "login_user": "view", "logout": "change", } @decorators.action(methods=["POST"], detail=False, permission_classes=[permissions.AllowAny]) def login_user(self, request): serializer = LoginSerializer(data=request.data) if not serializer.is_valid(): raise exceptions.ValidationError({"detail": "Invalid username or password"}) username = serializer.validated_data["username"] password = serializer.validated_data["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return Response(CustomUserSerializer(user).data, status=status.HTTP_200_OK) else: raise exceptions.AuthenticationFailed({"detail": "Invalid username or password"}) As you see, I have permission_classes=[permissions.AllowAny] in the api action. Also, giving this permission class in the action was the last thing I tried, before that, I tried to adjust the permission in rules.py: import typing import rules if typing.TYPE_CHECKING: from .models import User rules.add_perm("accounts.login_user", rules.predicates.always_allow) None of the above methods has worked, and I still get the same message that I need to log in to perform this action. -
AttributeError : 'NoneType' object has no attribute 'lower'
I installed django-comments-dab package and i have done steps like documents but recived this error: AttributeError: 'NoneType' object has no attribute 'lower' how can i fix it? def get_model_obj(app_name, model_name, model_id): content_type = ContentType.objects.get(app_label=app_name, model=model_name.lower('')) model_object = content_type.get_object_for_this_type(id=model_id) return model_object -
My Django endpoint does not access the has_object_permission method
Here's a view class that I have: from rest_framework.views import APIView class MyView(APIView): permission_classes = [CustomAccessPermission] def get(self, request, id: int) -> Response: object = get_object_or_404(MyObjectClass, id) serializer = MySerializer(object) return Response(serializer.data) def delete(self, request, id: int): object = get_object_or_404(MyObjectClass, id) object.status = MyObjectClass.Status.DELETED object.save() return Response(status=status.HTTP_200_OK, data=id) Here's my custom access permission class: from rest_framework import permissions from django.core.exceptions import PermissionDenied class CustomAccessPermission(permissions.BasePermission): message = "You cannot access objects created by other users." def has_object_permission(self, request, view, obj): if obj.user_id != request.user.id: raise PermissionDenied(self.message) return True So within my objects I store user_id that contains IDs of users that created this object. I want to check if the id from request is equal to that user_id to undestand if user can see this object. So, for example, when I run GET:http://localhost:8050/api/objects/4 i want to take the user_id of object with id=4 and if it's equal to request.user.id then we'll allow the user to see it, otherwise we should deny. The same with DELETE requests, they should be first checked against the user_id of object. This code above doesn't work, it doesn't access the has_object_permission() method in my permission class. What should I modify? -
removing trailing slashes from django multi language url pattern (i18n_patterns)
I'm trying to get rid of trailing slash from urls. Currently the web-server successfully removes slashes and APPEND_SLASH = false Everything works fine but I have a problem with the localized homepage: http://example.com/en/ - ok http://example.com/en - Page not found (404) I add this class to Middleware: from django.shortcuts import redirect from django.utils import translation class RemoveTrailingSlashFromMultilingualURLsMiddleware: def init(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) # Check if the URL ends with a language code and a slash language_code = translation.get_language() if request.path.endswith(f'/{language_code}/') and request.path != f'/{language_code}/': new_path = request.path.rstrip('/') return redirect(new_path) and add MIDDLEWARE to setting: MIDDLEWARE = [ # ... other middleware 'blog.middleware.RemoveTrailingSlashFromMultilingualURLsMiddleware', # ... other middleware ] But it doesn't work and keeps giving 404 not found error if possible help me to solve my problem thanks a lot -
Django+Cython Deployment with Gunicorn
I have a Django application and I don't want to provide access my source code. As a result of my research, I used the Djcompiler library, which basically uses Cython. As a result, I converted the project into .so modules. When I run this converted project with the python3 manage.py runserver command, the project runs smoothly. However, when I run the project for production via Gunicorn with the gunicorn tracking.wsgi.python-39-darwin:application --bind0.0.0.0:7005command, I get the following errors. ModuleNotFoundError: No module named 'accounts.urls' ModuleNotFoundError: No module named 'log.models' How can I successfully implement this Cython converted project to .so modules with Gunicorn? -
How to test nested Serializers in Django Rest?
I have a ToDo App Django project, and so there are Task and TaskList models which are linked with a ManyToMany relation. Inside my TaskSerializer, I have defined a nested TaskListSerializer which handles the reverse relation of a task's tasklists. Everything is going well in real world, and the serialization and deserialization is ok. This is what you should put request when updating a task (as json): { "title": "hello", "tasklists": [ {"pk": "b84d3375-0e09-4dd1-9809-f92d29d6aa36"}, {"pk": "b84d3375-0e09-4dd1-9809-f92d29d6aa36"} ] } But inside the Tests, I want to test this serializer and, when I'm sending the put request the tasklists field is not sent to the view! This is the test request: path = self.task.get_absolute_api_url() data = { "title": "hello", "tasklists": [ {"pk": "b84d3375-0e09-4dd1-9809-f92d29d6aa36"}, {"pk": "b84d3375-0e09-4dd1-9809-f92d29d6aa36"} ] } self.client.put(path, data) But there is no tasklists field inside the validated_data and initial_data of view.(the title field is sent and validated) I guess that the Renderer and json_encoder have the problem with this type of data. so how should the correct request data be inside a nested serializer test? In General, How to test a Nested Serializer! -
How to handle forward slash in API call
I know this goes against all of the rules, but I have a database that has a primary key in the format of /. Ex. 12345/A. I'm using Django Rest Framework and can't seem to make the API call to retrieve this record. The Django admin changes this to 12345_2FA in the URL, but this doesn't work for the API call. Thanks!