Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make option HTML tag set something in the url - Django
I am trying to do something, but I don't know if it's acutally possible... Basically I'm trying to pass information in the url... (something like this) <form class="header__search" method="GET" action=""> <input name="q" placeholder="Browse Topics" /> </form> but instead of using a text input I would like the user to simply click an option in a dropdown menu... (like this) <form action="" method="GET"> <div class="units-div"> <label for="units">Units:</label> <select name="units" id="units-selection"> <option value="metric">Metric</option> <option value="imperial">Imperial</option> </select> </div> <div class="language-div"> <label for="language">Language:</label> <select name="language" id="language-selection"> <option value="english">English</option> <option value="italian">Italian</option> </option> </select> </div> </form> Is it possible to do so? Hopefully I've explained myself decently lol -
Django: 'Couldn't reconstruct field' on subclass of `OneToOneField`
I've made a field Extends with this super short declaration: class Extends(models.OneToOneField): def __init__(self, to, **kwargs): super().__init__( to, on_delete=models.CASCADE, primary_key=True, **kwargs ) However, if i use this as a field in a model, say class Person(models.Model): user = Extends(User) I get the following error, when making migrations: TypeError: Couldn't reconstruct field user on app.Person: Extends.__init__() missing 1 required positional argument: 'to' I'm struggling to understand what this means. How can I fix it? -
How to auto increament unique number with a prefix?
How can i increment an invoice number with a prefix “INV” and number that increments ‘0001’, ‘0002’, ‘0003’......and so on..... when the user creates an invoice? class Invoice(model.Models): clients_name = models.ForeignKey(Clients, on_delete=models.CASCADE, blank=True,null=True) invoice_number = invoice_number = models.CharField(max_length=200, blank=True, null=True) once the user creates/saves the invoice form, the hidden field(invoice field) should be autofilled with invoice number e.g. | client | invoice| | -------- | -------- | | client_name1 | INV-001 | | client_name2 | INV-002 | | client_name4 | INV-003 | | client_name8 | INV-004 | -
Accessing field from OneToOne field in ModelForm using Class based Views
I have created a model Agent that is in a OneToOne relation with the User model. I managed to create a form where I can edit the Agent(user) details, but I would like to populate the form with the existing details of the model(Agent/user). Found something similar here but it is not using Class based views. models.py -> class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) organisation = models.ForeignKey(UserProfile, on_delete=models.CASCADE) def __str__(self): return self.user.email forms.py -> from django import forms from django.contrib.auth import get_user_model User = get_user_model() class AgentModelForm(forms.ModelForm): class Meta: model = User fields = ( 'email', 'username', 'first_name', 'last_name' ) views.py -> class AgentUpdateView(OrganisorAndLoginRequiredMixin,generic.UpdateView): template_name = "agents/agent_update.html" form_class = AgentModelForm queryset = Agent.objects.all() def get_success_url(self): return reverse("agents:agent_list") -
Uploading images in Django-React framework returns error 403
I am building an app in Django-React that requires me to upload some images into a folder. When I submit the upload button I get error 403 on the request. Looking at the console, the response says: "CSRF Failed: CSRF token missing or incorrect." I have tried adding the @csrf_exempt decorator over the function in views.py but that is not working. Here's an extract of the relevant code: settings.py MEDIA_URL = '/upload/' MEDIA_ROOT = os.path.join(BASE_DIR, '..', 'frontend', 'build', 'static', 'assets') urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, re_path from django.views.generic import TemplateView from woundapp import views from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ path('upload/', views.upload_images), path('admin/', admin.site.urls), ... re_path(r".*", TemplateView.as_view(template_name="index.html")), ] urlpatterns = format_suffix_patterns(urlpatterns) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py from django.db import models class Image(models.Model): image_url = models.ImageField(upload_to='unprocessed/') serializers.py from rest_framework import serializers from .models import Image class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = [ 'image_url' ] views.py from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import os from .models import Image from .serializers import ImageSerializer import requests from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status @api_view(['POST']) @csrf_exempt def upload_images(request, format=None): if … -
django forms - CSS alignment
I am pretty new to CSS, however I have a django modelformset_factory which i need to render and align all rendered fields in same line for each field, it has TextArea and Textinput, the problem as per the attached picture i tried to aligned all but they never get aligned together. here my view: from django.forms import modelformset_factory def form_employee(request, employee_id): employee = Employee.objects.get(pk=employee_id) Employee_PM = PMF.objects.filter(badge=employee_id) for pm in Employee_PM: form_reference = pm.form_ref emp_form = PMF_Form.objects.filter(form_ref=form_reference) emp_summary = PMF_Summary.objects.filter(badge=employee_id) PMF_formset = modelformset_factory(PMF_Form, fields=('objective','obj_desc','rating',), extra=0) formset = PMF_formset(queryset=PMF_Form.objects.filter(form_ref=form_reference)) if request.method == "POST": formset = PMF_formset(request.POST, queryset=PMF_Form.objects.filter(form_ref=form_reference)) if formset.is_valid(): formset.save() return redirect('/') for form in formset: form.fields['objective'].widget.attrs['disabled'] = True form.fields['obj_desc'].widget.attrs['disabled'] = True context = {"Employee_PM":Employee_PM,"employee":employee,"emp_form":emp_form,"emp_summary":emp_summary,"formset":formset} return render(request, 'PMS/form_employee.html',context) \* { padding: 2px; margin: 0px; margin-bottom: 4px; background-color: black; color: aliceblue; box-sizing:border-box; flex-direction: column; } .container { background-color: black; } body { background-color: black; } .form2 { margin: 20px; box-sizing: border-box; width:100%; resize: none; overflow-wrap: break-word; /\* display: flex; \*/ margin: auto; } input { /\* width: 50%; \*/ display: inline-block; width:15rem; height: 70px; position: relative; } textarea { width: 50rem; height: 70px; resize: none; } } span { justify-content: center ; display: flex; } <div class="container"> <h2>formset</h2> <form method="POST" class="form2" enctype="multipart/form-data"> … -
Django form 2 not loading
I am trying to build a inventory management project facing some difficulty, Looking for a solution. I have created a 2 form in django model and when I try to load form2 only form1 is loading for all the condition. I have tried to comment form1 and load only form2 with that I got the expected result but when I try to add run with both the forms I am facing the issue. Additional to this in django admin panel I am getting I am getting both the forms as expected. Any kind of help will be appreciated. Views.py from .models import Inventory_Details, Incoming_QC from .forms import MyForm, Incoming_QC_form def my_form(request): if request.method == "POST": form = MyForm(request.POST) if form.is_valid(): form.save() return HttpResponse('Submitted successfully') #return redirect('/home_page/') else: form = MyForm() return render(request, "authentication/Inventory_details.html", {'form': form}) def View_Inventory(request): Inventory_list = Inventory_Details.objects.all() return render(request,'authentication/View_Inventory.html', {'Inventory_list': Inventory_list}) def Incoming_qc_form(request): if request.method == "POST": QC_form = Incoming_QC_form(request.POST) if QC_form.is_valid(): QC_form.save() return HttpResponse('Submitted successfully') #return redirect('/home_page/') else: QC_form = Incoming_QC_form() return render(request, "authentication/Incoming_QC.html", {'QC_form': QC_form}) def View_Incoming_QC(request): Incoming_QC_list = Incoming_QC.objects.all() return render(request,'authentication/View_Incoming_QC.html', {'Incoming_QC_list': Incoming_QC_list}) urls.py url(r'form', views.my_form, name='form'), path('View_Inventory', views.View_Inventory, name="View_Inventory"), url(r'QC_form', views.Incoming_qc_form, name='QC_form'), path('View_Incoming_QC', views.View_Incoming_QC, name="View_Incoming_QC") html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, … -
Show 'POST' method API in urls.py and browser url list
Currently I got create a new API with method('POST') how I can set it in the urls.py so that when I runserver, at the browser able to found this API view.py @transaction.atomic @api_view(['POST']) def posting_simain_api(request,): print("Start Time"+ str(panda.panda_toda urls.py from django.urls import include, path, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'ts_TsSimain', views.TsSimainViewSet) router.register(r'ts_TsSimain_parent', views.TsSimainViewSet_parent) urlpatterns = [ path('', include(router.urls)), path('posting_simain_api', views.posting_simain_api, name='posting_simain_api'), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] Question is how I going to show this API in this list? enter image description here I want to show the API in the list here, so that Frontend Developer able to know what API are ready -
How to convert this quesry into Django ORM
SELECT * FROM SUbPlans LEFT JOIN orders on SUbPlans.empId=orders.selected_id where orders.user_id=2 I have this query that I want to convert into Django ORM. What I did was : orders = orders.objects.filter(user_id=2).first() userid = orders.some_field subplans = SUbPlans.objects.filter(another_field=some_field) I just want to do this using select_related. SUbPlans and orders are connected via foriegn key -
OpenEdx error while running python code in Codejail Plugins using Dockerize container services
I have installed a stack of OpexEDX platform using Tutor and installed OpexEdx "Codejail" plugin using below link pip install git+https://github.com/edunext/tutor-contrib-codejail https://github.com/eduNEXT/tutor-contrib-codejail I am facing a problem during working on the code jail while importing python matplotlib library. importing the same library inside codejail container is working fine. the only problem is import through OpnexEdx code block. > advance black > problem. I have already installed the Codejail and Matplotlib on docker. I have to run this code. which gives error <problem> <script type="loncapa/python"> import matplotlib </script> </problem> import os but getting error on the import matplotlib open edx version : openedx-mfe:14.0.1 code jail version : codejailservice:14.1.0 please see the error message below cannot create LoncapaProblem block-v1:VUP+Math101+2022+type@problem+block@3319c4e42da64a74b0e40f048e3f2599: Error while executing script code: Couldn't execute jailed code: stdout: b'', stderr: b'Traceback (most recent call last):\n File &#34;jailed_code&#34;, line 19, in <module>\n exec(code, g_dict)\n File &#34;<string>&#34;, line 66, in <module>\n File &#34;/sandbox/venv/lib/python3.8/site-packages/matplotlib/__init__.py&#34;, line 921, in <module>\n dict.update(rcParams, rc_params_in_file(matplotlib_fname()))\n File &#34;/sandbox/venv/lib/python3.8/site-packages/matplotlib/__init__.py&#34;, line 602, in matplotlib_fname\n for fname in gen_candidates():\n File &#34;/sandbox/venv/lib/python3.8/site-packages/matplotlib/__init__.py&#34;, line 599, in gen_candidates\n yield os.path.join(get_configdir(), \'matplotlibrc\')\n File &#34;/sandbox/venv/lib/python3.8/site-packages/matplotlib/__init__.py&#34;, line 239, in wrapper\n ret = func(**kwargs)\n File &#34;/sandbox/venv/lib/python3.8/site-packages/matplotlib/__init__.py&#34;, line 502, in get_configdir\n return get_config_or_cache_dir(_get_xdg_config_dir())\n File &#34;/sandbox/venv/lib/python3.8/site-packages/matplotlib/__init__.py&#34;, line 474, in get_config_or_cache_dir\n tempfile.mkdtemp(prefix=&#34;matplotlib-&#34;)\n File … -
Axios Post request Is Not Working it is Changing to get request
I Am trying To Send Post request to The Django using Axios But it Is Not Working instead it sending get request after the submit button is pressed. I don't know why this happening I Hvae configured Everything corretelty but it is not working Any Has Any solution to this then please help me My Html Code Is <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Out</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.1.3/axios.min.js" integrity="sha512-0qU9M9jfqPw6FKkPafM3gy2CBAvUWnYVOfNPDYKVuRTel1PrciTj+a9P3loJB+j0QmN2Y0JYQmkBBS8W+mbezg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> {% load static %} </head> <body> <div align = "center"> <form action="" name = "out" id ="out" > {% csrf_token %} <table> <th>Name</th> <th>Stock_out</th> <tr> <td><input type="text" id="name" name="name"></td> <td><input type="text" id="stock_out" name="stock_out"></td> </tr> <tr > <td><span id ="name_er"></span></td> <td><span id ="stock_err"></span></td> </tr> </table> <input type="button" value="Submit" form = "out" onclick="submit()"> </form> </div> <script src="{% static 'out.js/'%}"></script> </body> </html> Here Is My Js Script function submit(){ let nam = document.getElementById('name').value; let out = document.getElementById('stock_out').values if(nam=="" | nam==null){ document.getElementById('nam-er').innerHTML="Name Insert please" return false }else{ let form = document.getElementById('out'); var data = new FormData(form); data.append('name', document.getElementById('name').value); data.append('stock_out', document.getElementById('stock_out').value); data.append("csrfmiddelwaretoken",'{{csrf_token}}'); // form.reset(); const url = BASE_URL + '/add/product_out'; axios.post(url,data).then(function(resp){ window.location.href = "add/success"; console.log(resp); }) .catch(function (error) { console.log(error); }) } } Here Is My Django … -
In django I have created "tool" app, When I try to import tool to other file I got error "No module named 'tool' "
please check the following image for reference from tool.models import loginauth Traceback (most recent call last): File "<string>", line 1, in <module> ModuleNotFoundError: No module named 'tool' -
Redis giving the error: TypeError: Connection.__init__() got an unexpected keyword argument 'username'
I am integrating the celery in our project. Redis giving the error when, I am trying to run this command python -m celery -A claims_dashboard worker # Celery settings.py CELERY_BROKER_URL = "redis://0.0.0.0:6379" CELERY_RESULT_BACKEND = "redis://0.0.0.0:6379" CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' # celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "claims_dashboard.settings") app = Celery("claims_dashboard") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() #init.py file from .celery import app as celery_app __all__ = ('celery_app',) This is the traceback of my code , I have not write anywhere the "username" in my code. (django-venv) naveenprakashsatyarthi@LAP-ART-MP283WK5:~/Desktop/Artivatic/claims_dashboard/claims_dashboard_backend/claims_dashboard$ python -m celery -A claims_dashboard worker -------------- celery@LAP-ART-MP283WK5 v5.1.1 (sun-harmonics) --- ***** ----- -- ******* ---- Linux-5.15.0-53-generic-x86_64-with-glibc2.35 2022-11-23 05:25:07 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: claims_dashboard:0x7f233d74ba90 - ** ---------- .> transport: redis://0.0.0.0:6379// - ** ---------- .> results: redis://0.0.0.0:6379/ - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [2022-11-23 05:25:07,912: CRITICAL/MainProcess] Unrecoverable error: TypeError("Connection.__init__() got an unexpected keyword argument 'username'") Traceback (most recent call last): File "/home/naveenprakashsatyarthi/django-venv/lib/python3.10/site-packages/kombu/transport/virtual/base.py", line 925, in create_channel return self._avail_channels.pop() IndexError: pop from empty list … -
Can I add a non-editable field to the class based view UpdateView in Django
class EmployeeView(generic.edit.UpdateView): model = Employee fields = '__all__' template_name = 'wfp/employee.html' def get_object(self, queryset=None): return Employee.objects.get(uuid=self.kwargs.get("employee_uuid")) has everything I need except the UUID that is on the employee which is non-editable. I'd really like to include that in the HTTPResponse so I can use elsewhere a link to another page. (Employee have allocations of things) Ideas? Thanks -
Django admin extend user permissions template
I have setup a custom user model with BaseUserManager and AbstractBaseUser. All is working fine but I am missing the Django build in user permissions. How can I extend a custom template to include this? -
How do I set up my Django urlpatterns within my app (not project)
Let's say I've got the classic "School" app within my Django project. My school/models.py contains models for both student and course. All my project files live within a directory I named config. How do I write an include statement(s) within config/urls.py that references two separate endpoints within school/urls.py? And then what do I put in schools/urls.py? For example, if I were trying to define an endpoint just for students, in config/urls.py I would do something like this: from django.urls import path, include urlpatterns = [ ... path("students/", include("school.urls"), name="students"), ... ] And then in school/urls.py I would do something like this: from django.urls import path from peakbagger.views import StudentCreateView, StudentDetailView, StudentListView, StudentUpdateView, StudentDeleteView urlpatterns = [ # ... path("", StudentListView.as_view(), name="student-list"), path("add/", StudentCreateView.as_view(), name="student-add"), path("<int:pk>/", StudentDetailView.as_view(), name="student-detail"), path("<int:pk>/update/", StudentUpdateView.as_view(), name="student-update"), path("<int:pk>/delete/", StudentDeleteView.as_view(), name="student-delete"), ] But how do I do I add another urlpattern to config/urls.py along the lines of something like this? The include statement needs some additional info/parameters, no? from django.urls import path, include urlpatterns = [ ... path("students/", include("school.urls"), name="students"), path("courses/", include("school.urls"), name="courses"), ... ] And then what happens inside of school/urls.py? I'm open to suggestions, and definitely am a neophyte when it comes to the Django philosophy. … -
Adding foriegn key to model- Django
I am a novice in django. So please hear me out. I have 2 models: 1. class Plans(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) plan_type = models.CharField(max_length=255) class Order(models.Model): id = models.IntegerField(primary_key=True) selected_plan_id = models.IntegerField(primary_key=True) Order model's selected_plan_id is Plans id. Which model should i add foriegn key to? and how? So far i have started learning django, -
How can I make a view with an admin and user?
I'm making a crude in Django, and when I create it's shows and options depending if you are an administrator or a Jefe from the table. the administrator its from panel Django class UsuarioCrear(SuccessMessageMixin, CreateView): model = Usuarios form = Usuarios if user.is_superuser: fields = ['nombre', 'correo', 'contraseña', 'cedula'] success_message = 'usuario creado correctamente !' def get_success_url(self): return reverse('leer') else: fields = "_all_" success_message = 'usuario creado correctamente !' def get_success_url(self): return reverse('leer') So, I try with an if asking if is a superuser show al fields and if not is a super user show an specific fields, but i got an error when i do that -
How to update django database with a list of dictionary items?
I have a list of key value pairs here. stat = [{'id': 1, 'status': 'Not Fixed'}, {'id': 2, 'status': 'Not Fixed'}, {'id': 4, 'status': 'Not Fixed'}, {'id': 5, 'status': 'Not Fixed'}, {'id': 6, 'status': 'Not Fixed'}, {'id': 7, 'status': 'Not Fixed'}] The id in this list represents the id(primary key) of my django model. How can I update the existing records in my database with this list? Models.py file class bug(models.Model): ....... ....... status = models.CharField(max_length=25, choices=status_choice, default="Pending") -
How to allow changing a model field if the user has a certain role?
I have CustomUserModel in Django and four roles - user, student, curator, admin And I have group field in CustomUserModel, which default value is Null Now every User can have group, but I want only students to have it. How can I do this on my model level? (like how to check that you need to have Student role to change the value of the group field from Null to other) I tried to use validator, but there I can get only the value of group, and can't use self to check like if self.role = STUDENT USER = 'user' STUDENT = 'student' CURATOR = 'curator' ADMIN = 'admin' ROLES = ( (USER, USER), (STUDENT, STUDENT), (CURATOR, CURATOR), (ADMIN, ADMIN), ) def validate_user_can_have_group(value): ### class User(AbstractUser): role = models.CharField(max_length=max([len(role[0]) for role in ROLES]), choices=ROLES, default=USER,) group = models.ForeignKey('structure.Group', on_delete=models.SET_NULL, validators=[validate_user_can_have_group], related_name='users', blank=True, null=True,) class Meta: swappable = "AUTH_USER_MODEL" ordering = ['username'] @property def is_admin(self): return ( self.role == ADMIN or self.is_staff or self.is_superuser ) @property def is_curator(self): return self.role == CURATOR @property def is_student(self): return self.role == STUDENT @property def is_user(self): return self.role == USER def __str__(self): return self.username -
How to store user input in a variable in django python
So i want to take the user input and compare it to data present in the sqlite3 db, and if matches I'd like to print that whole row, using django orm. form.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title> Assignment 3</title> </head> <body> <h1> Please enter the product barcode in the text box below: </h1> <form action="search"> BARCODE: <input type="text" name="barcode"> <br> <br> <input type="submit"> </form> </body> </html> urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('search', views.search, name='search'), ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return render(request, 'form.html') def search(request): return render(request, 'result.html') I really appreciate your time and help, thank you! i think adding logic to the search function to compare should work but extremely new to django and dont really know on how to start.. -
How to sent an extra field to serializer from view in django rest framework?
serializer.py class DataSerializer(serializers.ModelSerializer): flag = serializers.BooleanField(required=False) class Meta: model = Plans fields = { 'id', 'name', 'type', 'details', 'price' } views.py class DetailsView(APIView): def get(self, request): user_sub_plans = Order.objects.filter(id=request.user).first() selected_plan = False if user_plans is not None: selected_plan = True original_plans = Plans.objects.all() user_serializer = DataSerializer(original_plans, many=True) return Response(user_serializer.data) These are my serializers and views. I want to send selected_plan into my serializers as an output. I have created an extra field in serializers called flag for this but don't know how to send it. Can anyone help? -
Error de Python 4.0.1 con conexión a SQL Server
He intentado conectar a SQL server con Python Django pero no me permite realizar la migración inicial pero me sale error. enter image description here Me sale que Django no tiene soporte. Estos son los paquetes que he usado: Package Version asgiref 3.5.2 asttokens 2.1.0 backcall 0.2.0 colorama 0.4.6 contourpy 1.0.6 cycler 0.11.0 debugpy 1.6.3 decorator 5.1.1 Django 4.0.8 django-environ 0.9.0 django-pyodbc 1.1.3 django-pyodbc-azure 2.1.0.0 djangorestframework 3.14.0 djangorestframework-simplejwt 5.2.2 entrypoints 0.4 executing 1.2.0 fonttools 4.38.0 ipykernel 6.17.1 ipython 8.6.0 jedi 0.18.1 jupyter_client 7.4.7 stack-data 0.6.1 tornado 6.2 traitlets 5.5.0 tzdata 2022.6 wcwidth 0.2.5 Espero que el aplicativo Django pueda conectarse con una Base de datos SQL Server Express local -
Exposing websockets port through same location dokku
I have a django project where I run my web and django channels as separate procs in the Procfile: web: gunicorn django_project.wsgi:application socket: daphne django_project.asgi:application And have exposed ws/wss using dokku proxy:ports-add web ws:80:8000 wss:443:8000 (web is my dokku app name): =====> web proxy information Proxy enabled: true Proxy port map: http:80:5000 https:443:5000 ws:80:8000 wss:443:8000 Proxy type: nginx I've exposed container port 8000 because daphne runs on port 8000 by default: app[socket.1]: Starting server at tcp:port=8000:interface=127.0.0.1 app[socket.1]: Configuring endpoint tcp:port=8000:interface=127.0.0.1 app[socket.1]: Listening on TCP address 127.0.0.1:8000 But I'm unable to connect to my websocket in the browser. I get a Not Found: /ws/mywebsocket error for my websocket endpoint, and socket.onclose function immediately gets called with a code: 1006. I think I need to create a custom nginx.sigil for dokku to redirect to the websocket if the url contains /ws/, but a lot of the answers seem out of date and not working. -
Add field to DRF's exceptions.PermissionDenied
Right now django-rest-framework's exceptions.PermissionDenied returns a 403 and a detail saying "You don't have permission to perform his action." {"detail": "You don't have permission to perform this action."} I'd like to extend this to include a "reason" field, so I can do something like `MyException(detail="Some detail here", reason="INSUFFICIENT_TIER"). but detail seems to chain quite far up and get transformed in quite a few places. Does anyone know how I might easily add a field that will be returned in the json above? Here's DRF's exception for reference. class PermissionDenied(APIException): status_code = status.HTTP_403_FORBIDDEN default_detail = _('You do not have permission to perform this action.') default_code = 'permission_denied' It extends APIException: class APIException(Exception): """ Base class for REST framework exceptions. Subclasses should provide `.status_code` and `.default_detail` properties. """ status_code = status.HTTP_500_INTERNAL_SERVER_ERROR default_detail = _('A server error occurred.') default_code = 'error' def __init__(self, detail=None, code=None): if detail is None: detail = self.default_detail if code is None: code = self.default_code self.detail = _get_error_details(detail, code) def __str__(self): return str(self.detail) def get_codes(self): """ Return only the code part of the error details. Eg. {"name": ["required"]} """ return _get_codes(self.detail) def get_full_details(self): """ Return both the message & code parts of the error details. Eg. {"name": [{"message": "This …