Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ORA-12170: TNS:Connect timeout occurred on docker container
Im building a project which connect to a oracleDB remotely using a VPN, the backend is python with django and I dockerized the project until fridays last week everything was working well, after that when i run docker compose up I get this error: django.db.utils.DatabaseError: ORA-12170: TNS:Connect timeout occurred The dockerfile has following structure: FROM python:3.10.12-alpine3.18 ENV PYTHONUNBUFFERED 1 RUN apk add --update --no-cache\ build-base jpeg-dev zlib-dev libjpeg\ gettext\ py3-lxml\ py3-pillow\ openldap-dev\ python3-dev\ gcompat\ && rm -rf /var/cache/apk/* RUN apk add --no-cache libaio libnsl libc6-compat curl bash WORKDIR /opt/oracle RUN wget https://download.oracle.com/otn_software/linux/instantclient/instantclient-basiclite-linuxx64.zip && \ unzip instantclient-basiclite-linuxx64.zip && \ rm -f instantclient-basiclite-linuxx64.zip && \ cd instantclient* && \ rm -f *jdbc* *occi* *mysql* *jar uidrvci genezi adrci && \ mkdir /etc/ld.so.conf.d && \ echo /opt/oracle/instantclient* > /etc/ld.so.conf.d/oracle-instantclient.conf RUN ldconfig /etc/ld.so.conf.d ENV LD_LIBRARY_PATH=/opt/oracle/instantclient_21_11 ENV PATH=/opt/oracle/instantclient_21_11:$PATH RUN echo 'INPUT ( libldap.so )' > /usr/lib/libldap_r.so The DB connection is: DATABASES = { "default": { "ENGINE": "django.db.backends.oracle", "NAME": ( f"{env('DATABASE_SERVER')}:{env('DATABASE_PORT')}/{env('DATABASE_SERVICE_NAME')}" ), "USER": env("DATABASE_USER"), "PASSWORD": env("DATABASE_PASS"), } } What seems more strange to me is that I can perfectly connect to the DB via DBeaver (client) and another test is that I pinged the IP of the DB server and I have a response but, if … -
How to upadate a text for H2 tag from views.py in django
I have the buttons defined in html file. When I click on the button iam sending the name of the button using post request using Ajax and getting it to the views.py , saving it in 'catogory_type'. When iam printing it in the terminal, it is getting printed. But when iam rendering the page, that H2 tag is showing empty without any text. How can I print that value in the page when I clicked on the button. Asper my understanding, after clicking the button in the page, it is not getting reloaded. Iam not sure how to refresh the page to re-render it with updated data again. Please suggest me on this. Thanks:) Need to get the the page refresh with updated data in django. -
python django factory set random locale and then create model based on this locale
I would like to create test models of people of different nationalities. During creation, factory would randomly select nationality from a list of "locale" attributes. It would then determine personal attributes based on the previously drawn nationality. Here is my code, which does not work. It mixes attributes of different nationalities class PersonModelFactory(factory.django.DjangoModelFactory): locale = factory.fuzzy.FuzzyChoice(["cs_CZ", "da_DK", "de_DE", "en_GB", "es_ES", "fr_FR", "hr_HR", "hu_HU", "it_IT", "nl_NL", "no_NO", "pt_BR", "pt_PT", "ro_RO", "sk_SK", "fr_CH", "pl_PL", "de_AT", "es_AR"]) class Meta: model = Person exclude = ("locale",) first_name = factory.Faker("first_name_male", locale=locale) last_name = factory.Faker("last_name_male", locale=locale) nationality = factory.Faker("current_country", locale=locale) ...and so on... In addition, it would be best if half of the people could be British, another half as other mixed nationalities. I tried this code to do so: locale = factory.fuzzy.FuzzyChoice(["en_GB", None]) if locale is None: locale = factory.fuzzy.FuzzyChoice([...]) Unfortunately, only the first line of code is is read and the program only chooses between en_GB and None (which is en_US by default). If statement is ignored. -
I want Small Modal but my modalis not worrk properley as I want
<!-- Modal --> <div class="modal fade" id="deleteItemModal" tabindex="-1" role="dialog" aria-labelledby="deleteItemModalLabel" aria-hidden="true"> <div class="modal-sm modal-dialog " role="document"> </div> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body confirm-delete text-center" > <div class="alert" id="delete_item_alert"></div> <div id="modal-message"></div> <hr> <form action="" method="post" id="form_confirm_modal"> {% csrf_token %} <button type="button" class="btn btn-danger" data-dismiss="modal" id="confirmButtonModal">Delete</button> <button type="button" class="btn btn-primary" data-dismiss="modal">close</button> </form> <input type="hidden" id="address_suppress"/> </div> </div> </div> <div class="modal-body confirm-delete text-center" > <div class="alert" id="delete_item_alert"></div> <div id="modal-message"></div> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', () => { let form_confirm = document.querySelector('#form_confirm_modal') let buttons = document.querySelectorAll("[data-target='#deleteItemModal']"); buttons.forEach(button => { button.addEventListener("click", () => { // extract texts from calling element and replace the modals texts with i if (button.dataset.message) { document.getElementById("modal-message").innerHTML = button.dataset.message; } // extract url from calling element and replace the modals texts with it if (button.dataset.url) { form_confirm.action = button.dataset.url; } }) }); let confirmModal = document.getElementById("confirmButtonModal") confirmModal.addEventListener('click', () => { form_confirm.submit(); }); }); </script> I want modal popup delete confirmation ,The modal is work properley but it is too large i need small modal. I have the above modal ,I use class .modal-sm but it doesnot work .please help me. I want modal popup delete confirmation ,The modal is work properley but it … -
Errno 13 Permission denied: 'images' on Production environment
I'm facing an issue with file permissions when trying to access an AWS S3 bucket in my Django application. Everything works perfectly in my local development environment. However, when I deploy the application to my production environment, I encounter a "Permission Denied" error when trying to read/write from the 'images' directory in the S3 bucket. Locally, I see successful GET and POST requests in my logs, and the S3 URLs are generated as expected. In production, I get an error message saying "Exception in generate_diamond_painting_preview: [Errno 13] Permission denied: 'images'." I've checked my IAM policies and S3 bucket policies, and they seem to allow for the necessary actions. I'm at a loss for what could be causing this discrepancy between my local and production environments. Local Environment Testing: Verified that the S3 bucket interaction works as expected in my local development environment. Files are read and written without any issues. AWS IAM Policy: Reviewed the IAM policy attached to the role/user used by the Django application. The policy allows for full S3 access to the specific bucket and its contents (s3:*). Server Logs: Checked the logs in the production environment to pinpoint the error, which led me to the "Permission … -
Django forms Choicefield parameter session key
I am working on a project which bases operations on the session_key parameter. I would like to fetch data from the database and add the variables into a choicefield in forms. Using the ModelChoiceField(queryset=..., empty_label="(Nothing)") could be an option, but i still cant take in the session_key as a parameter to filter the queryset. so my question, how can i fetch the session_key from the request in views and pass it to the queryset in the forms class? Thx! -
Django Admin: IntegrityError When Adding New or Modifying Existing Models From Django Admin Panel in Browser
I'm encountering a peculiar issue when attempting to add or update existing models through the Django Admin panel. It results in the following error: IntegrityError at /admin/main/user/2/change/ FOREIGN KEY constraint failed Here are the details: Django Version: 4.2.4 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed Exception Location: C:\Users\Administrator\Desktop\oracle\Site #041\site\env\Lib\site-packages\django\db\backends\base\base.py, line 313, in _commit Occurred during: django.contrib.admin.options.change_view Python Version: 3.12.0 Python Executable: C:\Users\Administrator\Desktop\oracle\Site #041\site\env\Scripts\python.exe This error happens when I try to update or add data to an existing model. However, it's worth noting that when I update or add new data using my custom admin interface, everything works as expected. I'm seeking assistance in understanding the root cause of this issue and how to resolve it. Any guidance would be greatly appreciated. -
Htmx POST for Editable Row
I am trying to do an editable row with Django and HTMX. I have trouble editing rows. When I click the edit button, form appears instead of row. I click save after edit fields, nothing happens. Why is there no POST operation? Here is my code edit_link_form.html <td> <form hx-post="{% url 'link:link_update' pk=object.pk %}"> {% csrf_token %} {% load crispy_forms_tags %} {% for field in form %} <td colspan="{{ form|length }}"> <div class="form-row"> <div class="form-group col-md-12"> {{ field|as_crispy_field }} </div> </div> </td> {% endfor %} <td> <button type="submit" class="btn">Submit</button> </td> <td> <button class="btn btn-primary" type="button">Cancel</button> </td> </form> </td> Here is my row.html <tr id="link_list_{{link.pk}}"> <td>{{ link.title }}</td> <td>{{ link.get_full_url }}</td> <td> <span class="p-1 border fs-12 rounded text-light bg-primary"> <a href="{{ link.category.get_absolute_url }}" class="text-decoration-none text-light"> {{ link.category }} </a> </span> </td> <td> {% for shortcode, tags in tags_by_shortcode.items %} {% if shortcode == link.shortcode %} {% for tag in tags %} <li class="list-inline-item border p-1 text-muted fs-12 mb-1 rounded"> <a href="{{ tag.get_absolute_url }}" class="text-decoration-none text-muted"> {{ tag.title }} </a> </li> {% endfor %} {% endif %} {% endfor %} </td> <td> <button class="btn btn-warning" hx-get="{% url 'link:link_update' pk=link.pk %}" hx-target="#link_list_{{link.pk}}"> Edit </button> </td> <td> <button class="btn btn-danger btn-sm float-end" hx-delete="{% url … -
How to generate server code from an OpenAPI Specification (OAS) in Django Rest Framework?
I'm working on a Django Rest Framework project, and I have an OpenAPI Specification (OAS) file that I'd like to use for code generation. My goal is to automatically generate API endpoints, serializers, and views from this OAS file. I'm seeking guidance on how to generate Django Rest Framework code (serializers, views, URLs) based on the OAS file. I'd like to know which tools or libraries are commonly used for this purpose and any steps or configurations I need to follow. Additionally, any tips or best practices for integrating OAS with Django Rest Framework would be greatly appreciated. I've read through the documentation for Django Rest Framework and searched for relevant resources online, but I haven't found a clear path for integrating OAS with Django Rest Framework. Thank you for any guidance or suggestions you can provide! https://spec.openapis.org/oas/v3.1.0 -
displaying a product and all related comment to the product and add new comment form in a single template
I am creating a web store using Django. i want to have a page displays a chosen product and within that page i want to see all the comment related to that specific product and also want to have a form for customers to add new comment for the product. I used class-based list-view and detail-view but the problems are 1- i could not displays related comments using class-based views(actually i could display it by creating a query_set and using template tags) 2- i could not render add new comment form into my template here is my code models.py class Goods(models.Model): goods_main_band = models.ForeignKey( MainBranch, to_field='mb_code', on_delete=models.CASCADE, verbose_name='کد دسته اصلی', default=0 ) goods_sub_band1 = models.ForeignKey( SubBranch1, to_field='sb1_code', on_delete=models.CASCADE, verbose_name='کد دسته فرعی 1', default=0 ) goods_sub_band2 = models.ForeignKey( SubBranch2, to_field='sb2_code', on_delete=models.CASCADE, verbose_name='کد کالا', default=0 ) goods_properties = models.OneToOneField( GoodsProperties, on_delete=models.CASCADE, verbose_name='مشخصات کالا', null=True, blank=True ) goods_specifications = models.OneToOneField( GoodsSpecification, on_delete=models.CASCADE, verbose_name='معرفی کالا', default=0, null=True, blank=True ) name = models.CharField(verbose_name='نام کالا') image = models.ImageField(upload_to='photos/%Y/%m/%d', null=True, blank=True, verbose_name='تصویر کالا') quantity = models.PositiveIntegerField(default=0, verbose_name='تعداد موجود') price = models.DecimalField( decimal_places=0, max_digits=12, default=0, verbose_name='قیمت کالا' ) discount = models.SmallIntegerField(null=True, blank=True, verbose_name='میزان تخفیف') seller = models.ManyToManyField('Seller', verbose_name='کد فروشنده') def __str__(self): return self.name class Comments(models.Model): goods = models.ForeignKey(Goods, … -
Storing 'formattable' strings in database
I'm working on a project where I need to store certain descriptions in a database. These descriptions need to be strings akin to prepared statements in SQL, where I can later 'inject' my own values wherever necessary. The reason is that the data that goes in the fields needs to be generated by the backend on demand (also the descriptions will potentially be localized later on). Currently I'm simply storing the descriptions in the form of "This is the description for {} and {}" and in the backend I call .format on it to pass the generated values. It's probably worth noting that the user can't interact with this procedure, meaning it shouldn't really be a security hole. However, is there a better way of doing this in Django? Or is my design somehow flawed? Thanks. -
Maintaning isolation between modules in Django monolith
In our company, we have a monolith. Right now is not that big but we are already seeing some problems with the isolation between the modules we have. Our setup is pretty similar to other Django backends: we have a common User model and another UserProfile model where we store additional information about the user. As an additional thing, we also have a company model to group our users by company. These models are shared across all the modules, at least they are coupled as foreign keys in the models of the rest of the modules. They are contained in a companies module, where we have our business rules about how many users a company can have, invariants in their profile, etc. I think this is fine because we usually just do simple and fast join by user ID or filter by it, so we treat this dependency as read-only so we don't skip any business rules/boundaries related to the companies module. My problem comes when, for instance, some moduleA, needs to trigger an application service in moduleB. For instance, let's say moduleB needs to access a resource in moduleA. The code would be something like: # The GetResourceInterface is … -
Django Migrations are not Migrating on production
I am using MySql DB,I am having some problems with the migrations.When I am running python manage makemigrations it creates a migration file with the old field migrations also,and when I run python manage migrate I get "No migrations to apply",but when i check the db,fields are absent.I had this problem recently but --fake worked for it,Now when I am faking it also gives "No migrations to apply".I am working On production server so I don't think deleting migration files and resetting db is a good solution.Maybe someone can help me with that,Thank in advance! This is the migrations file which it created for me now,I only added cancellation_note and Iban fields now. class Migration(migrations.Migration): dependencies = [ ('auths', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='customuser', name='bank_account_iban', ), migrations.RemoveField( model_name='customuser', name='bank_account_name', ), migrations.RemoveField( model_name='customuser', name='bank_account_name_on_card', ), migrations.RemoveField( model_name='customuser', name='social_media_account', ), migrations.AddField( model_name='customuser', name='cancellation_note', field=models.CharField(blank=True, max_length=255), ), migrations.AddField( model_name='customuser', name='iban', field=models.CharField(blank=True, max_length=255), ), migrations.CreateModel( name='payze_saved_cards', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('CardToken', models.CharField(max_length=255, null=True)), ('CardMask', models.CharField(max_length=255, null=True)), ('CardBrand', models.CharField(max_length=255, null=True)), ('CardCountry', models.CharField(max_length=255, null=True)), ('CardHolder', models.CharField(max_length=255, null=True)), ('ExpirationDate', models.CharField(max_length=255, null=True)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] -
How to django orm get value anyone in query multi dictionary
Hi I want get model data with django orm. Mymodel, Security Field have multiple dictionary in list. if group_id = sg-1111222222 , i will get below data. So, I want to find a value that matches at least one of several dictionaries. [ { "GroupId": "sg-12345", "GroupName": "test1" }, { "GroupId": "sg-1111222222", "GroupName": "test2" } ] -
when i use axios of vue,don't get session in django
When I use axios in vue to send a request, django can get the request, but it cannot return the value in request.session. The return value of axios is always null. I tried many methods on the Internet but couldn't find a solution This is my axios request import axios from "axios"; export default function(){ axios.get("/api/session/", { withCredentials: true }) .then((response) => { console.log('err:', response.data); }) .catch((error) => { console.error('err:', error); }); } This is my function to handle requests class GetSession(APIView): def get(self, request): session_data = request.session.get("self_data") return Response({"statue": True, "session": session_data}) def post(self, request): session_data = request.session.get("self_data") return Response({"statue": True, "session": session_data}) I also set settings.py in django """ Django settings for transfer project. Generated by 'django-admin startproject' using Django 3.2.10. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os ALLOWED_HOSTS = ['*'] BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-0u0t-zy!qkafw1dn65ce662z%s8o(j)_#m)ewm5)ypn7ew8=vz' DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'app01.apps.App01Config', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'transfer.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', … -
What is the best approach to handle long tasks in a django app
So I have one function where clients uploads files and does a little parsing and then proceeds to send these results using another API. Now each file takes around 30 seconds to complete and a large deal of that is a POST request im making and awaiting an answer for 25 seconds. My initial solution was that when a client sent a request about this particular function of my app I'd just loop through all those files until the task was completed and then sent back a http response. Of course I noticed that I started getting 504 error because it was taking too long. My second, and current, solution is to respond with a http response immediately containing an empty html page where I then use javascript to use fetch to make calls to this function(a django view) and continually update the page and tell the client that a file has been processed. I also introduced threads to this solution and to my surprise it made it a lot faster, I suppose that is because each thread can get to that point where it waits for the long POST request so going from one to two almost doubled the … -
TemplateSyntaxError : Could not parse the remainder: '(ticket.status' from '(ticket.status'
when i use this condition it gives an syntax error like this TemplateSyntaxError at /developers/dev_pendings/Could not parse the remainder: '(ticket.status' from '(ticket.status'Request Method: GETRequest URL: http://127.0.0.1:8000/developers/dev_pendings/Django Version: 4.2.6Exception Type: TemplateSyntaxErrorException Value: Could not parse the remainder: '(ticket.status' from '(ticket.status'Exception Location: C:\Users\x\Desktop\lspok\vnv\Lib\site-packages\django\template\base.py, line 703, in initRaised during: Developers.views.devPendingsDashboardPython Executable: C:\Users\x\Desktop\lspok\vnv\scripts\python.exePython Version: 3.11.3Python Path: ['C:\Users\x\Desktop\lspok\pokeus','C:\Users\x\AppData\Local\Programs\Python\Python311\python311.zip','C:\Users\x\AppData\Local\Programs\Python\Python311\DLLs','C:\Users\x\AppData\Local\Programs\Python\Python311\Lib','C:\Users\x\AppData\Local\Programs\Python\Python311','C:\Users\x\Desktop\lspok\vnv','C:\Users\x\Desktop\lspok\vnv\Lib\site-packages']Server time: Wed, 18 Oct 2023 11:44:14 +0530' The code i used like this : {% elif (ticket.status == 'DA' or ticket.status == "CD" ) and ticket.tester_id != '' %} Why this happening, isn't it right way in Django? I just want evaluate this condition correctly -
While using DRF APIView with drf_yasg appears additional POST query, that i have not defined
I have got this urls urlpatterns = [ path('users/', UserApiView.as_view()), path('users/<str:pk>/', UserApiView.as_view()), ] and APIView class: class UserApiView(APIView): @swagger_auto_schema( request_body=CreateUserSerializer, responses={'200': openapi.Response('response description', DetailUserSerializer(many=True))} ) def post(self, request): user_data = CreateUserSerializer(request.data) user_data.is_valid(raise_exception=True) new_user = user_data.save() return Response(DetailUserSerializer(new_user).data) @swagger_auto_schema( responses={'200': openapi.Response('response description', DetailUserSerializer)} ) def get(self, request): queryset = UserRepo().get_all() serializer = DetailUserSerializer(queryset, many=True) return Response({'data': serializer.data}) @swagger_auto_schema( responses={'200': openapi.Response('response description', DetailUserSerializer(many=True))} ) def get(self, request, pk=None): queryset = UserRepo().get_all() user = get_object_or_404(queryset, pk=pk) serializer = DetailUserSerializer(user) return Response(serializer.data) but in swagger i see extra /users/{id}/ POST query (it's the last one) enter image description here I tried to find something in drf_yasg docs, but it was not successful -
Django Rest Framework with TensorFlow: Server Error on Model Training Endpoint
I'm building a web application using Django Rest Framework (DRF) to train a TensorFlow model and then use that model for text prediction. I have separated the training and prediction into two APIViews: TrainModelView and TextGenerationView. When I hit the /train_model/ endpoint, I am getting a 500 Internal Server Error. The error logs show: ERROR:django.request:Internal Server Error: /train_model/ [17/Oct/2023 21:42:28] "POST /train_model/ HTTP/1.1" 500 72 Here's the relevant part of my DRF view: python class TrainModelView(APIView): # ... [Your Code Here] def post(self, request, *args, **kwargs): data_path = r"C:\Users\hp\Downloads\models\urlsf_subset00-7_data\0006004-f940b83d9ed9a19f39d18df04679b071.txt" train_data, train_labels, tokenizer = data_preprocessing.preprocess_txt_data(data_path) # ... [Rest of Your Code] What I have tried so far: Checked the data path and ensured that the file exists. Tested the model training function separately, and it seems to be working fine. What I have tried so far: Checked the data path and ensured that the file exists. Tested the model training function separately, and it seems to be working fine. -
dj-rest-auth - Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name
I am using dj-rest-auth, and after following the documentation exactly how it is, when I go to the password/reset api endpoint, and enter my email, it return this error: NoReverseMatch at /api/dj-rest-auth/password/reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Request Method: POST Request URL: http://127.0.0.1:8000/api/dj-rest-auth/password/reset/ Django Version: 4.2.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Exception Location: /Users/coding/Projects/django/user_template_api/.venv/lib/python3.12/site-packages/django/urls/resolvers.py, line 828, in _reverse_with_prefix Raised during: dj_rest_auth.views.PasswordResetView Python Executable: /Users/coding/Projects/django/user_template_api/.venv/bin/python3 Python Version: 3.12.0 Python Path: ['/Users/coding/Projects/django/user_template_api/backend', '/Library/Frameworks/Python.framework/Versions/3.12/lib/python312.zip', '/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12', '/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/lib-dynload', '/Users/coding/Projects/django/user_template_api/.venv/lib/python3.12/site-packages'] Server time: Wed, 18 Oct 2023 01:59:54 +0000 this is my accounts/urls.py from django.urls import include, path from rest_framework import routers from .views import CustomUserViewSet from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) router = routers.DefaultRouter() router.register(r'users', CustomUserViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), ] this is my settings.py """ Django settings for backend project. Generated by 'django-admin startproject' using Django 4.2.1. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path # Build paths inside … -
Writing your first Django app, part 5 error import models
I’m doing the first django application tutorial, I’m in part 05 and I’m having problems with “tests.py”, when I run “python manage.py test polls”, it returns the following error message: “RuntimeError: Model class mysite.polls.models.Question doesn’t declare an explicit app_label and isn’t in an application in INSTALLED_APPS.” However, ‘polls.apps.PollsConfig’ has already been added to INSTALLED_APPS, and the error continues to appear. I started “from polls.models import Question”, I managed to start the entire test through the shell, but in tests.py it gives this error I want the error to go away so I can run the necessary tests and continue the django tutorial -
Response Data from Django API not Fetching correctly, got an empty array #React,
I have the following data in the API in the backend (does this mean that I have backend well settled??): enter image description here And I'd like to display them in the frontend something like this: enter image description here Instead, I got the following empty page: enter image description here The structure of the folder is: enter image description here And the code of api.js file is the following: import { toast } from 'react-toastify'; function request(path,{ data = null, token = null, method = "GET"}) { return fetch(path, { method, headers: { Authorization: token ? `Token ${token}` : "", "Content-Type": "application/json", }, body: method !== "GET" && method !== "DELETE" ? JSON.stringify(data) : null, }) .then((response) => { console.log(response) // If it is success if(response.ok) { if (method === "DELETE") { // if delete, nothing return return true; } return response.json(); } //Otherwise, if there are errors return response .json() .then((json)=>{ // Handle Json Error, response by the server if (response.status === 400) { const errors = Object.keys(json).map( (k) => `${(json[k].join(" "))}` ); throw new Error(errors.join(" ")); } throw new Error(JSON.stringify(json)); }) .catch((e) => { if (e.name === "SyntaxError") { throw new Error(response.statusText); } throw new Error(e); }) … -
simplejwt token work for all tenants for django-tenants
I just want to mention about my problem. I have already researched many documents but I could not find any solution. I just try to use django-tenants. Everything seems OK. But If any user gets the token after login, that token works for all tenants. It's a big leak of security. I have been thinking about an idea SIGNING_KEY. If I can change SIGNING_KEY for each tenant, it may be fixed. But It did not. class TenantJWTAuthenticationMiddleware(MiddlewareMixin): def process_request(self, request): tenant = Client.objects.get(schema_name=connection.schema_name) jwt_secret_key = tenant.jwt_secret_key settings.SIMPLE_JWT['SIGNING_KEY'] = jwt_secret_key This is my Middleware to change SIGNING_KEY for each tenant. class Client(TenantMixin): name = models.CharField(max_length=100) paid_until = models.DateField() on_trial = models.BooleanField() created_on = models.DateField(auto_now_add=True) jwt_secret_key = models.CharField(max_length=100, null=True, blank=True) # default true, schema will be automatically created and synced when it is saved auto_create_schema = True class Domain(DomainMixin): pass This is my model. So, I added jwt_secret_key into my model and I got this field in Middleware and tried to set SIGNING_KEY for jwt. But still, jwt after user login can be used for all tenants. Does anyone have any idea about my problem? Any suggestion or amendment to my solution? Thanks. -
how to refresh the page without reloading, using django, ajax, jquerry?
So I am trying to delete products from cart without refreshing the entire page, I can delete an item and then I need to reload the page to delete another item. I am using Django, jQuery and AJAX to attain the desired result after going through questions of similar nature. In another branch I have implemented the auto refresh feature, whereby after deletion the page automatically reloads but it is not a great user experience. Any help will be greatly appreciated. here's my views.py delete item from cart function def delete_item_from_cart(request): cart_total_amt = 0 product_id = str(request.GET['id']) if 'cart_data_obj' in request.session: if product_id in request.session['cart_data_obj']: cart_data = request.session['cart_data_obj'] del request.session['cart_data_obj'][product_id] request.session['cart_data_obj'] = cart_data if 'cart_data_obj' in request.session: for p_id, item in request.session['cart_data_obj'].items(): cart_total_amt += int(item['qty']) * float(item['price']) context = render_to_string("core/async/cart-list.html", {"cart_data":request.session['cart_data_obj'], 'totalCartItems':len(request.session['cart_data_obj']), 'cart_total_amount':cart_total_amt}) return JsonResponse({"data":context, "totalCartItems":len(request.session['cart_data_obj'])}) here's my function.js implementation $(document).ready(function(){ $(".delete-product").on("click", function(){ let product_id = $(this).attr("data-product") let this_val = $(this) console.log(product_id); console.log(this_val); $.ajax({ url:'/delete-from-cart', data:{ 'id':product_id }, dataType: 'json', beforeSend: function(){ console.log("IN before send"); this_val.hide() console.log("IN after send"); }, success: function(response){ console.log("Starting success"); this_val.show() $("#cart-items-count").text(response.totalCartItems) $("#cart-list").html(response.data) console.log("successfully removed"); }, error: function(response){ alert('error'); } }) }) }) To be able to delete the next item in the cart without refreshing … -
Redirect Django TemplateDoesNotExist to 404
When the template does not exist, a 500 error returns to the user. I want Django to redirect to the 404 page for any view that gets a TemplateDoesNotExistError. Is there a way to accomplish this?