Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
COUNT(DISTINCT <col>) without GROUP BY
In Django, Count("col", distinct=True) can be used to perform COUNT(DISTINCT col) but it automatically adds a GROUP BY so is there a way to prevent that from happening so the distinct count of all rows that match the WHERE can be received? -
Why we should install postgresql in the Django container?
Why is necessary install postgresql as dependency in a Django backend container? the Django app is intended to connect to a PostgreSQL DB running in a separate container. I have the next Dockerfile: # pull official base image FROM python:3.12.4-slim-bookworm # set working directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # new # install system dependencies RUN apt-get update \ && apt-get -y install gcc postgresql \ && apt-get clean # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # add app COPY . . And I have the next docker-compose.yml file: services: movies: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8009:8000 env_file: - ./app/.env.dev depends_on: - movies-db movies-db: image: postgres:16 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=movies - POSTGRES_PASSWORD=movies - POSTGRES_DB=movies_dev volumes: postgres_data: This is the case in the course "Test-Driven Development with Django, Django REST Framework, and Docker" by testdriven.io Thanks in advance. -
Better directory structure for Django projects with git perspective
I'm new to Django and trying to decide between two different directory structures. I want to understand the implications of each structure from git perspective and also which one is more favorable in the industry or common practice. Method 1 . ├── .git ├── mysite │ ├── manage.py │ └── mysite │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── README.md Method 2 . ├── .git ├── manage.py ├── mysite │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── README.md created a few projects with both the structures and want to stick to one or atleast have a favourite. -
Incorrect Redirection to Login Page from Profile and Logout Links After User Login
Context: I’m working on a Django project where I have implemented user authentication with profile and logout functionality. The issue I'm encountering is that when I try to access the profile or logout links from the navbar, it redirects me to the login page instead of navigating to the user's profile or performing logout. Profile Link: Should navigate to the user's profile page if the user is logged in. Logout Link: Should log out the user and redirect to the homepage. Current Setup: Templates (base.html): {% if logged_in %} <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> {{ customer_name }} </a> <ul class="dropdown-menu" aria-labelledby="userDropdown"> <li><a class="dropdown-item" href="{% url 'profile' %}?email={{ customer_email }}">Profile</a></li> <li><a class="dropdown-item" href="{% url 'logout' %}">Logout</a></li> </ul> {% else %} <a class="nav-link" href="{% url 'login' %}">Login</a> {% endif %} Views: from django.shortcuts import redirect, render from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import costumer @login_required def profile_view(request): email = request.GET.get('email') if email: try: user = costumer.objects.get(email=email) if user.id == request.session.get('customer_id'): return render(request, 'profile.html', {'user': user}) else: return redirect('index') except costumer.DoesNotExist: return redirect('index') else: return redirect('index') def logout_view(request): request.session.flush() auth_logout(request) return redirect('index') def login_view(request): if request.method … -
How to create a node in neo4j using Django
I am working on a web app. For the backend I chose Django and as a database I would like to use a graph database so I chose neo4j. There is a python library neomodel to work with neo4j and a specific library django_neomodel to incorporate neomodel with Django. I am able to use Django to with neo4j to retrieve data from a node in the database, however I cannot get it to create a node in the database. Here is my a part of my settings.py file: INSTALLED_APPS = [ ... 'django_neomodel', 'neomodel', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt', 'create', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.TokenAuthentication', ], } NEOMODEL_NEO4J_BOLT_URL = 'bolt://neo4j:password@localhost:7687' and here the views.py from create class RegisterView(View): """ This view handles POST requests to create a new user in the database. """ def post(self, request): new_node = myNode(XXX=request.POST['XXX'], YYY=request.POST['YYY'], ZZZ=request.POST['ZZZ']) new_nodesave() Here the myNode class: from neomodel import (StructuredNode, StringProperty, UniqueIdProperty) from .event import Event class myNode(StructuredNode): # Properties uid = UniqueIdProperty() XXX = StringProperty(required=True, unique_index=True) YYY = StringProperty(required=True) ZZZ = StringProperty(required=True) The error I get is: django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I asked chatGPT and … -
Concurrency Control Mechanism For Dataframe Processing In Django WebApp
I have django webapp where processing data directly on pandas dataframe without using django model. now, i want to make this operations concurrency control for multiple processing requests simultaneously. suggest me best approach for it. i am aware about atomic transactions in django but it is not useful for the pandas processing. -
Invalid block tag on line 1: 'include'. Did you forget to register or load this tag?
During a Django tutorial I've got an issue with the index.html file. I can't handle this exception: Invalid block tag on line 14: 'else'. Did you forget to register or load this tag? I really don't understand why it doesn't recognize "include". My index.html is like this: <h1>{{ title }}</h1> {% include 'alphas/includes/nav.html' %} <ul> {% for item in posts %} {% if item.is_published %} <li> <h2>{{ item.title }}</h2> <p>{{ item.content }}</p> <p><a href="{% url 'post' item.id %}">Читать пост</a></p> {% if not forloop.last%} <hr> {% endif %} </li> {% endif %} {% endfor %} </ul> -
Importing rembg in Celery Task breaks workers
I'm trying to use the rembg library in a Celery worker (Django), but once I import the library, the worker is exited prematurely: objc[47160]: +[NSCharacterSet initialize] may have been in progress in another thread when fork() was called. We cannot safely call it or ignore it in the fork() child process. Crashing instead. Set a breakpoint on objc_initializeAfterForkError to debug. [2024-07-24 14:16:14,501: ERROR/MainProcess] Process 'ForkPoolWorker-16' pid:47160 exited with 'signal 6 (SIGABRT)' [2024-07-24 14:16:14,514: ERROR/MainProcess] Message: Error: {'signal': <Signal: task_failure providing_args={'traceback', 'einfo', 'kwargs', 'task_id', 'exception', 'args'}>, 'sender': <@task: assets.tasks.image_background.remove of oml at 0x1046a5c50>, 'task_id': '6219ab75-62b5-4d14-88ac-034d9fa71d45', 'exception': WorkerLostError('Worker exited prematurely: signal 6 (SIGABRT) Job: 15.'), 'args': [], 'kwargs': {}, 'traceback': 'Traceback (most recent call last):\n File "/Users/cesarrodriguez/.pyenv/versions/3.11.2/lib/python3.11/site-packages/billiard/pool.py", line 1264, in mark_as_worker_lost\n raise WorkerLostError(\nbilliard.exceptions.WorkerLostError: Worker exited prematurely: signal 6 (SIGABRT) Job: 15.\n', 'einfo': <ExceptionInfo: ExceptionWithTraceback()>} Data: {} [2024-07-24 14:16:14,514: ERROR/MainProcess] Task handler raised error: WorkerLostError('Worker exited prematurely: signal 6 (SIGABRT) Job: 15.') Traceback (most recent call last): File "/Users/cesarrodriguez/.pyenv/versions/3.11.2/lib/python3.11/site-packages/billiard/pool.py", line 1264, in mark_as_worker_lost I'm not sure if it's something related to multiprocessing Issues, have any thoughts? -
How do I transfer axes to the Django 5 custom admin panel?
I have a django project with two admin panels, one main for filling with models, etc., and the second for blogs (I want to store users, groups and all sorts of logs there) I connected logentry to the custom one, untied everything superfluous to the main one, but axes cannot be transferred how can this be done? -
Implement google login with django
I have a django application in which I want to deploy google login auth. My frontend framework is flutter. After login with flutter in to the google, it sends auth_code received from google to the django backend. This is how I implement my login google_auth_request = HttpRequestManager() class GoogleAuth: def __init__(self, code): self.code = code def get_access_token(self, code: str, redirect_uri: str) -> str: data = { "code": code, "client_id": config.settings.constants.GOOGLE_AUTH_CONFIG["GOOGLE_OAUTH2_CLIENT_ID"], "client_secret": config.settings.constants.GOOGLE_AUTH_CONFIG["GOOGLE_OAUTH2_CLIENT_SECRET"], "redirect_uri": redirect_uri, "grant_type": "authorization_code", } response = google_auth_request.post( config.settings.constants.GOOGLE_AUTH_CONFIG["GOOGLE_ACCESS_TOKEN_OBTAIN_URL"], data=data ) if not response.ok: log.error("Response.json() for get access_token") log.error(response.json()) print(response.json(), flush=True) raise ValidationError("Could not get access token from Google.") access_token = response.json()["access_token"] return access_token def get_user_info(self, access_token: str) -> Dict[str, Any]: response = google_auth_request.get( config.settings.constants.GOOGLE_AUTH_CONFIG["GOOGLE_USER_INFO_URL"], params={"access_token": access_token} ) if not response.ok: log.error(f"google auth response data: {response.data}") print(response.json(), flush=True) raise Exception("google service is unavailable") return response.json() def login(self): domain = config.settings.constants.GOOGLE_AUTH_CONFIG["GOOGLE_OAUTH2_API_URL"] redirect_uri = f"{domain}/api/auth/v1/login/google/" access_token = self.get_access_token(code=self.code, redirect_uri=redirect_uri) user_data = self.get_user_info(access_token) # Creates user in DB if first time login query = EtloUser.objects.filter(email=user_data["email"]) if not query.exists(): EtloUser.objects.create( email=user_data["email"], first_name=user_data.get("given_name"), last_name=user_data.get("family_name"), ) profile_data = { "email": user_data["email"], "first_name": user_data.get("given_name"), "last_name": user_data.get("family_name"), } return profile_data And this is its view @extend_schema(request=GoogleAuthSerializer, responses={200: OutputCredentialSerializer}) class GoogleAuthView(APIView): throttle_scope = "auth" def post(self, request, … -
Django annotation based on Count not working, always return 1
In models.py I have defined: class Order(models.Model): ... class Operation(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="operations") ... I have a queryset of orders where the first order has two operations. orders = order.annotate(mycount=Count('operations')) print(orders[0].operations.count()) print(orders[0].mycount) The previous piece of code returns: 2 1 Hence orders.filter(mycount__gte=2) erroneously returns an empty set. I can see from old posts that this was already a problem in the past, and that it seems like it got fixed as the forum discussions are old (here for example) . -
Can I get the related data directly when using a join query in django?
Well considering two models: class School(models.Model): name = TextField() class Student(models.Model): school = ForeignKey(School related_name=students ) firstname = TextField() And the query: School.objects.filter(Q(name="oldschool") & Q( Q(students__firstname="hello") | Q(students__firstname="testname") )) I retrieve the schools. However there is a join/subquery obviously executed, yet I do not get the student information. I also wish to get the student information for which the "first name is set". Can I make django orm actually fill in a students_set, so I do not have to do multiple lookups later? (having to iterate over the schools and check per school). -
python manage.py runserver No such file or directory
enter image description hereenter image description here I have learned the lesson and applied all the steps, but the page did not appear to me as in the lesson. It is expected that the server should work, but an error is showing. What is the reason? -
what is the default engine value used in django rest framework while using postgres database [closed]
ImproperlyConfigured at /api/token settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Request Method: POST Request URL: http://localhost:8000/api/token Django Version: 5.0.6 Exception Type: ImproperlyConfigured Exception Value: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Exception Location: /home/k/PycharmProjects/ProjectPMS/.venv/lib/python3.10/site-packages/django/db/backends/dummy/base.py, line 20, in complain Raised during: rest_framework_simplejwt.views.TokenObtainPairView Python Executable: /home/k/PycharmProjects/ProjectPMS/.venv/bin/python Python Version: 3.10.12 http://localhost:8000/api/token i am accessing this endpoint inorder to obtain token for authorization in postman -
Django local server deployment on windows
I have a Django project that has to be installed on local servers for multiple customers. I've looked into utilizing Docker, but I can't find any solid information about how to use it on local hosting. My customers use computers running Windows. A friend advised that I utilize a virtual machine to run the Linux Server, then install my project with all dependencies, produce an image of that custom OS, then install it on more virtual computers. The issue that bothers me is consistency in installing and maintaining dependencies. I don't know whether you have any better suggestions. On the subject of virtual machines, my plan was for them to start automatically as soon as the computer turned on and operate the server that would be accessed via the Windows operating system. I'm concerned about whether autotation is possible, whether the server can be accessed by other computers, and whether the client machines are powerful enough to handle the virtualisation. I have installed before, the old school way (straight to the OS), but is a hustle. Im afraid if the server fails, reapeting the whole process of intalling dependences and configurations might take a lot of time while a client … -
Websocket handshake result in 404 not found
All http(s) request are working fine but whenever I try to make a websocket connection it results in the following: Request URL: https://my-domain.com/ws/listen?jwt=<token> Request Method: GET Status Code: 404 Not Found This is my project configuration: nginx upstream geej_app_server { server unix:/webapp/run/gunicorn.sock fail_timeout=0; } server { server_name my-domain.com; access_log /webapp/logs/access.log; error_log /webapp/logs/error.log; location /static/ { alias /webapp/geej_backend/static/; } location /media/ { alias /webapp/geej_backend/media/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass https://geej_app_server; } } location /ws/ { proxy_pass https://geej_app_server; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host $host; } listen 443 ssl http2; listen [::]:443 ssl http2; ssl_certificate /etc/ssl/cert.pem; ssl_certificate_key /etc/ssl/key.pem; ssl_client_certificate /etc/ssl/cloudflare.crt; ssl_verify_client on; } server { listen 80; listen [::]:80; server_name my-domain.com; return 302 https://$server_name$request_uri; } supervisor [program:geej] command = /webapp/env/bin/gunicorn_start user = guser stdout_logfile = /webapp/logs/supervisor.log redirect_stderr = true environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 gunicorn_start (bash file for starting) #!/bin/sh NAME='geej' DJANGODIR=/webapp/geej_backend SOCKFILE=/webapp/run/gunicorn.sock USER=geejuser GROUP=webapp NUM_WORKERS=3 DJANGO_SETTINGS_MODULE=geej.settings DJANGO_ASGI_MODULE=geej.asgi TIMEOUT=120 cd $DJANGODIR source ../env/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mdkir -p $RUNDIR exec ../env/bin/gunicorn -k uvicorn.workers.UvicornWorker ${DJANGO_ASGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --timeout $TIMEOUT \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- routing.py … -
How to Version Control a PostgreSQL Table?
Backend: Python 3.11 and Django 5.0.6 Database: PostgreSQL 15 Our app deals with reporting from the database. We don't store report SQL queries in the codebase; instead, we store them in DB tables. However, developers change SQL queries from time to time. How can we track such changes made in the database, similar to using Git? For example, I want to see the query changes made in the database one year ago. How can I do that? Does anyone have any approach to do this? I tried to set up Liquibase, but it lacks support/documentation for a Python + Django app. Currently, what we are doing is we created a repo for the database, manually generating insert statements from the table and pushing them into the repo. But this is a hectic procedure. Some approaches that may work include using PostgreSQL triggers or logs. There are only some specific static tables that I want to track because some tables have data in the millions. If possible, I need an implementation similar to a version control tool like Git. Does anyone have a better approach to this problem? -
What does __code mean in Django?
What does __code mean in Django? I'm beginner find this code, but I don't now what does name__code mean. def get_queryset(self): names = self.request.query_params.get("name", None) if names: # qs = Hero.objects.filter(name=names) for name in names.split(self.names_separator): qs = Hero.objects.filter(name__code=name) # res = Hero.objects.get(name="Bad") # print(res) return qs I tried to find info in enthernet, but I can't -
Django decorator and middleware issue
My decorator looks like this def require_feature(feature_name): def decorator(view_func): print(f"process_view - view_func: {view_func}") # Debugging @wraps(view_func) def _wrapped_view(request, *args, **kwargs): return view_func(request, *args, **kwargs) _wrapped_view.required_feature = feature_name return _wrapped_view return decorator and the middleware looks like this class EntitlementMiddleware(MiddlewareMixin): def __init__(self, get_response) -> None: self.get_response = get_response def __call__(self, request) -> Any: if request.user.is_authenticated: request.user.features = get_user_features(request.user) else: request.user.features = [] return self.get_response(request) def process_view(self, request, view_func, view_args, view_kwargs): print(f"process_view - view_func: {view_func}") # Debugging required_feature = getattr(view_func, "required_feature", None) if required_feature and not request.user.features.filter(name=required_feature): raise PermissionDenied("You do not have access to this feature") return None # if none is returned then view is called normally def process_response(self, request, response): return response and this is how I am using it in my viewset class MyViewSet(ValidatePkMixin, viewsets.ViewSet): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] queryset = My.objects.all() @method_decorator(require_feature("Basic")) def list(self, request): pass the decorator sets the required_feature when server starts. the middleware gets called when I make a /get call but this required_feature = getattr(view_func, "required_feature", None) returns None what am I missing here? -
Not loading static(CSS,JS,BOOTATRAP) files after applying "Empty Cache and Hard Reload"
I am working on django website,i made some changes in jquery file and then apply "Empty Cache and Hard Reload" in browser ,but now all the static files are not reflecting in browser, before clearing the cache all the files were working properly, What should be the issue here and how can I solve this I am unable to find the issue ,i don't think that the issue with any url, static or location of files as they were working properly before applying "Empty Cache and Hard Reload" ,and the error in console is "404" for all the static files like " GET http://127.0.0.1:8000/static/js/bootstrap.bundle.min.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:19 GET http://127.0.0.1:8000/static/js/jquery-2.0.0.min.js net::ERR_ABORTED 404 (Not Found) " # settings.py DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Category', 'accounts', 'store', 'cart', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',index,name='index'), path('store/',include('store.urls')), path('cart/',include('cart.urls')), path('accounts/',include('accounts.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # base.html {% load static%} <script src="{% static 'js/bootstrap.bundle.min.js' %}" type="text/javascript"></script> <link href="{% static 'css/bootstrap.css' %}" rel="stylesheet" type="text/css"/> <!-- Font awesome 5 --> <link href="{% static 'fonts/fontawesome/css/all.min.css' %}" type="text/css" rel="stylesheet"> -
How to retrieve project directory in MerginMaps?
I intend to develop a Django project by including MerginMaps Python API Client. I need to pull project history by entering project directory as a function parameter. How i can retrieve project destination in Mergin Maps -
How to make Django to increase a field by db value?
For example, I have model: class CacheMetaData(models.Model): count = models.IntegerField(default=0) def inc(self): self.count += 1 self.save() If I define method inc() like above, then Django will execute a SQL statement like: UPDATE the_table set count = 1 where id = 1 This way lead to race condition so that count might not be correctly increased. I want Django to execute: update the_table set count = count + 1 So that count will always be correctly increased. Can Django do that? If yes, how to define the field count? -
Django formset duplication
I have used inline formsets to create a form but for some reason the fields are duplicating and I can't figure out where I have made a mistake- Ignore the bad styling! Here is my CreateView from Views.py class RecipeInline(): form_class = RecipeForm model = Recipe template_name = "recipes/recipe_form.html" def form_valid(self, form): named_formsets = self.get_named_formsets() if not all((x.is_valid() for x in named_formsets.values())): return self.render_to_response(self.get_context_data(form=form)) self.object = form.save() for name, formset in named_formsets.items(): formset_save_func = getattr(self, 'formset_{0}_valid'.format(name), None) if formset_save_func is not None: formset_save_func(formset) else: formset.save() return redirect('recipes-home') def formset_variantingredients_valid(self, formset): variantingredients = formset.save(commit=False) for variantingredient in variantingredients: variantingredient.recipe = self.object variantingredient.save() def formset_images_valid(self, formset): images = formset.save(commit=False) for image in images: image.recipe = self.object image.save() class RecipeCreate(LoginRequiredMixin, RecipeInline, CreateView): def get_context_data(self, **kwargs): ctx = super(RecipeCreate, self).get_context_data(**kwargs) ctx['named_formsets'] = self.get_named_formsets() return ctx def get_named_formsets(self): if self.request.method == "GET": return { 'variantingredients': VariantIngredientFormSet(prefix='variantingredients'), 'images': ImageFormSet(prefix='images'), } else: return { 'variantingredients': VariantIngredientFormSet(self.request.POST or None, self.request.FILES or None, prefix='variantingredients'), 'images': ImageFormSet(self.request.POST or None, self.request.FILES or None, prefix='images'), } class RecipeUpdate(RecipeInline, UpdateView): def get_context_data(self, **kwargs): ctx= super(RecipeUpdate, self).get_context_data(**kwargs) ctx['named_formsets'] = self.get_named_formsets() return ctx def get_named_formsets(self): return { 'variants': VariantIngredientFormSet(self.request.POST or None, self.request.FILES or None, instance=self.object, prefix='variantingredients'), 'images': ImageFormSet(self.request.POST or None, self.request.FILES or None, instance=self.object, prefix='images'), … -
Django serializers unable to serialize a queryset into JSON
Trying simple Django serializer. I use a queryset, with specific values. Then I pass the queryset or the queryset.values() to the serializer. Why doe it give 500 error? @csrf_protect def geoLookup(request, **kwargs): country = kwargs.get('Country') city = kwargs.get('Place') queryset = GeoNames_location.objects.filter(geoCountry_code=country, feature_class='P', geoAsciiName__istartswith=city).values_list("geoAsciiName", "geoLongitude", "geoLatitude", "geo_timezone", "geo_population", "geoCountry_code").order_by('-geo_population')[:5] data = serializers.serialize("json", queryset.values()) # tried queryset and queryset.values() parsed_data = json.loads(data) pretty_json = json.dumps(parsed_data, indent=4) return JsonResponse(json.loads(pretty_json), safe=False) [24/Jul/2024 06:07:52] "GET /edit_chart_form HTTP/1.1" 200 18929 Internal Server Error: /geolookup/US/p Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\decorators.py", line 188, in _view_wrapper result = _process_exception(request, e) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\decorators.py", line 186, in _view_wrapper response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "G:\My Drive\myProgram\runtime\devui\ui\views.py", line 81, in geoLookup data = serializers.serialize("json", queryset.values()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\serializers\__init__.py", line 134, in serialize s.serialize(queryset, **options) File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\serializers\base.py", line 113, in serialize concrete_model = obj._meta.concrete_model ^^^^^^^^^ AttributeError: 'dict' object has no attribute '_meta' [24/Jul/2024 06:07:55] "GET /geolookup/US/p HTTP/1.1" 500 105779 -
Django REST framework serializer.is_valid() saves files to MEDIA_ROOT although .is_valid() is False
I have a project which supports file uploads via Django forms and also Django REST framework, these files are used are stored in a model 'Document'. The issue is that when a file that fails validation is uploaded via the REST framework the file is still saved to its 'upload_to' parameter (MEDIA_ROOT) (No 'Document' model instance is created as expected), this doesn't happen when uploading the same file via Django forms. Some testing seems to point to "serializer.is_valid()" being the thing that saves the file dispite "serializer.is_valid()" is false in the case i am refering to. My ideal outcome is that when a unacceptable file is uploaded via REST framework, that file is not present in the MEDIA_ROOT folder. Please leave a answer/comment if you have any advice. My code is below. Models.py: from django.db import models from apps.common.models import BaseModel from datetime import datetime import os from django.core.exceptions import ValidationError def file_storage_handler() -> str: """This function provides a file path to a Document model's FileField based on the current date. If the file path doesn't exist it creates it.""" currentDate = datetime.now().date() path = f"uploaded_documents/{currentDate.year}/{currentDate.month}/{currentDate.day}/" if not os.path.exists("media/"+path): os.makedirs("media/"+path) return path def validate_file(file): # I dont believe that the …