Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
cannot create from a factoryBoy class
I try to make a class a make some instances but I can't create any instance with the class in my django shell factories.py import factory from webshare.models import WebShareFileFolders class WebShareFileFactoryBoy(factory.django.DjangoModelFactory): class Meta: model = WebShareFileFolders inode = factory.Sequence(lambda n: n) name = factory.Faker('name') path = factory.Faker('text', max_nb_chars=50) is_dir = factory.Faker('boolean') and then the error in my console >>> from webshare.tests.factories import WebShareFileFactoryBoy >>> instance = WebShareFileFactoryBoy() Traceback (most recent call last): File "C:\Python37\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> TypeError: 'module' object is not callable >>> instance = WebShareFileFactoryBoy.create() Traceback (most recent call last): File "C:\Python37\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> AttributeError: module 'webshare.tests.factories.WebShareFileFactoryBoy' has no attribute 'create' Thank you for your help ;) Python 3.7.9 factory-boy 3.3.0 I just try to make instance from a factory class -
IntegrityError when I go to create superuser in Django
I am doing a blog project, I have made the user registration and login to be done through email, instead of using username. When I went to create the superuser to access admin, I get the following error in terminal. For the database I have connected it with PostgreSQL. django.db.utils.IntegrityError: llave duplicada viola restricción de unicidad «accounts_customuser_username_key» DETAIL: Ya existe la llave (username)=() Can someone help me with this problem? I hope you can guide me to solve this problem and to understand it so that I can solve it. Also to know if it is a problem with Django and the database configuration or if it has to do with PostgreSQL. -
Upload files to s3 bucket for a react js and django application
I am trying to use ASW s3 services to upload files. When clicked on a button to upload a file, the user should be able to select a file from his computer and upload it to the s3 bucket. The following code has been done by me views.py def upload_file(file_name, object_name=None): """Upload a file to an S3 bucket :param file_name: File to upload :param bucket: Bucket to upload to :param object_name: S3 object name. If not specified then file_name is used :return: True if file was uploaded, else False """ # If S3 object_name was not specified, use file_name if object_name is None: object_name = os.path.basename(file_name) # Upload the file s3_client = boto3.client('s3') try: response = s3_client.upload_file(file_name, 'my-bucket', object_name) except ClientError as e: logging.error(e) return False return True urls.py - Django app router = DefaultRouter() router.register(r'userdata', UserDataViewSet) router.register(r'education', EducationViewSet) router.register(r'workexperience', WorkExperienceViewSet) router.register(r'clientregistration', ClientRegistrationViewSet) router.register(r'jobdescription', JobDescriptionViewSet) router.register(r'assessment', AssessmentViewSet) router.register(r'appointment', AppointmentViewSet) urlpatterns = [ path('', include(router.urls)), path('api/recruiters/', get_recruiters, name='get_recruiters'), path('api/clients/', get_clients, name='get_clients'), path('submit-assessment/', submit_assessment, name='submit_assessment'), path('api/amanager/', get_accoutmanagers, name='get_accountmanagers'), path('api/job-descriptions/', get_job_descriptions, name='get_job_descriptions'), path('api/job-descriptions/<int:job_id>/assessments/', get_assessments_for_job, name='get_assessments_for_job'), path('clientregistration/', ClientRegistrationViewSet.as_view({'post': 'create'}), name='clientregistration'), path('api/get_user_details/', get_user_details, name='get_user_details'), path('submit_user_data/', submit_user_data, name='submit_user_data'), path('upload_file/', upload_file, name='upload_file') ] And on my react frontend const handleUploadResume = () => { // Assuming 'resumeFile' … -
How to Show Serializer Error in Django Templates
I created a register page using the Django rest framework, now I write all validation code in serializers.py and serializers.py in writing some errors but I can't see those errors in templates. class PersonSerializer(serializers.ModelSerializer): GENDER_CHOICES = [ ("male", "Male"), ("female", "Female"), ("other", "Other"), ] gender = serializers.ChoiceField(choices=GENDER_CHOICES) class Meta: model = Person fields = "__all__" def create(self, validated_data): gender = validated_data.pop("gender") validated_data["gender"] = gender.lower() return Person.objects.create(**validated_data) def validate(self, data: Union[str,int]) -> Union[str,int,None]: username = data.get("username") password = data.get("password") confirmpassword=data.get("confirmpassword") phone = data.get("phone") if Person.objects.filter(username=username).exists(): raise serializers.ValidationError('Username is allready exists') if len(phone) != 10: raise serializers.ValidationError("phone number is not valid") if password != confirmpassword: raise serializers.ValidationError('password not match') return data I expect to show an error in the Templates. -
client_max_body_size 0; is not being aplied even setting in every section
Why client_max_body_size 0; is not being aplied?? I'm receiving the following error trying to upload a file of 50M 413 Request Entity Too Large nginx/1.25.3 But I have setted the client_max_body_size 0; in every section My application is dockerized but mapping the config file to docker, so the config is working, but max body not client_max_body_size 0; upstream lito_upstream { # ip_hash; server viajah-api:8000; server front_viajah:3000; } server { client_max_body_size 0; location /static/ { client_max_body_size 0; autoindex on; alias /src/static/; } location /media/ { client_max_body_size 0; autoindex on; alias /src/media/; } location / { client_max_body_size 0; proxy_pass http://viajah-api:8000/; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Passa os cabeçalhos de cookie proxy_set_header Cookie $http_cookie; } listen 8000; server_name api.viajahturismo.com.br; } #server server { client_max_body_size 0; #Defines the port on which the server will listen for requests. include /etc/nginx/mime.types; location /media/ { client_max_body_size 0; autoindex on; alias /app/media/; } location / { client_max_body_size 0; proxy_set_header Host $host; proxy_pass http://front_viajah:3000; } listen 3000; server_name viajahturismo.com.br; } -
I made a "add to cart" function for my website but the js is not working
I made an add to cart function for my website So, in product-detail.html: <div class="button"> <input type="hidden" value="{{p.id}}" class="product-id" name=""> <input type="hidden" value="{{p.title}}" class="product-title" name=""> <a href="#" class="btn" id="add-to-cart-btn">Add to cart</a> <a href="#" class="btn">Buy Now</a> </div> and I also make a js file for this So, in function.js: $("#add-to-cart-btn").on("click",function(){ let quantity=$("#product-quantity").val() let product_title=$(".product-title").val() let product_id=$(".product-id").val() let product_price = $("#current-product-price").text() let this_val=$(this) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("Title:", product_title); console.log("Price:", product_price); console.log("Current Element:", this_val); $.ajex({ url: '/add-to-cart', data: { 'id': product_id, 'qty': quantity, 'title': product_title, 'price': product_price, }, dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(res){ this_val.html("Item added to cart") console.log("Added products to cart"); } }) }) In this code somethig is wrong with this portion dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(res){ this_val.html("Item added to cart") console.log("Added products to cart"); } Other thing is working perfectly well because In the console It is not displaying Adding products to cart and Item added to cart So Please help me out with this problem... -
`SSL: CERTIFICATE_VERIFY_FAILED` certificate verify failed: Hostname mismatch, certificate is not valid for 'smtp.gmail.com'. (_ssl.c:1007)
Issue Deploying Django Project on cPanel: Certificate Verification Error I am facing an issue while deploying my Django project on cPanel. The error indicates a certificate verification problem with the SMTP server 'smtp.gmail.com'. I have tried various solutions found online, but the issue persists. Here is my email configuration in settings.py: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '***' EMAIL_HOST_PASSWORD = '***' EMAIL_PORT = 587 Despite trying different solutions, I continue to receive the following error: csharp certificate verify failed: Hostname mismatch, certificate is not valid for 'smtp.gmail.com'. (_ssl.c:1007) I also attempted to create a custom EMAIL_BACKEND with the following code: import ssl from django.core.mail.backends.smtp import EmailBackend as SMTPBackend from django.utils.functional import cached_property class EmailBackend(SMTPBackend): @cached_property def ssl_context(self): if self.ssl_certfile or self.ssl_keyfile: ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT) ssl_context.load_cert_chain(self.ssl_certfile, self.ssl_keyfile) return ssl_context else: ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE return ssl_context However, this resulted in the error: bash code 535, b'Incorrect authentication data' I also attempted to use GPT, but did not find any useful resources. The output from the openssl s_client command indicates a successful SSL handshake, but the common name (CN) in the server certificate is listed as grace.mysecurecloudserver.com, not smtp.gmail.com. Is there a problem with my … -
Passing input form value to URL variable
I need to pass the form input entered by the user to the URL variable in Django <form> <div class="input-group"> <input type="text" name="ticker" class="form-control" placeholder="Search"> <div class="input-group-btn"> <a her="{% url 'Main:search' %}" class="btn btn-default"> <i class="bi bi-search"></i> </a> </div> </div> </form> The input value needs to be passed as a variable in the following URL logic "{% url 'Main:search' %}" urls.py app_name = 'Main' urlpatterns = [ path("", views.index, name='index'), path('search/<ticker>', views.search, name='search'), ] views.py def search(request, ticker): ticker = ticker.upper() result = Symbol.objects.filter(symbol=ticker).first() if result is not None: return redirect('Symbol:index', ticker=ticker) else: return render(request, 'symbol_not_found.html') -
How to send extra parameter to unittest's side_effect in Python?
I'm using side_effect for dynamic mocking in unittest. This is the code. // main functionn from api import get_users_from_api def get_users(user_ids): for user_id in user_ids: res = get_users_from_api(user_id) // test script def get_dynamic_users_mock(user_id): mock_by_user_id = { 1: { "id": 1, "first_name": "John", "last_name": "Doe", ... }, 2: { "id": 2, "first_name": "Jane", "last_name": "Smith", ... }, ... } return mock_by_user_id[user_id] @patch("api.get_users_from_api") def test_get_users(self, mock_get_users) user_ids = [1, 2, 3] mock_get_users.side_effect = get_dynamic_users_mock # mock get_users_from_api get_users(user_ids) # call main function I want to send extra parameter from test_get_users to this get_dynamic_users_mock function. How to do this? -
How to change the background color of an input field of a Django form if it contains errors
I'm trying to code a form with fields that, if a user inputs data that doesn't pass the validation of the form, change their background colors from the default white to lightcoral. Here is a fragment of the HTML file that contains the form itself: <div id="div_formbox"> <form method="post" id="form_appointments"> {% csrf_token %} {{ form.non_field_errors }} <div class="input_group"> <div class="input_field {% if form.name.errors %}error{% endif %}"> {{ form.name}} </div> <div class="input_field {% if form.last_name.errors %}error{% endif %}"> {{ form.last_name }} </div> <div class="input_field {% if form.email.errors %}error{% endif %}"> {{ form.email }} </div> </div> <button type="submit">Send</button> </form> </div> And here is the part of the CSS file where I try to apply the color change to the input fields with errors: .error { background-color: lightcoral; } As you can see, I'm using Django tags to change the class of the form fields with errors from "input_field" to "error". Next, in the CSS file, I reference the "error" class to apply the styling I want. But it doesn't work. I've tried a bunch of variations but none have worked. I'm out of ideas. -
Celery server not terminating immediately when using prefork and without pool line command
I'm working on a django project with celery and redis installed. When I run the Celery server as 'celery -A main_proj -l debug -P solo' or 'celery -A main_proj -l debug -P threads', I can terminate them just fine by just pressing CTRL-C once or twice for warm/cold shutdown. However, when I run Celery as 'celery -A main_proj -l debug' and 'celery -A main_proj -l debug -P prefork', whenever I try to terminate them, it just get stuck at Worker: Stopping Pool. No matter how long I wait, it stays like that until I decide to terminate it with taskkill. I'm fine with the first two alternatives but I want to know why the latter options don't finish quickly. This is the code I have for my celery app: from __future__ import absolute_import, unicode_literals import os from celery.schedules import crontab from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main_proj.settings') app = Celery('main_proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() Additionally, withing the settings.py file I set the CELERY_BROKER_URL with a redis URL that I get from Railway and I have the following code within the init file for the main_proj folder: from .celery import app as celery_app __all__ = ('celery_app',) This is what always happens whenever I … -
subdomain routing in django application
I have a django project that's hosted on a custom domain (e.g. mydomain.com). I have "app" app. For example, in development, requests looked like mydomain.com/app/dashboard. However, I wanted to use a subdomain instead so that my entire app is hosted on the subdomain app.mydomain.com and requests to mydomain.com/app/dashboard would route to app.mydomain.com/dashboard. I am using Nginx to handle this but I'm running into a few problems. Main part of nginx config: server { listen 443 ssl; server_name mydomain.co www.mydomain.co; location ~ ^/app(/?)(.*)$ { return 301 https://app.mydomain.co/$2; } location ~ ^/help(/?)(.*)$ { return 301 https://help.mydomain.co/$2; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # WebSocket specific headers proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } } server { listen 443 ssl http2; server_name app.mydomain.co; location / { # Proxy to your Django application server proxy_pass http://127.0.0.1:8000; # Adjust the port to match your setup proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } # same for help When my url pattern is like this: path('app', include('app.urls')), and I try to access the dashboard it redirects to app.mydomain.com/dashboard which is not valid since /dashboard is a url exclusively … -
upload images in Django save onlyto folder but not saving to mysql database
I need help my code below save image to folder but not saving to mysql database. pls i dont knw where am getting it wrong. VIEW.PY def indeximg(request): if request.method == "POST": form=ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('uploadok') else: form = ImageForm() return render(request, 'indeximg.html', {'form': form}) def uploadok(request): return HttpResponse(' upload successful') IN MODEL.PY class Image(models.Model): caption=models.CharField(max_length=100) image=models.ImageField(upload_to='images/') -
Best method to model django database using through table to access associations by date
Looking for advice on a tidy solution for accessing The end result I am looking for is the following report: cast, start_date, wire, winch I currently run a script when a cast object is submitted via form to get the active wire associated with the cast, and save it in the 'wire' foreign key field. The active wire is accessed in the script through property tags. Technically this information is retained in the database through a series of models associating a cast with a wire (Cast-DrumLocation-WireDrum), and the date fields that store when the events occurred. These events update the association between cast and wire. Is the way I modelled this a proper solution?, or is there another solutions where the wire foreign key does not need to be stored as a field in the cast model. class Cast(models.Model): id = models.AutoField(db_column='Id', primary_key=True) startdate = models.DateTimeField(db_column='StartDate') enddate = models.DateTimeField(db_column='EndDate') wire = models.ForeignKey('Wire', models.DO_NOTHING, db_column='WireId') winch = models.ForeignKey('Winch', models.DO_NOTHING, db_column='WinchId') class Drum(models.Model): id = models.AutoField(db_column='Id', primary_key=True\) location = models.ManyToManyField(Location, through='DrumLocation', related_name='active_location') material = models.TextField(db_column='Material') wiretype = models.TextField(db_column='WireType') class Winch(models.Model): id = models.AutoField(db_column='Id', primary_key=True) name = models.TextField(db_column='Name') drums = models.ManyToManyField(Drum, through='Drumlocation', related_name='active_drum') class Wire(models.Model): id = models.AutoField(db_column='Id', primary_key=True) nsfid = models.TextField(db_column='NsfId') drums … -
Django ImportError: No module named 'idna' – How to Resolve?
I have a problem with the request module in Django. In development mode i can make API calls okay, but for some reason in production I run into an error that says "No module found 'idna'", I am using IIS webserver in my project. Please help! I tried to use Django rest framework but it seems the request module is still needed, to consume the API. -
Django can't read docker enviroment variable
I'm building a docker compose environment and Django can't read the environment variables i try to give it. Inside my settings.py i have this bit of code ... import os SECRET_KEY = os.environ["DJANGO_SECRET_KEY"] DEBUG = os.environ["DEBUG"] ... and this should be able to read the variables i give to the container, which i tried to give in many different ways. This is the content of my envfile: DJANGO_SECRET_KEY="k64dpx9s1h!ijwafy-lif!(*)sabwk*w+rg#6=nu@ty2jkw%gc" DEBUG="False" All of the following result in django not being able to read the variables during docker build. First attempt: env_file inside compose.yaml This is my compose.yaml services: django: env_file: - ./django/.env Error given: Keyerror Second attempt: changing env_file path This is my compose.yaml services: django: env_file: - /some/other/random/path Error given: no such file or directory (don't mess around with files that don't exist, the file location is correct) Third attempt: hardconding variables This is my compose.yaml services: django: environment: DJANGO_SECRET_KEY: "k64dpx9s1h!ijwafy-lif!(*)sabwk*w+rg#6=nu@ty2jkw%gc" DEBUG: "False" env_file: - ./django/.env Error given: Keyerror Fourth attempt: running standalone container I tried running a docker standalone container and giving the variables by cmd docker run -dp 127.0.0.1:8000:8000 \ -e DJANGO_SECRET_KEY='k64dpx9s1h!ijwafy-lif!(*)sabwk*w+rg#6=nu@ty2jkw%gc' \ -e DEBUG="False" django:v0 Error given: Keyerror Thanks for reading this far. I hope no one will … -
Cookies not accessible in react, but shown chrome developer tools. Django RF backend
Using Django rest framework, I have # views.py @method_decorator(ensure_csrf_cookie, name="dispatch") class SetCsrfTokenAPIView(APIView): permission_classes = (permissions.AllowAny,) def get(self, request, format=None): response = Response({"success": "CSRF cookie set"}) response.set_cookie( "my_cookie", "cookie_value", max_age=3600, secure=True, samesite="None" ) return response # settings.py CORS_ALLOW_ALL_ORIGINS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = "None" # CSRF_COOKIE_SAMESITE = "Lax" CSRF_COOKIE_HTTPONLY = False CORS_EXPOSE_HEADERS = ["Content-Type", "X-CSRFToken"] SESSION_COOKIE_SAMESITE = None CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", # "*", ] INSTALLED_APPS = [ ... "rest_framework", "corsheaders", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", ... ] Using react frontend, i make a fetch request with to the endpoint that hits SetCsrfTokenAPIView. const data = await fetch( `${process.env.REACT_APP_API_URL}/auth/csrf/`, { method: "GET", credentials: "include", // This is equivalent to Axios's `withCredentials: true` headers: { "Content-Type": "application/json", }, } ); Call is successful and I can see the token values in chrome developer tools token in Applications header in Network However, when i use js-cookie, react-cookie or document.cookie to get the cookie contents, it cannot find any cookie set from django. How can I access cookies in react frontend? My goal is to extract the value and submit the value using the X-CSRFToken header. What I did so far I have scavenged relevant django … -
Stuck on Django 4.2.11
I try to learn Django but I came across a wall. I need to use Django 5 for my project but when I update Django to 5.0.3 my terminal update it than say that I am still in 4.2.11. So I tried to uninstall it then reinstall it but after a successfull uninstallation the command : "python -m django --version" still return the 4.2.11 version. So what can I do ? Thanks -
Best way for grouping models by two week periods and tie them to a data entry?
I am working on a project that is based on a two week time period. I have a model with a start_date and end_date as seen below: class CreateNewTimesheet(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) start_date = models.DateField(_("Start Date")) end_date = models.DateField(_("End Date")) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I want to be able to add another line or something that groups the start_date and end_date. Dates: 03/06/2024 - 03/16/2024 And group or tie that to "week 1". The purpose behind this is to create a timesheet based on a two week time period. I need to be able to group the timesheets by a two week period and tie them to that specific group. All of the Timesheets need to be stored. After start_date and end_date are entered I need them to be tied to week one. I was thinking about adding another line to the CreateNew model and then tie that to week one. And then each start_date and end_date are entered, a new "week" is entered for each new start_date and end_date is created. Should that be based off of created_at entry? Should each week be grouped by a new url? I am honestly stuck at this point about … -
what is different between wsgi.py and asgi.py file, and why we not use manage.py file in deployment
what is different between wsgi.py and asgi.py file, and why we not use manage.py file in deployment I expected, a reason, why we not used manage.py file in devlopyment,if we deploy a web-application through manage.py then what is sceurity threat -
checkbox getlist return max two values from request GET in django
I have a problem with the getlist function in Django. Specifically, I have several checkboxes listed using a for loop. The form is written in HTML without Django Forms. The problem is that the getlist function returns a maximum of two values even if I check more than two checkboxes. Where could the error be? if 'category' in request.GET: print('Category in request GET.') if len(request.GET.getlist('category')) == 1: print(request.GET.getlist('category')) filters['category_id'] = Category.objects.get( slug='-'.join(request.GET.get('category').lower().split())).id if len(Property.objects.filter(**filters)) == 0: queryset.clear() messages.info(request=request, message='No Results.') return redirect(to='properties') else: request.session['sorted_type'] = 'Newest Properties' request.session['filters'] = filters context.update(sidebar_context(**filters)) queryset.clear() queryset.extend(Property.objects.filter(**filters)) else: print('More than one Category.') filters['category__pk__in'] = [Category.objects.get(slug='-'.join(obj.lower().split())).id for obj in request.GET.getlist('category')] if len(Property.objects.filter(**filters)) == 0: queryset.clear() messages.info(request=request, message='No Results.') return redirect(to='properties') else: print(request.GET.getlist('category')) request.session['sorted_type'] = 'Newest Properties' request.session['filters'] = filters context.update(sidebar_context(**filters)) queryset.clear() queryset.extend(Property.objects.filter(**filters)) <form data-properties-filters-form class="properties__filters__filters-form theme-form" method="get" action="{% url 'properties' %}"> <div style="opacity: 0; position: absolute; top: 0; left: 0; height: 0; width: 0; z-index: -1;"> <label>leave this field blank to prove your humanity <input type="text" class="url" autocomplete="off" tabindex="-1"> </label> </div> {% if categories %} <div class="properties__filters__title h4">Category</div> <div class="form__row"> <div class="form__field"> <div data-change-category class="form__input-wrap form__checkbox-wrapper"> {% for category in categories %} <label> <input data-checkbox data-input type="checkbox" name="category" value="{{ category|lower }}"{% if category|lower in request.GET.category … -
Can't connect Django with Mysql
I tried to connect Django with Mysql server But the error show up when I ran python manage.py migrate I already created the database in Mysql and modify the settings.py in Django. I also check if the Mysql server is running which it's currently running. Library installed mysqlclient pymysql Here is my settings.py Here is the error django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1:3306' (111)") I tried restart the service of Mysql8services0 but still does not work for me -
400 Bad Request in Apollo Client querying Django Backend
I'm getting the following error when I attempt to make a GraphQL query using Apollo Client in my React frontend from my Django/Django Rest/Graphene Backend. I have also gotten some CORS errors so I have disabled cors on the client with: fetchOptions: { mode: "no-cors", }, and on the backend with csrf_exempt. I am able to make the query work just fine in Postman and GraphiQL but not in React. Here is my query: export const STOCKS_BY_ADJ_CLOSE_RANGE_AND_DATE_QUERY = gql` query StocksByAdjCloseRangeAndDate { stocksByAdjCloseRangeAndDate( low: 100 high: 105 start: "2024-03-01T00:00:00Z" end: "2024-03-10T00:00:00Z" ) { ticker datetime open high low close adjClose volume } } `; Here is my client: const errorLink = onError(({ graphQLErrors, networkError }) => { if (graphQLErrors) { console.log("graphQLErrors", graphQLErrors); } if (networkError) { console.log("networkError", networkError); } }); const client = new ApolloClient({ cache: new InMemoryCache(), headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", }, connectToDevTools: true, link: from([ errorLink, new HttpLink({ uri: "http://127.0.0.1:8000/graphql", fetchOptions: { mode: "no-cors", }, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": "true", }, }), ]), }); Here are my Django routes: urlpatterns = [ # path("", router.urls), # path("", include(router.urls)), path( "api-auth/", include("rest_framework.urls", namespace="rest_framework") ), path("admin/", admin.site.urls), # path("", TemplateView.as_view(template_name="frontend/build/index.html")), path("api/", include(router.urls)), path("", home), path( … -
Problem with "{% load static %}" in Django
I'm just starting with django, and when I put {% load static %} in the html it doesn't complete it, that is, it doesn't take it as code, I need helpenter image description here I tried importing it through a link, adding a general folder but I don't know what happens -
Could not deserialize class 'Functional'
I did transfer learning to VGG16 model in order to classify images to cat or dog and here is portion of the code snippet : prediction_layer = tf.keras.layers.Dense(1) prediction_batch = prediction_layer(feature_batch_average) def manual_preprocess_input(x, data_format=None): if data_format is None: data_format = tf.keras.backend.image_data_format() if data_format == 'channels_first': # If channels are first, move them to the last dimension x = tf.transpose(x, perm=[0, 2, 3, 1]) # Mean subtraction (ImageNet means in BGR order) mean = [103.939, 116.779, 123.68] x = x - tf.constant(mean, dtype=x.dtype) # Zero-centering by subtracting 127.5 x = x / 127.5 return x inputs = tf.keras.Input(shape=(224, 224, 3)) x = data_augmentation(inputs) x = manual_preprocess_input( x ) x = base_model(x, training=False) x = global_average_layer(x) x = tf.keras.layers.Dropout(0.2)(x) outputs = prediction_layer(x) model = tf.keras.Model(inputs, outputs) and here is the view code where I loaded my model : then I saved it using model.save('my_model.keras'), then I loaded in a django view but the problem is whenever I load it and make post request to the view, in the line where I load the model I encounter this error : def testSkinCancer(request): model = tf.keras.models.load_model( os.getcwd()+r'\media\my_model.keras', safe_mode=False) print(">>> model loaded") if not request.FILES: return HttpResponseBadRequest(json.dumps({'error': 'No image uploaded'})) # Access the uploaded image …