Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm trying to make a searcher but when i send a request from my frontend in react Django doesn't get the data sent
Sorry for my English. When I'm trying to get the data sent in the frontend (its seems its working well because is generating a json with the searchValue) the function in django is not getting the data that i sent, the print(search) return None This is my code in Django: views.py: @csrf_exempt def search_locations(request): search = request.POST.get('search') print(search) results = [] if search: locations = Location.objects.filter(name=search) print(locations) for location in locations: results.append({ 'id': location.id, 'name': location.name, 'latitude': location.latitude, 'longitude': location.longitude }) return JsonResponse(results, safe=False) urls.py: urlpatterns = [ path('locations/', LocationsView.as_view(), name='locations'), path('locations/search/', search_locations, name='search_locations'), path('locations/<int:pk>/', location_detail, name='location_detail'), ] React code: const [searchValue, setSearchValue] = useState(""); const handleSearch = async (event) => { event.preventDefault(); await axios .post("http://127.0.0.1:8000/apilocations/locations/search/", { search: searchValue, }) .then((response) => { setPlaces(response.data); console.log(searchValue) console.log(response) console.log(places) }) .catch((error) => { console.error(error); }); }; When i use the searcher search return None -
Trying to access the other side of a ForeignKey in the django admin display
I'm working off the django tutorial, and I was trying to figure out how to call the other side of a ForeignKey. My models right now are just Question and Choice, and under class Choice right now I have: question = models.ForeignKey(Question, related_name="choice", on_delete=models.CASCADE) (the only change I made from the tutorial was adding related_name) Then when creating class QuestionAdmin, I added "choice" to list_display, hoping to show choice for a question. list_display = ["question_text", "choice", "pub_date", "was_published_recently"] In the tutorial, they do something with another class and "inlines" but I'm trying to keep this simple, and I was hoping I could just treat the related_name as another attribute of the Choice model. I've tried changing the name, and I get different error messages depending on which admin function I'm using (list_display, fields, etc.) but I'm mostly seeing this: TypeError at /admin/polls/question/ Is there a way to just access the choices as a regular attribute? Am I doing something wrong? -
Issues installing packages from requirements.txt for Django project
I'm working with Python 3.11.3 and I'm having difficulty installing from my requirements.txt file, this is what my output is: https://pastebin.com/0Tcqfjvz This is what my requirements.txt is: asgiref==3.6.0 autopep8==2.0.2 distlib==0.3.6 Django==4.2.1 django-dotenv==1.4.2 environ==1.0 filelock==3.12.0 platformdirs==3.5.0 psycopg2-binary==2.9.6 pycodestyle==2.10.0 python-dotenv==1.0.0 sqlparse==0.4.4 tzdata==2023.3 virtualenv==20.23.0 -
unable to install django debug toolkit
Im new to django and trying to learn the basics, but when i try to install django debug tool kit in a virtual environment the installations keeps on failing and i get an error. is it because i need a specific version of django? im not sure and would appreciate any help. in the terminal i used pipenv install django-debug-toolkit and get this: Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning. Installing django-debug-toolkit... Resolving django-debug-toolkit... Installing... [ =] Installing django-debug-toolkit...[31m[1mError: [0m An error occurred while installing [32mdjango-debug-toolkit[0m! Error text: [36mERROR: Could not find a version that satisfies the requirement django-debug-toolkit (from versions: none) ERROR: No matching distribution found for django-debug-toolkit [0m Installation Failed -
Django DRF validation on GET method
I suppose that DRF framework / django has a better way to do that. class Providers(APIView): def get(self, request): from .doctor_search_helper import DoctorSearchHelper from .gmaps_helper import GMapsHelper localizacao = request.query_params.get("localizacao", None) especialidade = request.query_params.get("especialidade", None) plano = request.query_params.get("plano", None) tipo_estabelecimento = request.query_params.get("tipo_estabelecimento", None) distancia_maxima = request.query_params.get("distancia_maxima", None) if (not localizacao) or (localizacao == ""): return Response({"error": "localizacao is required"}, status=400) if (not especialidade) or (especialidade == ""): return Response({"error": "especialidade is required"}, status=400) if (not plano) or (plano == ""): return Response({"error": "plano is required"}, status=400) if (not plano) or (plano == ""): return Response({"error": "plano is required"}, status=400) if (not distancia_maxima) or (distancia_maxima == ""): return Response({"error": "distancia_maxima is required"}, status=400) Do DRF has any library that supports validation? -
Save data in a real-time application using websocket in Django
I developed a Django application to view live heart rate. For now, I generate the heart rate signal in a Jupyter Notebook and access it in Django using websocket for Python. When the connection with the Websocket closes, I want to record the entire received signal. How do I save this signal? My whole project is build on this model : Real_time_Django_App consumer.py from channels.generic.websocket import AsyncJsonWebsocketConsumer import json class DashConsumer(AsyncJsonWebsocketConsumer): print('==================') async def connect(self): self.groupname='dashboard' await self.channel_layer.group_add( self.groupname, self.channel_name, ) await self.accept() async def disconnect(self,close_code,signal): await self.channel_layer.group_discard( self.groupname, self.channel_name ) async def receive(self, text_data): datapoint = json.loads(text_data) val =datapoint['value'] await self.channel_layer.group_send( self.groupname, { 'type':'deprocessing', #function name to run 'value':val #value to send function } ) print ('>>>>',text_data) async def deprocessing(self,event,signal): valOther=event['value'] #@valOther = f'{valOther}' await self.send(text_data=json.dumps({'value':valOther})) Jupyter Notebook I tried to save each point individualy by accessing the Database in the receive function and modifying the instance stored but given the number of points and frequency at which they are send it doesn't seem to be a viable solution. Is it possible to save all the points send one time before closing the websocket ? Any help would be greatly appreciated! -
Customize the CSS classes passed to django form errors with custom `ErrorList`
I want to utilize Bootstrap for my django project and therefore always pass a CSS class to every form error. Let's name it "custom_class". I read the docs and it tells me that theoretically this setup should work: from django.forms.utils import ErrorList class BootstrapErrorList(ErrorList): error_class = "custom_class" class BaseForm(forms.BaseForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.error_class = BootstrapErrorList class FormA(forms.ModelForm, BaseForm): # ... class FormB(forms.Form, BaseForm): # ... There is no error or anything but also the "custom_class" does not show up in rendered html. This is where I informed myself. I also checked this unanswered "question". -
Folder picker on web application in Django Python
I want to integrate a folder picker on my web application such that when the user uploads a folder, I should be able to retrieve all the files inside it to perform some processing on it. To my knowledge, we CANNOT directly select the folder from web application HTML front end (unlike a file) via simply adding a button for upload (please correct me if I am mistaken here) Thus, I figured out a workaround by integrating JavaScript snippet to my HTML webpage. I am using Microsoft Visual Studio (VS code) to code this. This is what I have tried. I am providing all the required snippets that can be directly used to mimic this scenario: In "folder_processing.html" : <!doctype html> <html lang='en'> <head> <title>Scan Files</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <b> SELECT THE FOLDER FROM CHOOSER BELOW: </B> <br> <form id="scanForm" method="post"> {% csrf_token %} <input type="text" id="folderPathInput" name="folder_path" required readonly> <button type="button" id="selectFolderBtn">Select Folder</button> <button type="submit" name="folder_submit">Scan Folder</button> </form> <script> $(document).ready(function() { $('#selectFolderBtn').click(function() { // Open a file input dialog to select a file $('<input type="file" id="folderInput" style="display:none;">').change(function() { var folderPath = $(this).val(); if (folderPath) { // Set the selected folder path in the input field $('#folderPathInput').val(folderPath); } }).click(); … -
Images is not rendering even after giving the correct directory path in Django. but works when I give incomplete directory
So I have the image that I want to display in my page in a subdirectory 'media'.So I wrote this in my settings.py as recommended everywhere in the internet and documentation: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media/') And when I load the page I get this error: Not Found: /media/media/slider-1.jpg [09/May/2023 19:31:11] "GET /media/media/slider-1.jpg HTTP/1.1" 404 3943 why the path is media/media in my terminal eventhough the MEDIA_ROOT has only one 'media/' So I just wrote: MEDIA_ROOT = os.path.join(BASE_DIR) and this worked perfectly eventhough the image is not inside the base directory but inside the subdirectory called 'media' I'm curious how is this happening. -
How to remove title of inline object in django admin UI
As you can see in the image ,there is an image, there is one 1st model (1st mentioned in image), 2nd model is inlined one. Just wanted to remove the 2nd model title(which is highlighted by red color, complete row I want to delete class NewmodelInline(admin.StackedInline): fields = ['field1', 'field2', 'field3'] extra = 1 model = Newmodel @admin.register(Test) class AuthorAdmin(admin.ModelAdmin): delete_cache_keys_for_model = 'Test' fieldsets = ( (None, { 'fields': ( 'name', 'age', 'lastmod', ), }), ('Numbers', { 'fields': ( 'test1', 'test2', ), }), ) form = TestForm inline_type = 'stacked' inlines = [NewmodelInline] with the help of above code generated a form attached in the image. Now just wanted to remove the title from the admin UI, as attached in image(whole row highlighted with red color and text as 2nd) -
Django admin searchfield with GenericForeignKey
My Django Foo model has the following GenericForeignKey: content_type = models.ForeignKey(ContentType, blank=True, null=True, on_delete=models.SET_NULL) object_id = models.PositiveIntegerField(blank=True, null=True) my_object = GenericForeignKey('content_type', 'object_id') my_objects can be instances of Baz and (rarely) Qux models. The Qux model has a foreign key to Baz. I want to have a searchfield in my Foo admin page that would search by baz_id and yield either instances of Foo that have the Baz of the given ID in my_object field or instances of Foo that have Qux related to the Baz of the given ID. Here's what I'm trying to do: class FooAdmin(...): # some custom classes and mixins here, neither of which overrides get_search_results() query_fields_placeholders = {'object_id': 'Baz ID'} ... ... search_fields = ('object_id',) def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super().get_search_results(request, queryset, search_term) if search_term: baz_content_type = ContentType.objects.get_for_model(Baz) qux_content_type = ContentType.objects.get_for_model(Qux) baz_queryset = queryset.filter( content_type=baz_content_type, object_id=search_term ) related_qux_ids = Subscription.objects.filter(baz_id=search_term).values_list( 'id', flat=True ) qux_queryset = queryset.filter( content_type=qux_content_type, object_id__in=related_qux_ids ) queryset = baz_queryset | qux_queryset return queryset, use_distinct However, what happens is that only Foo instances that have Baz instances as my_objects are returned by the search and those that have Qux instances in my_object fields seem completely ignored (as if the qux_queryset part … -
How can i call an object?
I have got a project with auntification. This is my models.py: class Profile(models.Model): profile_id = models.IntegerField(primary_key=True) last_name = models.CharField(max_length=100) first_name = models.CharField(max_length=100) photo_url = models.URLField() There is a views.py: @login_required def home(request): return render(request, 'home.html') def vk_callback(request): try: vk_user = UserSocialAuth.objects.get(provider='vk-oauth2', user=request.user) vk_profile = vk_user.extra_data user_info = UserInfoGetter(vk_profile['access_token']) pers_id, first_name, last_name, photo_url = user_info.get_vk_info() try: user_profile = Profile.objects.get(profile_id=pers_id) except Profile.DoesNotExist: user_profile = Profile.objects.create( profile_id=pers_id, first_name=first_name, last_name=last_name, photo_url=photo_url ) user_profile.first_name = first_name user_profile.last_name = last_name user_profile.photo_url = photo_url user_profile.save() except UserSocialAuth.DoesNotExist: pass return redirect(home) I need to take pers_id in order to pull out the values of photo, name, last_name in home. How can I do this? -
Error while Dockerizing a simple Django app? (Beginner here)
I'm trying to dockerize my django app whilst following a tutorial, and of course nothing goes as planned hahah. Could you help me understand what's going on and how do i fix it? This is what i did: 1) I made my dockerfile ` `FROM python:3.8-slim-buster ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt RUN pip install psycopg2-binary COPY . . CMD python manage.py runserver 0.0.0.0:80` ` 2) i ran "docker build -t app ." which worked 3) i ran "docker run -p 8888:80 app" but thats when the following issue popped up: 1) I made my dockerfile 2) i ran "docker build -t app ." which worked 3) i ran "docker run -p 8888:80 app" but thats when the issue popped up Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, … -
Unable to test a celery chain when tasks are executed by different celery apps
I have two celery apps in my environment that are : app1 = Celery('app1', broker=BROKER_URL1, backend=BROKER_URL1) app2 = Celery('app2', broker=BROKER_URL2, backend=BROKER_URL2) From a Django app within a web container I need to call a chain of tasks: task1 is executed by app1 task2 is executed by app2 The two apps have different virtual environments / python versions so there no way of executing both tasks by the same app. @app1.task(bind=False) def task1(): return {"key": "value"} @app2.task(bind=False) def task2(result): return result["key"] task_chain = ( app1.signature('app1.task1') | app2.signature('app2.task2') ) I am then trying to test the chain works correctly - task1 appears to execute correctly but task2 errors: @override_settings(CELERY_TASK_ALWAYS_EAGER=True) def test_chain(self): task_chain.apply_async().get() # Error: celery.exceptions.NotRegistered: 'app2.task2' How can i test this chain? -
JWT How to mock JWT token authentication?
I'm writing unit tests in Django where I have to mock JWT token validation. I used the following code but it throws exception. I suspect the issue is because I'm unable to use decode method because jwt.encode returns a str value which does not have decode method. But in the sample I came across, jwt.encode returns bytes. helper def generate_jwt_token(): client_secret = getattr(settings, "AUTH0_CLIENT_SECRET", None) payload = {'user_id': 1} token = jwt.encode(payload, client_secret, algorithm='HS256') #Commenting the following line because jwt.encode returns str and str does not #have decode method #return token.decode('utf-8') return token Unit test @patch('jwt.decode') def test_post_request_with_valid_data_succeeds(self, mock_decode): payload1 = {'user_id': 1} mock_decode.return_value = payload1 response = self.client.post(self.url, self.dataset, format="multipart", HTTP_AUTHORIZATION=f'Bearer {self.token}') Exception Traceback (most recent call last): File "/usr/local/lib/python3.8/unittest/mock.py", line 1325, in patched return func(*newargs, **newkeywargs) File "/app/apps/datasets/test/test_views.py", line 89, in test_post_request_with_valid_data_succeeds response = self.client.post(self.url, self.dataset, format="multipart", HTTP_AUTHORIZATION=f'Bearer {self.token}') File "/root/.local/lib/python3.8/site-packages/rest_framework/test.py", line 296, in post response = super().post( File "/root/.local/lib/python3.8/site-packages/rest_framework/test.py", line 210, in post return self.generic('POST', path, data, content_type, **extra) File "/root/.local/lib/python3.8/site-packages/rest_framework/test.py", line 234, in generic return super().generic( File "/root/.local/lib/python3.8/site-packages/django/test/client.py", line 473, in generic return self.request(**r) File "/root/.local/lib/python3.8/site-packages/rest_framework/test.py", line 286, in request return super().request(**kwargs) File "/root/.local/lib/python3.8/site-packages/rest_framework/test.py", line 238, in request request = super().request(**kwargs) File "/root/.local/lib/python3.8/site-packages/django/test/client.py", line 719, in … -
Django ORM: This queryset contains a reference to an outer query and may only be used in a subquery
In the queryset, I want to get the average of what subquery returns and then group by 'store_id' and 'avg_sales'. However, when I used the following queries: subquery = StoreStatistics.objects.filter( store=OuterRef("store_id"), products__in=products, # list of ids created_date__gte='2023-01-01', ).annotate( month=TruncMonth("created_date") ).values( "month", "store" ).annotate( avg_sales_per_month=Avg("quantity") ) queryset = Company.objects.filter( company_id=company_id ).annotate( avg_sales=Subquery(subquery.aggregate(Avg("avg_sales_per_month"))) ).values( "store_id", "avg_sales" ) I got the following error: This queryset contains a reference to an outer query and may only be used in a subquery. Can anyone tell where am I making a mistake? -
Django migration error (SQL to PostgreSQL): return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable
I created a dump.json file from my SQL local DB. After that, I uploaded my file to the server prepared for PostgreSQL and I caught the following error after using the following commands: python3 manage.py shell >>> from django.contrib.contenttypes.models import ContentType >>> ContentType.objects.all().delete() >>> quit() python manage.py loaddata dump.json My error: Traceback (most recent call last): File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "posts_group" does not exist LINE 1: UPDATE "posts_group" SET "title" = 'Котики', "slug" = 'cats'... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/farexzon/hw05_final/yatube/manage.py", line 21, in <module> main() File "/home/farexzon/hw05_final/yatube/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/core/management/commands/loaddata.py", line 114, in loaddata self.load_label(fixture_label) File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/core/management/commands/loaddata.py", line 181, in load_label obj.save(using=self.using) File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/core/serializers/base.py", line 223, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/db/models/base.py", line 780, in save_base updated = self._save_table( File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/db/models/base.py", line 853, in _save_table updated = self._do_update(base_qs, using, pk_val, values, update_fields, File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/db/models/base.py", … -
NoReverseMatch at /detail/3/
I have multiple todo lists, and each todo list has list items. There is a completed field in the list item model. I get this error in the detail page when I put a form to handle if the list item has been completed by the logged in user. The error I get is: NoReverseMatch at /detail/3/ Reverse for 'completed_list_item' with arguments '('', '')' not found. 1 pattern(s) tried: ['completed\\-item/(?P<list_pk>[0-9]+)/(?P<item_pk>[0-9]+)/\\Z'] Request Method: GET Request URL: http://127.0.0.1:8000/detail/3/ Django Version: 4.1.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'completed_list_item' with arguments '('', '')' not found. 1 pattern(s) tried: ['completed\\-item/(?P<list_pk>[0-9]+)/(?P<item_pk>[0-9]+)/\\Z'] Exception Location: C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix Raised during: List.views.detail The traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/detail/3/ Django Version: 4.1.4 Python Version: 3.10.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'List', 'Chats', 'django.contrib.humanize', 'crispy_forms', 'crispy_bootstrap5'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\Fubara\Desktop\Desk\Web Dev\Django\TodoApp\Templates\detail.html, error at line 38 Reverse for 'completed_list_item' with arguments '('', '')' not found. 1 pattern(s) tried: ['completed\\-item/(?P<list_pk>[0-9]+)/(?P<item_pk>[0-9]+)/\\Z'] 28 : <h4 class="card-title">{{todo_list.title}}</h4> 29 : <p class="card-text">{{todo_list.description|linebreaksbr}}</p> 30 : <ul class="center list-unstyled"> 31 : <!-- {% comment %}{% endcomment %} --> 32 : {% for item in list_items %} 33 : … -
Cookiecutter : Stop the execution of the cookiecutter if user gives no as input to one parameter
Cookiecutter.json has a parameter which accepts "yes" or "no": { "test" : [ "yes", "no"] } if user selects "yes" then it should continue accepting the inputs further, if not it should stop. The same logic is included in pre_gen_project.py under hooks folder. try: if "{{ cookiecutter.test }}" == "yes": cookiecutter.prompt.read_user_variable("full_name","your_synthetic_test_name") else: sys.exit(0) except Exception as ex: print("Exception in pre_gen_project script") Problem here is , it is entering the else condition , but the cookie cutter execution is not stopping here. Any suggestion , Let me know. Thank you. -
Migrating 'openapi.Schema()' from drf-yasg to drf-spectacular
I'm migrating from drf-yasg to drf-spectacular, using the From drf-yasg to OpenAPI 3, and I've done most of my docs, but I have some problems triying to replace my old openapi.Schema(). By the docs Schema is not required and can be eliminated. Use a plain dict instead, but I'm not sure how to fit this dict when you have nested objects, for example, my code originaly was: @swagger_auto_schema( operation_summary="Text", operation_description="More text", request_body=openapi.Schema( "body", "Body params", openapi.TYPE_OBJECT, properties={ "params": openapi.Schema( type=openapi.TYPE_ARRAY, items=openapi.Items( type=openapi.TYPE_OBJECT, properties={ "param1": openapi.Schema(type=openapi.TYPE_INTEGER), "param2": openapi.Schema(type=openapi.TYPE_STRING), }, ), ) }, ), responses={ 200: openapi.Response( "Response", openapi.Schema( "response", type=openapi.TYPE_OBJECT, properties={ "status": openapi.Schema(type=openapi.TYPE_STRING, default="ok"), "details": openapi.Schema(type=openapi.TYPE_STRING), }, ), ), }, tags=["example"], I'm not sure how to deal with the type=openapi.TYPE_OBJECT and include the array type (I know about the many=True but again, not how to fit it in the dict). By the docs, it should go something like this? But where I should use the many=True here for the array? request={ "params": { "param1": OpenApiTypes.INT, "param2": OpenApiTypes.STR, } }, -
Run development server using django exe
I have been trying to run the exe file(created using pyInstaller) of my django project on the development server so that I can verify whether the it is working properly or not. Tried some commands and also asked Chatgpt but could find any suitable solution. The commands that I have tried: Input: manage.exe runserver Response: File "manage.py", line 11, in <module> File "manage.py", line 10, in main File "django\core\management\__init__.py", line 446, in execute_from_command_line File "django\core\management\__init__.py", line 440, in execute File "django\core\management\base.py", line 402, in run_from_argv File "django\core\management\commands\runserver.py", line 74, in execute File "django\core\management\base.py", line 448, in execute File "django\core\management\commands\runserver.py", line 111, in handle File "django\core\management\commands\runserver.py", line 118, in run File "django\utils\autoreload.py", line 682, in run_with_reloader File "Lib\site-packages\PyInstaller\hooks\rthooks\pyi_rth_django.py", line 23, in _restart_with_reloader File "django\utils\autoreload.py", line 272, in restart_with_reloader File "django\utils\autoreload.py", line 259, in get_child_arguments RuntimeError: Script runserver does not exist. [19796] Failed to execute script 'manage' due to unhandled exception! Input: manage.exe runserver 127.0.01:8000 (Derived after running "manage.exe help runserver") Response: Same as above -
How Become a Successful Software developer and actually land a job [closed]
I have been coding since I was in 9th grade started with python and now I just passed 12th, to be straight forwards my question is what are the things that I have to do to actually land a job in tech industry. I know a lot about python and it's modules and I'm also familier with front end web development using django and react -
How to pass into a variable what was created [closed]
View and receiver I want to pass what was added to the message variable. How to do it? Looked in the documentation, but without success. -
Django JSONField with arrays filtering by substring
I've got a events JSONField in my model and I want to filter by value on key. Example object creation: MyModel.objects.create( name="test", events=[ {"type": "created", "info": "xxx"}, {"type": "sent", "info": "abc"}, ] ) So in events I have a list of events with same keys but different value. I want to filter by name and info values for doing autocompletion feature - so I need to filter by string icontains in info. What I figured out is MyModel.objects.filter(Q(name__icontains='abc') | Q(events__info__0__icontains='abc')) but it takes only first event from a list - if info match in second element then it is not placed in results. Is it possible to do with django orm? I want something like MyModel.objects.filter(Q(name__icontains='abc') | Q(events__info__<all>__icontains='abc')) -
Django: How to automatically restart gunicorn after my code changed
I'm developing a Django website, in which top menu should reflect changes in the page structure. In some sections (such as "About") changes are rare, so the menu is kept as a separate HTML file, which is included into the base template base.html: {% include "includes/menu_about.html" %} Although this works, there is a problem: the server doesn´t "see" that my menu_about.html file has changed, and, apparently, shows the page from cash, so the user doesn´t see the updated menu until I manually restart Gunicorn server. How is it possible to solve this problem? Looks like I have to make Gunicorn to restart automatically each time after my "Page" model saved. Perhaps, there is certain command in Django, which can be run on model save and restart the Gunicorn? Or may be certain settings in the Gunicorn itself?