Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: Article() got an unexpected keyword argument 'many'
I created an article model for my project. i create my model, serializer and view . but i have this error: TypeError: Article() got an unexpected keyword argument 'many' how can i fix this?? class Article(models.Model): title = models.CharField(max_length=300) slug = models.SlugField(max_length=300, unique=True, allow_unicode=True) image = models.ImageField(upload_to='articles_pic/%Y/%m/%d/') content = RichTextUploadingField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) show = models.BooleanField(default=True) def __str__(self): return self.title serializer: class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = '__all__' view: class ArticleList(generics.ListAPIView): queryset = Article.objects.filter(show=True) serializer_class = Article permission_classes = (permissions.AllowAny,) class ArticleDetail(generics.RetrieveAPIView): queryset = Article.objects.filter(show=True) serializer_class = Article permission_classes = (permissions.AllowAny,) lookup_field = 'slug' -
Prevent User in django View
we can prevent user with permission_classes or Restrict queryset in django rest framework. which one is better?? for example: class OrganizationRetrieveUpdateAPIView(generics.RetrieveUpdateAPIView): permission_classes = [CanEditOrganization] or def get_queryset(self): return models.Organization.objects.filter(creator=self.request.user) !!!CanEditOrganization is a permission class that I writed for this permission I want only the user that is creator of this organization can access this organization now,which one is better?? -
When I activated my enviroment after that my project is not starting showing as django not recoqnized even i installed python and django
(base) C:\Users\shree>activate my (my) C:\Users\shree>django --admin startproject learning_users 'django' is not recognized as an internal or external command, operable program or batch file. (my) C:\Users\shree>conda install django Collecting package metadata (current_repodata.json): done Solving environment: done All requested packages already installed. (my) C:\Users\shree>django --admin startproject learning_users 'django' is not recognized as an internal or external command, operable program or batch file. (my) C:\Users\shree>conda install python Collecting package metadata (current_repodata.json): done Solving environment: done All requested packages already installed. (my) C:\Users\shree>django --admin startproject learning_users 'django' is not recognized as an internal or external command, operable program or batch file. -
Django Extends in template not working . When deploying to AWS
Extends template shows TemplateDoesNotExist at /aws/ adminp/temp.html This is in my setting TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'view.context_processors.data', ], }, }, ] And this is how I am using extends in a another file which is in same directory as "temp.html"- {% extends 'adminp/temp.html '%} it works perfectly on localhost but not when deploying to AWS. -
psycopg2.InterfaceError: only protocol 3 supported
I've created a software that uses PostgreSQL (Version 10.4) as it's DB. I also use Django as an internal API server. For some reason. in a code block not connected in any way to django (I haven't even ran the django migrate because I don't need any DB queries to be made from django) I get this Error: psycopg2.InterfaceError: only protocol 3 supported. The reason I mention django is that a lot of questions in here about this issue had mention django, so I though it might help. this question suggests to upgrade Postgres to version > 7.4 and as I wrote above, I have V10.4 and it still happens. this is the code where it happens: with psycopg2.connect(**self.db) as conn: # this is where the exception occures with conn.cursor() as cur: cur.execute(query) results = cur.fetchall() if return_headers: colnames = [desc[0] for desc in cur.description] results.insert(0, colnames) cur.close() Any idea why would it happen? there are seem to be a lot of questions about this issue on the web with no concrete answer. -
How to get queryset of foreignkey objects from queryset?
I have the following schema: class ModelA(models.Model): field1 = models.CharField(max_length=127) class ModelB(models.Model): field1 = models.CharField(max_length=127) class ModelC(models.Model): a_fk_field = models.OneToOneField(ModelA, on_delete=models.CASCADE) b_fk_field = models.ForeignKey(ModelB, on_delete=models.CASCADE) I have to sort the ModelA instances, based upon the ModelB field field1's values in alphabetical order. One solution that I have come up with is: a_instances = ModelA.objects.none() (a_instances.union(ModelA.objects.filter(id=c.a_fk_field.id)) for c in ModelC.objects.order_by('b_fk_field__field1')) But, this increases the total number of db queries too much. One alternative I thought about is: a_instance_ids = [c.a_fk_field.id for c in ModelC.objects.order_by('b_fk_field__field1')] a_instances = ModelA.objects.filter(id__in=a_instance_ids) But, this changes the order of the final a_instances queryset. Is there a better way to do this? -
How can I render a view from a predefined list/dict, instead of from a database id, in django?
I'm curious if I can render a view directly from a list (or dictionary) in Django instead of from a model, and thus programmatically generate pages based on the corresponding template (here, my_template.html). I've done this many times after creating a model whereby the <str:my_list> would reference the corresponding database in. In a use-case that involves an API call though, I'd rather not go the database route as it becomes somewhat redundant. I'm sure it has to be possible, but I seem to be going in circles trying to execute it. urls.py # ... urlpatterns = [ # ... path('path/<str:my_list>', views.my_view, name='my_view'), ] views.py # ... def my_view(request, my_list): return render(request, 'core/my_template.html') A list could be something as simple as: my_list = [ item_1, item_2, # ... ] Thanks! -
Django model error is unboundPylance (reportUnboundVariable)
I have a model class in Django model.py. like as class EmployInfo(models.Model): password = models.OneToOneField(User, on_delete=models.CASCADE) designation = models.ForeignKey(UserRole, on_delete=models.CASCADE) user_basic = models.OneToOneField(EmployBasicInfo, on_delete=models.CASCADE) user_academic = models.OneToOneField(EmployAcademicInfo, on_delete=models.CASCADE) user_address = models.OneToOneField(EmployAddressInfo, on_delete=models.CASCADE) def __str__(self): return self.user_basic.name I do query object from EmployInfo like as @api_view(['put']) @permission_classes([IsAuthenticated]) @edit_required def employ_update(request, pk): employ_user = EmployInfo.objects.get(id=pk) pass But This error local variable 'EmployInfo' referenced before assignment occurs. why this error occurs I can not understand. pls, help me to solve the problem... -
Change column name to current month
I have a snippet of the following template <div class="table-responsive-sm" style="overflow:scroll"> <table class="table table-striped table-bordered table-hover" id="example"> <thead class="thead-dark"> <tr> <th colspan="2" scope="colgroup">Student grades</th> </tr> <tr> <th colspan="1">Grade1</th> <th colspan="1">Grade2</th> </tr> <tr> <th colspan="1">Current Month</th> <th colspan="1">Previous Month</th> </tr> Does anybody know, how to change 'Current Month' and 'previous Month' into the actual current month (in letters) and actual previous month (also in letters)? I didn't include any code from my views.py because I had nothing written on it yet because I don't know how to change it. -
Tags input field in instance view at admin panel
I'm using django-taggit and its working fine, but one moment. When i open instance in django admin - tags input field autofill with following format: 1 is it possible to get tags input autofill format like this? 2 Or disable autofill by default? Django version 1.9, django-taggit 1.3.0 admin.py 3 -
How long does the event_loop live in a Django>=3.1 async view
I am playing around with the new async views from Django 3.1. Some benefits I would love to have is to do some simple fire-and-forget "tasks" after the view already gave its HttpResponse, like sending a push notification or sending an email. I am not looking for solutions with third-party packages like celery! To test this async views I used some code from this tutorial: https://testdriven.io/blog/django-async-views/ async def http_call_async(): for num in range(1, 200): await asyncio.sleep(1) print(num) # TODO: send email async print('done') async def async_view(request): loop = asyncio.get_event_loop() loop.create_task(http_call_async()) return HttpResponse("Non-blocking HTTP request") I started the django server with uvicorn. When I make a request to this view it will immediately return the HTTP-response "Non-blocking HTTP request". In the meantime and after the HTTP-response, the event loop continues happily to print the numbers up to 200 and then print "done". This is exactly the behaviour I want to utilize for my fire-and-forget tasks. Unfortunatly I could not find any information about the lifetime of the event loop running this code. How long does the event loop live? Is there a timeout? On what does it depend? On uvicorn? Is that configurable? Are there any resources which discuss this topic? -
Django allow user to select session timeout duartion
I want the users or the user admin in my Django application to be able to chose the session timeout duration. I know session timeout can be configured in settings.py but what if i want to give users the ability to chose session timeout duration on the GUI/frontend? -
How can I get editor instance by id? (page has multiple jsoneditor objects)
I am working on integrating JSONEditor into the Django project like a widget for json field. So on one page, I have several JSON instances, but the function onChange works only for the last instance JSONeditor . That is my template: <div id="{{ name }}_editor" style="width: 400px; resize:vertical"></div> <textarea cols="40" id="id_{{ name }}" name="{{ name }}" rows="10" style="display: none">{{ data }}</textarea> <script> var container = document.getElementById("{{ name }}_editor"); var options = { mode: 'code', modes: ['code', 'form', 'text', 'tree', 'view', 'preview'], onError: function (err) { alert(err.toString()); }, onChange(value) { var json = JSONEditor.get(); container.value=JSON.stringify(json); }, }; json = {{ data|safe }}; var editor = new JSONEditor(container, options); editor.set(json) </script> Can I get JSONEditor object by id in onChange?( editor.aceEditor.id) thanks! -
Filtering dropdowns of SubCategories that are in specific Categories
I'm learning django and I have trouble. In django admin panel, when I add product and choose category and subcategory, I see all subcategories of all categories. This is a problem because in my app there can be a lot of similiar SubCategories. The image! I've read a lot of similiar answers, docs in the internet but all the solutions didnt help me (or I'm stupid and did it wrong). Here are my models.py: class Category(models.Model): name = models.CharField('Название',max_length=255) slug = models.SlugField('Ссылка', unique=True) class Sub_Category(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField('Название', max_length=255) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) sub_category = models.ForeignKey(Sub_Category, on_delete=models.CASCADE) title = models.CharField('Название товара:', max_length=50) slug = models.SlugField(unique=True) I will be so grateful if you help me to understand this thing! -
How to update field in model connected via foreign key
I'm working on update view where I want to update size of tshirt by click on the item on Order view list. I stacked in point where I can only display name of item but not update size of tshirt. This is django 3. Please some hint, how I can update size of tshirt connected by foreign key with Order model. models.py class Size(models.TextChoices): SMALL = 'S', 'Small' c = 'M', 'Medium' LARGE = 'L', 'Large' class Tshirt(models.Model): name = models.CharField(max_length=255) size = models.CharField(max_length=2, choices=Size.choices, default=Size.MEDIUM) def __str__(self): return self.name class Order(models.Model): nr = models.PositiveIntegerField(unique=True) item = models.ForeignKey(Tshirt, related_name='order_tshirts', on_delete=models.CASCADE) send_date = models.DateTimeField(null=True, blank=True) def get_update_size_url(self): return reverse('size_update', kwargs={'pk': self.pk}) urls.py path('update/<int:pk>/', TshirtSizeUpdateView.as_view(), name='size_update'), views.py class TshirtSizeUpdateView(UpdateView): model = Order template_name = 'size_update.html' fields = ['item'] success_url = '/' forms.py class OrderForm(forms.ModelForm): class Meta: model = Order fields = '__all__' ``` -
How do I obtain a string with special characters line'<','>' that are filled into forms in django
I'm using a form to read inputs. The form.py looks like this from django import forms class Form_info(forms.Form): file_format = forms.CharField(label='file format :', help_text='Write the fields in the file within square brackets along with other special characters that occur') file_format field takes inputs like : <Date> <Time> <CustomerName>: [<Payment>]. I want to retrieve a this string in the view.py file. My current views.py file has a method forms_info that handles the form: def forms_info(request): if request.method = "POST": form = Form_info(request.POST) if form.is_valid(): file_format = form.cleaned_data['file_format'] return HttpResponse('<p>file_format : {}</p>'.format(file_format)) return render(request,"form.html",{}) When I fill the form with '<Date> <Time> <CustomerName>: [<Payment>]', the results printed look like this : file_format : : [] It looks like the input between the angular brackets aren't being read. And this is happening only for some characters like '<','>'. Is there any way that I can directly get this entire string : '<Date> <Time> <CustomerName>: [<Payment>]'? Thanks in advance. -
Django model save the form but does not show me
Hi I have created a address model and link that model to the forms and created the view. but that form does save any data but that data does not show to me. Although it show me that data in the terminal .This is how my admin look like:admin here is my address model.address model and my billing model is which I inherit here is: billing model and my form for address model is:address form my view for addresses isaddress view: the form is showing on checkout so the checkout view is: cart view now my form.html is: form html and my checkout html is: {% extends 'base.html' %} {% block content %} {{object.order_id}} -- {{object.cart}} {% if not billing_profile %} <div class="row text-center"> <div class="col-12 col-md-6"> <p class="lead">Login</p> {% include 'accounts/snippets/form.html' with form=login_form next_url=request.build_absolute_uri %} </div> <div class="col-12 col-md-6"> <p class="lead">Continue as guest</p> {% url "guest_register" as guest_register_url %} {% include 'accounts/snippets/form.html' with form=guest_form next_url=request.build_absolute_uri action_url=guest_register_url %} </div> </div> {% else %} {% if not object.shipping_address %} <div class="row"> <div class="col-md-6 mx-auto col-10"> <p class="lead">Shipping Address</p> {% url "checkout_address_create" as checkout_address_create %} {% include 'addresses/form.html' with form=address_form next_url=request.build_absolute_uri action_url=checkout_address_create address_type='shipping' %} </div> </div> {% elif not object.billing_address%} <div class="row"> … -
reduce line of code while fetching data from object to object?
I am creating a printing ordering service website in Django and I am stuck on the order page. I have three tables named "product" ,"size", and "sizeProductMap" table. views.py products = Product.objects.get(prod_ID=id) print(products.prod_Name) sizesmap = SizeProductMapping.objects.filter(prod_id=id) sizeslist = [] for data in sizesmap: sizes = data.size_id sizeslist.append(sizes.prod_size) # Here I am getting all the sizes I needed. print(sizes.prod_size) return render(request, "GalaxyOffset/product.html", {'products': products, 'sizeslist': sizeslist}) product.html {% extends 'GalaxyOffset\basic.html' %} {% block title%}Products{% endblock %} {% block body%} <div class="card my-2 mx-0 auto"> <div class="mx-4 my-2"> <h1>{{ products.prod_Name }}</h1> </div> <div class="row"> <div class="col-3"> <img class="border border-secondary my-4 mx-4" height="200" src="{{products.prod_img.url}}" width="200"/> </div> <div class="col-8 my-4"> <p> {{products.prod_Desc}}</p> </div> <div class="dropdown-divider"></div> </div> </div> <div class="row"> <div class="col-4"> <div class="card mx-2 my-2 border border-secondary"> <div class="mx-2 mt-4"> {% for category in categories %} <a id="{{ category.prod_ID }}" class="dropdown-item" href="{% url 'product' category.prod_ID%}"> {{ category.prod_ID }}. {{ category.prod_Name }}</a> <div class="dropdown-divider"></div> {% endfor %} </div> </div> </div> <div class="col-8"> <div class="card mx-2 my-2"> <div class="my-2"> <!-- How can I reduce Number of Line of code here. --> {% for s in sizeslist %} <input type="radio" name="sizes">{{s}} </br> {% endfor %} </div> </div> </div> </div> {% endblock %} Can you help me here … -
Validation error with DRF PointField - "Enter a valid location"
In one of my APIs, I am able to get the DRF extra field, PointField working. In one of the other API where I am using PointField in a nested serializer, it is giving me a validation error. { "booking_address": { "coordinates": [ "Enter a valid location." ] } } And the payload data is { "booking_address": { "coordinates" : { "latitude": 49.87, "longitude": 24.45 }, "address_text": "A123" } } My serializers are below: BookingSerializer class BookingSerializer(FlexFieldsModelSerializer): booked_services = BookedServiceSerializer(many=True) booking_address = BookingAddressSerializer(required=False) ------ def validate_booking_address(self, address): if address.get("id"): address = BookingAddress.objects.get("id") else: address["customer"] = self.context.get("request").user.id serializer = BookingAddressSerializer(data=address) if serializer.is_valid(): <---- error is coming from here address = serializer.save() else: raise ValidationError(serializer.errors) return address My Address Serializer is defined as: class BookingAddressSerializer(FlexFieldsModelSerializer): coordinates = geo_fields.PointField(srid=4326) customer = serializers.IntegerField(required=False) And booking model is: class BookingAddress(BaseTimeStampedModel): customer = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="booking_addresses", on_delete=models.CASCADE) coordinates = models.PointField() address_text = models.CharField(max_length=256) Tried Debugging, been stuck here for a few hours now and not able to find the issue. Any help will be appreciated. -
Django FilePathField throwing a TypeError
When a candidate submits a job application, I want the CV field on the application model to point to the CV that the candidate has saved on their profile. models.py def cv_path(instance): return os.path.join(settings.MEDIA_ROOT, 'candidates/user_{0}'.format(instance.candidate.user.id)) def user_directory_path(instance, filename): return 'candidates/user_{0}/{1}'.format(instance.user.id, filename) class Candidate(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True) cv = models.FileField(upload_to=user_directory_path, default="CV to be added") def __str__(self): return f"{self.user.first_name} {self.user.last_name}" class Application(models.Model): candidate = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) job = models.ForeignKey('Vacancy', on_delete=models.CASCADE) cv = models.FilePathField(path=cv_path, default=None) cover_letter = models.TextField(default=None, validators=[ MinLengthValidator(0), MaxLengthValidator(2000) ]) submitted = models.DateTimeField(auto_now_add=True) is_succesful = models.BooleanField(default=False) Right now, if I try to add an application from the admin site I get this TypeError: TypeError at /admin/recruit/application/add/ cv_path() missing 1 required positional argument: 'instance' However if I change the cv_path to this: def cv_path(): return os.path.join(settings.MEDIA_ROOT, 'candidates/user_2') I do not get any error and the cv field gives me a dropdown of all the CV's saved for the user with an id of 2 but of course I cannot hardcode this. How can I fix this error? -
Django dynamic menu in navbar
I want to create dynamic menu, means that menu load from table Here is menu setup in my django admin panel and here is how i create or setup a menu And this is the current result def process_request(self, request): html_menu = '' menus = menu.Menu.objects.order_by('order_number').all() used_ids = [] for m in menus: print(">>>>>> " , m, m.children_menu.all()) if m.target_url == '' or m.target_url is None or m.target_url == '#': menu_link = '#' else: menu_link = reverse(m.target_url) children = m.children_menu.all() if len(children) > 0: children_ids, children_html_menu = self.recursive_menu(m, children) html_menu += children_html_menu used_ids += children_ids elif m.is_divider: html_menu += f''' <hr class="sidebar-divider"> <div class="sidebar-heading"> {m.title} </div> ''' elif m.id not in used_ids: html_menu += f''' <li class="nav-item active"> <a class="nav-link" href="{menu_link}"> <i class="{m.icon_class}"></i> <span>{m.title}</span> </a> </li> ''' used_ids.append(m.id) print(html_menu) request.menus = html_menu def recursive_menu(self, m, children): print("test " , m, children) children_ids = [] html_menu = f''' <li class="nav-item"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapse{m.order_number}" aria-expanded="true" aria-controls="collapse{m.order_number}"> <i class="{m.icon_class}"></i> <span>{m.title}</span> </a> <div id="collapse{m.order_number}" class="collapse" aria-labelledby="headingUtilities" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> ''' if len(children) < 1: return children_ids, html_menu else: for c in children: # print(c, ">>>>>>>>>..", c.children_menu) children_ids.append(c.id) if c.target_url == '' or c.target_url is None or c.target_url == … -
How to get real password from Django rest framework ( JWT token ). For UserListView
I'm new to this topic, I want to implement the output of users and their real passwords for admin access. At the moment I have this code, it displays encrypted passwords. How can I make the password that the user entered during registration appear in the field? Thank you in advance. class UserListView(generics.ListAPIView): queryset = models.User.objects.all() serializer_class = serializers.UsersListSerializer class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(('email address'), unique=True) first_name = models.CharField(('first name'), max_length=30, blank=True) last_name = models.CharField(('last name'), max_length=30, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return str(self.email) def save(self, *args, **kwargs): super(User, self).save(*args, **kwargs) return self @property def token(self): return self._generate_jwt_token() def _generate_jwt_token(self): dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': dt.utcfromtimestamp(dt.timestamp()) }, settings.SECRET_KEY, algorithm='HS256') return token.decode('utf-8') class UserManager(BaseUserManager): def _create_user(self, first_name, last_name, email, password=None, is_active=True, is_staff=False, is_superuser=False): if not first_name: raise ValueError('First name should be set') if not last_name: raise ValueError('Last name should be set') if not email: raise ValueError('Email should be set') user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, is_active=is_active, is_staff=is_staff, is_superuser=is_superuser ) user.set_password(password) user.save(using=self._db) return user def create_user(self, first_name, last_name, email, password=None): user = self._create_user(first_name, last_name, email, password=password, is_staff=True) return … -
how do I make toasts push messages if there's any
So some of the toasts are working fine how it's supposed to except some "class-based toasts" aren't working, like the 'warning toast' and 'info toast'(sometimes). I want them to show up for a certain time and then make them disappear and all of them should work the same. I tried compiling the javascript code in Babel but still doesn't work, no clue what's causing the situation. Thnx for any help! Getting a console error as such "messages.js:4 Uncaught TypeError: Cannot read property 'style' of null at showToast (messages.js:4) at messages.js:17" let margin = 10; const showToast = (type) => { const toast = document.getElementById(`toast-${type}`); toast.style.display = 'block'; toast.style.marginBottom = `${margin}px`; margin += toast.clientHeight + 5; hideToast(toast); } const hideToast = (toast) => { setTimeout(() => { toast.style.display = 'none'; margin -= toast.clientHeight + 5; }, 2000); } showToast('success'); showToast('info'); showToast('warning'); showToast('error'); .success{ display: none; position: fixed; bottom: 0; margin-bottom: 10px; margin-left: 4%; font-family: Arial; padding: 15px; background-color: forestgreen; color: #FFFFFF; border-radius: 10px; text-align: center; z-index: 2; box-shadow: 0 0 20px rgba(0,0,0,0.3); } .info{ display: none; position: fixed; bottom: 0; margin-bottom: 10px; margin-left: 4%; font-family: Arial; padding: 15px; background-color: blue; color: #FFFFFF; border-radius: 10px; text-align: center; z-index: 2; box-shadow: 0 0 … -
Use `throttle_classes` for spyne application for set rate limit
I have used spyne library for my django rest framework application for incoming XML data. Now i want to implement throttle_classes for set rate limit in order to avoid heavy incoming request load on my server. I have tried this code to use permission_class in URL for spyne application, but it is not working. remove authentication and permission for specific url path url( r"^vapi/", (permission_classes([IsAuthenticated])(vapi_view.vapp)).as_view(application=vapi_view.vapp), ), This one is from django view which is working fine. url(r'^test/$', (permission_classes([IsAuthenticated])(algo_program_views.TestView)).as_view()), I have also tried to use that in Service Class as a decorator, which is also not working. class HelloWorldService(Service): @api_view(['POST']) @permission_classes([IsAuthenticated]) @rpc(Unicode, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, name, times): for i in range(times): yield 'Hello, %s' % name -
How to enable Forms in Django Rest Framework's Browsable API on production?
I'd like to set DEBUG = False in Django, while preserving full Django Rest Framework's Browsable API functionality. I'd like to preserve full functionality for whitelisted IP addresses only. This is how it looks like when DEBUG = True is set: DebugTrue Forms are displayed and working (Raw data and HTML form tabs) Extra actions and OPTIONS buttons are working JSON highlighting is active. I'd like to preserve this functionality on production (for whitelisted IP addresses only). As soon as I set DEBUG to False, I lose it. This is how it looks like when DEBUG = False is set: DebugFalse No forms are displayed Extra actions and OPTIONS buttons are not working JSON highlighting isn't active How to force activate these DRF features while leaving Django in DEBUG = False mode? I'd like to have these features enabled for whitelisted IP addresses. How to achieve this? Thank you!