Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dont know, why the my app url is ashowing as undefined, inside include function of project url
File structure of my project and app django All the steps needed to make a virtual environment.Then make a project ,and a app,then write a view function inside the aap level.Then map it with urls inside app. Finally when going to project,s url.py and map the app's url with include function.It is not working.(Showing as undefined). I really stucked into it since two day.If someone could help me,it would be very good, -
Autofill Timestamps in Django Model
I want to create two fields for creating an object in Django models. The first field is required and will use the built in DateTimeField. Second field will take on the same data as in the first field, furthermore it should be possible to update the date without changing the data in the first field. This is my class: class MyClass(models.Model): ... created_at = models.DateTimeField(null=True) updated_at = models.DateTimeField(null=True) # this field should take data ... I looked for built-in Models which fulfill my requirements, but couldn't find the right one. This class with auto_now_add won't show me any field. class MyClass(models.Model): ... created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) ... -
Can't wire up URLs, giving a 404 message despite path I choose
I get a 404 message telling me "The current path, contact/, matched the last one." 404 image I have tried multiple different path on both url.py files and nothing seems to work.enter image description here url views Path I have is below: [[webpage layout](https://i.stack.imgur.com/UJxHO.png)](https://i.stack.imgur.com/h01z3.png) I was hoping to get the link from my 'base.html' to link to this app and load in the page.base site html -
Celery task sent with channel_layer.group_send is not received by websocket Consumer
This is a Django Channels project, using celery beat I update periodically datas and send it to the Front using channels (Redis) and Websocket. Datas are properly generated during in task side but never received in Consumers side. Logs seems silents to me. Note : Reverse process show no trouble : I successfuly get datas from Consumer to Celery worker's task. requirements.txt celery==5.2.7 channels==4.0.0 Django==4.1.7 redis==4.5.4 daphne==3.0.2 psycopg2-binary==2.9.6 channels-redis==4.1.0 djangorestframework==3.14.0 markdown==3.4.3 django-filter==23.2 whitenoise==6.4.0 task.py from celery import shared_task from celery.utils.log import get_task_logger from channels.layers import get_channel_layer from asgiref.sync import async_to_sync log = get_task_logger(__name__) @shared_task def periodic_update(): channel_layer = get_channel_layer() \# Get the channel layer data = {'message': 'test'} # Send a group message async_to_sync(channel_layer.group_send)( "group_potos", { 'type': 'senddata', 'message': data } ) print('[CELERY WORKER TASK] message sent to group') @shared_task def handle_player_input(message): log.info('\[CELERY WORKER TASK\] message from player ...: {}'.format(message)) \# Treat player input.... consumers.py import logging from channels.generic.websocket import AsyncWebsocketConsumer from .tasks import handle_player_input log = logging.getLogger(__name__) class GameConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = "potos" self.room_group_name = "group_potos" # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard(self.room_group_name , self.channel_name) # Receive message from WebSocket async def receive(self, … -
How to filter fields in the default form of the Django Rest Framework API?
I need to show the results (options) of a SELECT input according to what was selected in another input select. In this print case, for example, I need only the X capacitors that are registered with the foreign key of the Unit to appear. Example form image This form is the default of the Django Rest Framework API, and I would like to use it if possible. -
Pass a variable from views.py to .html
I have a table which can store comment ratings. I'm trying to calculate the average of comment ratings and print it in my store.html file. But {{ average }} doesn't return any value. What i've tried, models.py class MyComments(models.Model): TRUE = 'True' FALSE = 'False' STATUS_CHOICES = ( (TRUE, 'yes'), (FALSE, 'no'), ) user = models.ForeignKey(User, related_name='comments', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='comments',on_delete=models.CASCADE) subject = models.CharField(max_length=50,blank=True) comment = models.TextField(max_length=200,blank=True) rate = models.IntegerField(blank=True) status = models.CharField(max_length=10,choices=STATUS_CHOICES,default=TRUE) def __str__(self): return self.subject views.py def average_of_rates(request, product_id): comments = MyComments.objects.filter(product_id=product_id,status=MyComments.TRUE) rates = 0 amount = 0 for comment in comments: rates += comment.rate amount+=1 average = rates/amount return render(request,'store/store.html',{ 'average': average, }) urls.py path('comments/<int:product_id>/', views.average_of_rates, name='average_of_rates'), store.html <p class = "font-extrabold text-lg"> {{ average }}</p> I'm new to django btw. What's the mistake that i am doing here? Thanks in advance. -
Restart Django database connection after updating database settings in tests
In my Django settings, I have a setting called POSTGRES_STATEMENT_TIMEOUT that allows me to configure a statement timeout. I'm setting the deafault to 30 seconds. Note, I'm django-environ. # settings.py env = environ.Env( POSTGRES_STATEMENT_TIMEOUT=(str, "30s"), ) POSTGRES_STATEMENT_TIMEOUT = env("POSTGRES_STATEMENT_TIMEOUT") DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", ... "OPTIONS": { "options": f"-c statement_timeout={POSTGRES_STATEMENT_TIMEOUT}s" }, } } I want to write a simple test to ensure the postgres statement timeout setting works properly. Note I'm using pytest-django. # tests.py def test_statement_timeout(settings): # Lower statement timeout so this test doesn't take 30s to run. settings.POSTGRES_STATEMENT_TIMEOUT = "1s" with connection.cursor() as cursor: with pytest.raises(OperationalError) as exc: cursor.execute("select pg_sleep(2)") assert "canceling statement due to statement timeout" in str(exc.value) This is test is failing. When I print settings.DATABASES I see the statement timeout is still 30 second, not 1 second. Even if I override settings.DATABASES directly via settings.DATABASES["default"]["OPTIONS"] = {"options": "-c statement_timeout=1s"}, the test still fails. I think I need to restart the database connection after updating the settings. Is there anyway to do this in the tests? -
DRF asgi request don't have request.data
class HelloWorldView(APIView): def post(self, request): print("request body....", request._request.body) print(f"drf data {request.data}") print("inside request type...", type(request._request)) return HttpResponse("Hello world") output request body.... b'{"test": "body here"}' drf data {} inside request type... <class 'django.core.handlers.asgi.ASGIRequest'> Issue When i deploy application with asgi on server request.data is empty for post requests. It works fine in my local. The difference here noticed is that in local request._request is WSGIRequest while in server it is ASGIRequest. somehow DRF not able to convert the ASGIRequest's post data to request.data. can somebody help me to fix this issue ? -
Celery task unable to find time.sleep()
I have a strange issue with celery tasks. The task itself is a simple test task that calls sleep in a loop thus: @shared_task() def testtask(num=100): for i in range(num): import time print_log("in testtask {0}".format(i)) time.sleep(1) return Calling testtask(x) from the python IDE works just fine. I have imported all the relevant celery app stuff before this. Calling testtask.delay(x) causes the task to get queued, but fails with the following error: [2023-05-15 16:36:39,168: ERROR/ForkPoolWorker-2] Task profiles.views.testtask[8beca657-e492-4526-9aac-ddba42eae653] raised unexpected: NameError("name 'sleep' is not defined",) Traceback (most recent call last): File "/home/raxak/raxak/lib64/python3.6/site-packages/celery/app/trace.py", line 450, in trace_task R = retval = fun(*args, **kwargs) File "/home/raxak/raxak/lib64/python3.6/site-packages/celery/app/trace.py", line 731, in __protected_call__ return self.run(*args, **kwargs) File "/u01/rp/raxak/profiles/views.py", line 1498, in testtask print_log("in testtask {0}".format(i)) NameError: name 'sleep' is not defined Error comes no matter where I put the import time line: at the start of the file, in the loop, just after the def testtask etc. Also strange that the error is flagged as being on the print_log line which is before the one that is invoking sleep. Must me something so obvious that I am missing it somehow. It does not matter if I import time and do time.sleep(1), or if I do from time … -
How to slugify on get_root() function of django-mptt on overriding save method
I have a models.py class Category(MPTTModel): name = models.CharField(max_length = 255, null = False, blank = False) parent = TreeForeignKey('self', on_delete = models.CASCADE, blank = False, null = True, related_name = 'children') def save(self, *args, **kwargs): if self.parent: self.slug = slugify("%s %s" % (self.get_root(), self.name)) else: self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) I'm trying to slugify the root and name fields here. Since the instance is not saved, i get this error ValueError: Cannot call get_root on unsaved Category instances. I think i can save the instance first and then do the slugifying logic but that would result in hitting db multiple times. Is there any way i can slugify this effectively ? -
how to regain access to the website I have created using Django?
I did 'python manage.py runserver' and the website was created and it was all fine until I decided to get some sleep so obviously I closed the laptop and everything. Next day comes and I don't know to get back to that website. I tried 'python manage.py runserver' because I figured that's how I get back to the website but all it showed was a bunch of files and an error message. I tried typing in the address of the website in google but it says it refuses to connect. I have tried creating a new project to create a new website but it didn't work either. Please help, I've been stuck in this for 2 days the start the end -
Django 2.2.6 use SSO and Local logins gets me a CSRF error
In Django 2.2.6, I would like to use SSO logins (default) and local logins. My urls look like so ... from django.contrib.auth import views as auth_views from .core import sso urlpatterns += [ url(r"^login/$", sso.ssologin, name="ssologin"), re_path(r"^ssoauth/.*$", sso.ssoauth, name="ssoauth"), url(r"^accounts/login/$", auth_views.LoginView.as_view(), name="login"), url(r"^accounts/logout/$", auth_views.LogoutView.as_view(), name="logout"), ] the only backend I have configured is ... AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", ] the SSO login works great using requests-oauthlib, the local login gives me ... CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests. ... after logging in I'm not using any templates, only views. How can I debug this ? -
Configure settings.py to return an html page on error
I would like to ask for help configuring Django's settings.py if there is a way to configure it to return an html page in case of any error, be it sending data or even misconfiguring views. My goal is to make it return a custom page in case of error and not the default Django error page enter image description here -
How to enable tagging in the default autocomplete fields of the Django admin?
I would like to enable tagging (creating related objects on the fly) in the autocomplete fields of the Django admin. Consider a model named Task that has a foreign key to a simple Instruction model with a single TextField: class Task(models.Model): instructions = models.ForeignKey( "Instructions", on_delete=models.SET_NULL, null=True, blank=True ) class Instructions(models.Model): content = models.TextField(blank=False, null=False, max_length=500) The Task model may be displayed using an inline in other model admins (for instance Project). So far I've managed to enable the tagging feature of the Select2 widget by setting data-tags in the ModelForm: from django.contrib.admin.widgets import AutocompleteSelect class TaskInlineModelForm(forms.ModelForm): class Meta: model = Task widgets = { "instructions": AutocompleteSelect( Task.instructions.field, admin_site=admin.site, attrs={"data-tags": "true"}, # <--- right here ), ... } but when trying to save a form containing a TaskInlineModelForm and having typed a yet unseen value in the instructions field, Django complains about finding the typed value instead of an id Field 'id' expected a number but got "This is a brand new instructions that has never been seen". How could this be solved so users can conveniently add new Instructions on the fly without using the mouse? -
MySQLdb.ProgrammingError: (1146, "Table ' ' doesn't exist")
I get the error "MySQLdb.ProgrammingError: (1146, "Table 'test_sageservice.processed_transactions' doesn't exist")" when ever I try to run the my tests using the command pyton manage.py test . I have tried running python manage.py makemigrations and python manage.py migrate, all goes well but when try running my tests I get the error below my tests.py look like this from django.test import TestCase # Create your tests here. class DashboardTests(TestCase): def test_uses_dashboard_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'dashboard.html') My settings look like this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sageservice', 'USER': 'root', 'PASSWORD': 'not_my_password', 'HOST': '127.0.0.1', 'PORT': '3306', } } -
I've problem with time consuming and Application killed in django API after run a massive data handling
I wanna a solution for this part of code I put my code for review def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) sensors = serializer.data["sensors"] string_sensors = ["\"id\"", "\"datatime\""] string_sensors += [f"\"{s_s['parameter']}\"" for s_s in sensors] query = f'SELECT {",".join(string_sensors)} FROM public.traces ' if "start" in serializer.data and "end" in serializer.data: start = serializer.data["start"] end = serializer.data["end"] query += f"where datatime >= '{start}' AND datatime <= '{end}'" if "db" in kwargs: db = kwargs['db'] else: raise ValidationError({"error": "the id of project required"}) try: project = Projects.objects.filter(id=db).first() conn = connection(project.database) cur = conn.cursor(cursor_factory=RealDictCursor) query += " ORDER BY datatime ASC" cur.execute(query) data = cur.fetchall() cur.close() conn.close() df = pd.DataFrame(data) pandas_time_interval = self.get_unit_for_pandas(serializer.data["unit"], serializer.data["time_interval"]) df['datetime'] = df['datatime'] df.set_index('datatime', inplace=True) df = df.resample(pandas_time_interval).first() df.reset_index(drop=True, inplace=True) df.dropna(how='all', inplace=True) # calculating sensors with units # formatting sensors formula sensors_formula = dict() for sensor in sensors: sensors_formula[sensor["parameter"]] = sensor["formula"] sensors_data = df.to_dict() for data in sensors_data: if data == "id" or data == "datetime": continue # handle calculation import numexpr as ne formula = sensors_formula[data] for i in sensors_data[data]: if formula is None: continue f_replaced = formula.replace("x", str(float(sensors_data[data][i]))) try: sensors_data[data][i] = float(ne.evaluate(f_replaced)) except Exception as e: continue # save file df = pd.DataFrame(sensors_data) exported_data … -
Django logs not displaying in docker container with Gunicorn when DEBUG = False
I have a Django application that I'm trying to containerize for Kubernetes, I don't need nginx, I have Kubernetes load balancer. I have created a Docker file for the Django container as follows: FROM python:3.11-alpine WORKDIR /usr/src/app COPY requirements.txt ./ RUN apk add musl-dev mariadb-dev gcc RUN pip install --no-cache-dir -r requirements.txt COPY . . RUN python manage.py collectstatic CMD ["gunicorn" , "--bind", "0.0.0.0:8000", "app.wsgi"] I have set DEBUG = False in my Django settings, and I would like to see the Django logs in the container. However, when I run the container, I only see the following logs: datetime [datetime] [1] [INFO] Starting gunicorn 20.1.0 datetime [datetime] [1] [INFO] Listening at: http://0.0.0.0:80 (1) datetime [datetime] [1] [INFO] Using worker: sync datetime [datetime] [1] [INFO] Booting worker with pid: 7 I have tried to set up the default logging configuration in my Django settings as follows: LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "root": { "handlers": ["console"], "level": "INFO", }, } However, I still don't see any Django logs in the container. Is there anything else I need to configure to get the Django logs to display when running the container (visited … -
Can you pause a Django view execution until a condition is met?
I have a request to an external API within a view which returns two separate solutions. What I would like to achieve is a pause on the execution (so the results are in memory) and, once the user on the front-end decides which solution to save, the execution continues and the results they chose are saved. What I’ve initially tried is something like this: def result_user_wants(request): request.session[‘user_wants_result’] return JsonResponse({‘result_user_wants’: 1}) def view_to_pause(request): while ‘user_wants_result’ not in request.session.keys(): sleep(1) code_that_saves_result() Whatever the user decides on the front end is passed to the results_user_wants view and modifies the session data. What I’m then hoping is that the while loop in view_to_pause is paused until the key exists. This unfortunately doesn’t work, I think because the request data hasn’t been refreshed due to the pause. My only other thought is to save both results sets in the database and when the user chooses, the other result set is deleted. Appreciate any other thoughts! -
How to filter in a django mptt-model using django-filters
I have models.py from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length = 255, null = False, blank = False) parent = TreeForeignKey('self', on_delete = models.CASCADE, blank = False, null = True, related_name = 'children') # other fields class Product(models.Model): category = models.ForeignKey(Category, on_delete = models.SET_NULL, null = True, blank = True, related_name = 'products') # other fields views.py class ProductAPIView(generics.GenericAPIView): serializer_class = ProductSerializer queryset = Product.objects.all() filter_backends = [ DjangoFilterBackend ] filterset_class = ProductFilter def get(self, request): products = self.filter_queryset(self.get_queryset()) serializer = self.serializer_class(products, many = True) return Response(serializer.data) class CategoryAPIView(generics.GenericAPIView): serializer_class = CategorySerializer queryset = Category.objects.root_nodes() filters.py from django_filters import FilterSet, CharFilter, NumberFilter from .models import Product class ProductFilter(FilterSet): brand = CharFilter(field_name='brand__name', lookup_expr='iexact') category = CharFilter(field_name='category__name', lookup_expr='iexact') discount = NumberFilter(field_name='discount', lookup_expr='gte') class Meta: model = Product fields = {} My response looks like this { "name" : "electronics" "parent" : None, "products" : [] "children" : [ "name" : "cameras" "parent" : "electronics", "products" : [] "children" : [ "name": "DSLR Cameras", "parent" : "cameras", "products": [ "name": "Cannon EOS 80D DSLR Camera" ] ] ] } When i send query param with category=dslr cameras, i'm able to get the products associated with this category, but if i … -
How can i add css style tag in django template
im trying to style my html code but its not working properly {% extends 'base.html' %} {% load static %} <style> .divider:after, .divider:before { content: ""; flex: 1; height: 1px; background: #eee; } </style> {% block content%} <section class="vh-100"> <div class="container py-5 h-100"> <div class="row d-flex align-items-center justify-content-center h-100"> <div class="col-md-8 col-lg-7 col-xl-6"> <img src="https://mdbcdn.b-cdn.net/img/Photos/new-templates/bootstrap-login-form/draw2.svg" class="img-fluid" alt="Phone image"> </div> <div class="col-md-7 col-lg-5 col-xl-5 offset-xl-1"> <form> <!-- Email input --> <div class="form-outline mb-4"> <input type="email" id="form1Example13" class="form-control form-control-lg" /> <label class="form-label" for="form1Example13">Email address</label> </div> </form> im trying to style my html code but its not working properly i didnot add my full html code anyone please help me to solve this -
How to include multiple urls.py from the sam django app?
I'm new to django and htmx and was trying to keep my urls.py a bit more clean by putting all urls which just give a htmx response into another file. To include this file into my paths I used djangos include function, because I'd like to route all htmx-specific request over an url called /htmxFunctions/* The folder structur is: project base_project urls.py my_app urls.py htmx htmx_urls.py my url files look like this: # base_project/urls.py urlpatterns = [ path("", include("my_app.urls")), path("admin/", admin.site.urls), path("__reload__/", include("django_browser_reload.urls")), #tailwind specific ] #my_app/urls.py urlpatterns = [ path("", views.index, name="index"), ... # htmx-funktionen path("htmxFunctions", include("my_app.htmx.htmx_urls")), ] my_app/htmx/htmx_urls.py urlpatterns = [ path("test", views.test, name="test"), path("", views.index, name="test"), # for testing purposes ] My Probblem is, using hx-post="/htmxFunctions/test/" only results in an 404 error. but the general include seems to work because just using hx-post="/htmxFunctions" gives the right response. Does someone know how to solve this problem? Allready checked for spelling errors, tried porbably every combination of using slashes in the routes of hx-post and my path but nothing seems to work. Also tried namespacing but didn't really get what it is supposed to do. path( "htmxFunctions", include(("my_app.htmx.htmx_urls", "htmx"), namespace="htmx"), ), -
return multiple objects from Django get
I am updating an API get response in a Django app to include additional data. I have the following existing structure models.py class OriginalModel(models.Model): field_1 = models.CharField() field_2 = models.CharField() serializers.py class OriginalSerializer(serialisers.ModelSerializer): class Meta: model = models.OriginalModel fields = ['var_1', 'var_2'] views.py class OriginalView(RetrieveAPIView): query_set = models.OriginalModel.objects.all() serializer_class = serializers.OriginalSerializer I now need to introduce an additional model (without updating the existing one), but have the view return all data from both models. models.py class NewModel(models.Model): field_3 = models.CharField() serializer.py class NewSerializer(serialisers.ModelSerializer): class Meta: model = models.NewModel fields = ['var_3'] What is the best way to update the view so that it can return the data from both models? I have the following so far views.py from rest_framework.response import Response class OriginalView(RetrieveAPIView): query_set = models.OriginalModel.objects.all() def get(request, *args, **kwargs): original_model = get_object_or_none(models.OriginalModel, *args, **kwargs) s1 = serializer.get_serializer(original_model) new_model = get_object_or_none(models.NewModel, *args, **kwargs) s2 = serializer.get_serializer(new_model) if not s1 or not s2: raise Exception("Error getting models") return Response(s1.data) Firstly, I am not sure if this is the correct approach? If so, I need help in extending the query_set variable to include the NewModel objects in addition to the OriginalModel ones. I also don't know how to correctly forumulate the response … -
Heroku Deployment Issue: App Deploys Empty, No Content Rendered
I'm facing an issue with deploying my Django application on Heroku. The deployment process completes without any errors, but when I access the deployed app, it appears empty with no content rendered. However, when I run the application locally, everything works perfectly, and I can see the expected content. I have checked the logs using the heroku logs command, and there are no error messages or exceptions indicating any issues with the deployment. It seems like the deployment process itself is successful, but the app is not rendering the expected content on Heroku. I have confirmed that all the necessary files, including templates, static files, and database migrations, are included in my Git repository and are being pushed to Heroku. I have also ensured that the Heroku environment variables are properly set. I would greatly appreciate any insights, suggestions, or troubleshooting steps to identify the cause of this issue and successfully deploy my application on Heroku with the expected content rendered. Thank you in advance for your assistance! I have tried basic troubleshooting steps to identify the issue with the deployment. These include: Verifying that all necessary files, such as templates, static files, and database migrations, are included in the … -
Django: static files not served locally
I know this question was previously asked and I already tried many different configurations to fix this. I had no problem serving my static files locally when developing but, if I remember correctly (don't know exactly because of the browser cache), I ran python manage.py collectstatic and then all static files were nowhere to be found: [15/May/2023 08:55:59] "GET /static/js/script.js HTTP/1.1" 404 179 [15/May/2023 08:55:59] "GET /static/admin/css/responsive.css HTTP/1.1" 404 179 ... Here is my settings.py: DEBUG = ENV.bool("DEBUG") # set to True INSTALLED_APPS = [ "django.contrib.staticfiles", ... ] STATIC_URL = "static/" STATIC_ROOT = BASE_DIR / STATIC_PATH # I have checked that the path is correct STATICFILES_DIRS = [ # I tried with and without STATICFILES_DIRS BASE_DIR / "vhsapp" / "static" ] urls.py ... if settings.DEBUG: urlpatterns += [ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT), ] base_site.html {% extends "admin/base_site.html" %} {# TEMPLATE EXTENSION FOR THE DEFAULT ADMIN INTERFACE #} {% load static %} {% block extrahead %} {{ block.super }} <link rel="icon" type="image/x-icon" href="{% static 'img/favicon.png' %}"> <!-- 404 error --> <script> const APP_NAME = "{{ APP_NAME }}"; // variable defined correctly </script> {% endblock %} Project arborescence project_root/ ├── staticfiles/ # all static files are inside this directory ├── templates/ │ └── admin/ … -
How to change UUID field representation globally in Django?
I have defined various models with UUID ids in a Django DRF project: id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) However, the default to_representation implementation of rest_framework.serializers.UUIDField is: valid_formats = ('hex_verbose', 'hex', 'int', 'urn') def to_representation(self, value): if self.uuid_format == 'hex_verbose': return str(value) else: return getattr(value, self.uuid_format) So the output of all API routes in the project render the UUID output as a string, divided by dashes: "id": "86582c7d-a10e-4e2e-be42-8e045ca0fa00", what I want to do is to change the global representation of UUIDs in all the project serializers/routes to hex (removing the dashes), "id": "86582c7da10e4e2ebe428e045ca0fa00". Does anyone know how can I address rest-framework to change the output for all UUIDs? I don't want to change any pre-defiend model, serializer or view!