Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I allow users to upload multiple images and files in django?
I want to create functionality like facebook/twitter for creating a post. I have a url smth like example.com/username/posts/create with the form related to the post model. As you probably know, there is no ability in vanilla ImageField & FileField to upload multiple items, as well as no decent editor for drag&drop like things. Drag&Drop isn't a crucial feature, but I really want to handle with a twitter/facebook like editor somehow. With all it's convenient buttons for photo/video/file. I saw there is a bunch of custom editors like DJANGO-CKEDITOR and etc., but I don't understand how it suppose to work anyway with one image/file field. Maybe, somebody was facing the problem? Attach my form and model in case it will help: Models.py class Post(models.Model): title = models.CharField(max_length=200, null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) images = models.ImageField(null=True, blank=True, upload_to="posts/images") body = models.TextField(max_length=255) post_date = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) likes = models.ManyToManyField(User, through='UserPostRel', related_name='likes') forms.py class PostCreationForm(ModelForm): class Meta: model = Post fields = [ 'title', 'body', 'images', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['title'].label = "Title" self.fields['body'].label = "Body" self.fields['images '].label = "images" -
display form errors. Django
I have sign up form. I don't know how I can display errors. I'm trying it from models.py, I have unique errors, but they don't display, I also have custom validation in forms.py, where I'm checking if passwords match and some rules for passwords and it doesn't work either. So, question is, how can I display validation errors? models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, AbstractUser # Create your models here. class User(AbstractUser): username = models.CharField(max_length=100, unique=True, error_messages={ 'unique': "This username has already been registered."}) password = models.CharField(max_length=200, unique=False) email = models.EmailField(unique=True, error_messages={ 'unique': "This email has already been registered."}) phoneNumber = models.CharField(max_length=12, unique=True, error_messages={ 'unique': "This phone number has already been registered."}) first_name = None last_name = None forms.py from django.forms import ModelForm, ValidationError from django import forms from .models import User class LogInForm(forms.Form): username = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Username', 'class': 'form-input'}), required=True) password = forms.CharField(widget=forms.PasswordInput( attrs={'placeholder': 'Password', 'class': 'form-input'}), required=True, min_length=8) class SignUpForm(ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput( attrs={"placeholder": "Password"}), min_length=8, required=True) password2 = forms.CharField( label='Confirm password', widget=forms.PasswordInput(attrs={"placeholder": "Confirm password"}), min_length=8, required=True) error_css_class = 'message-error' error_messages = { 'password_mismatch': 'Passwords must match.', } class Meta: model = User fields = ('username', 'email', 'phoneNumber', 'password') widgets = { "username": … -
fetch Django model in many to many relationship my other model
I am trying to figure out how many objects of a djanog model have a many to many relationship with a spicific objects of another model. my modles.py is from django.db import models from django.contrib.auth.models import User class Post(models.Model): post_title = models.CharField(max_length=200) post_body = models.CharField(max_length=1000) pub_date = models.DateTimeField('date published') by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.post_title def get_id(self): return self.id def get_body(self): return self.post_body def get_date(self): return self.pub_date def get_name(self): return self.post_title def get_author(self): return self.by def get_likes(self): return type(self).likes.all() class Like(models.Model): associated_post = models.ManyToManyField(Post) associated_user = models.ManyToManyField(User) and my view is from django.views import generic from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.utils import timezone from .models import Post def index(request): posts = [] for post in Post.objects.order_by('-pub_date'): posts.append({'title': post.get_name(), 'author_id': str(post.get_author()), 'created': post.get_date(), 'body': post.get_body(), 'id': post.get_id()}) print(post.get_likes()) return render(request, 'home.html', {'posts': posts}) Basically the function post.get_likes needs to return the number of likes that have a realtionship with the post. I v'e read the django documentation on this topic, but I just can't quite figure out what is actually going on in the example code. -
Parallel execution of for loop in django functions
I have a function and this function goes to 10 different sites and retrieves data with a GET request. This is how I do it inside the for loop. WebSite.objects.all(); The database that I saved in a different area on django. web_site = WebSite.objects.all(): for web in web_site: get information from web I want to run this for loop in parallel. How can I achieve this, is there an easy way? I can also implement it directly in func code or try a feature of django/celery. -
Debug dockerized Django application running Uvicorn - ASGI on VSCode?
I'm trying to run debugpy in attach mode to debug on VScode a dockerized Django app. With the following configuration on launch.json { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "attach", "pathMappings": [{ "localRoot": "${workspaceFolder}", "remoteRoot": "/app" }], "port": 9999, "host": "127.0.0.1" } ] } I've been able to attach correctly to it adding the following section on the manage.py file: #!/usr/bin/env python import os import sys from pathlib import Path if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") # debugpy configuration from django.conf import settings if settings.DEBUG: if os.environ.get("RUN_MAIN") or os.environ.get("WERKZEUG_RUN_MAIN"): import debugpy debugpy.listen(("0.0.0.0", 9999)) ... The Django Dockerfile is launching the script: #!/bin/bash set -o errexit set -o pipefail set -o nounset python manage.py migrate exec python manage.py runserver 0.0.0.0:8000 And I'm exposing the ports 8000 and 9999 running the docker image. So far so good. What I'm trying to do now is enable the same support for the ASGI application running under uvicorn. #!/bin/bash set -o errexit set -o pipefail set -o nounset python manage.py migrate exec uvicorn config.asgi:application --host 0.0.0.0 --reload --reload-include '*.html' asgi.py """ ASGI config for Suite-Backend project. It exposes the ASGI callable as a module-level variable named ``application``. For more information … -
How do I create a Django model for a chatroom in python?
Just letting you all know that I am very inexperienced with web development and so I decided to start a project in which I am making an application similar to Discord in which people can go to chat rooms and voice chat each other. From research, I decided to use Django (now with sockets). I started my project making the models first since that is the easiest for me to understand now. I was easily able to create a User Profile like so: from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver import django class UserProfile(models.Model): user_name = models.OneToOneField(User, related_name='user profile', on_delete=models.CASCADE) photo = models.ImageField(null=True, blank=True, default='random_14-512.webp') status = models.CharField(default='This is my status', max_length=255) is_online = models.BooleanField(default=False) objects = models.Manager() @receiver(post_save, sender=User) def create_user_profile(self, sender, instance, created, *args, **kwargs): if (created): UserProfile.objects.create(user_id=instance.pk) class ChatRoom(models.Model): pass but I have no idea how I can create a model for the chatroom. I can give it a name easily and such, but if I use models.CharField, the first parameter is the user. If anyone can point me in the right direction on how I can create the model for the chat room, that would be much … -
Im having trouble with the variable of a for loop in javascript in a django template
what i am trying to do is make an animation by looping throught some images in my static file folder with javascript in django. but something keeps screwing their adress up my code looks something like this {% load static %} <img id="image_1" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/62/Solid_red.svg/512px-Solid_red.svg.png?20150316143248"> <button onclick="animation()">Click me</button> <script> function animation(){ for(var i=0; i < 10; i++){ changeImg(i); } } function changeImg(number){ let text = number.toString(); document.getElementById("image_1").src = "{static 'img" + text + ".png' %}"; } </script> if the images in static look like this: img1.png img2.png img3.png and so forth... and the adress of the image was this afterward img%22%20%2B%20text%20%2B%20%22.png -
React-redux cannot get user information for the profile
I am working on an e-commerce project(react, django) and register/login system is working well, but I when I started to work on update profile form, first I decided to get some info of the user. I am getting Authentication credentials were not provided error message. In console i am getting a 401 Unauthorized error: "GET /api/users/profile/ HTTP/1.1" 401 58. userReducers.js: export const userDetailsReducer = (state = { user: {} }, action) =>{ switch (action.type) { case USER_DETAILS_REQUEST: return { ...state, loading: true } case USER_DETAILS_SUCCESS: return { loading: false, user: action.payload } case USER_DETAILS_FAIL: return { loading: false, error: action.payload} default: return state } } userActions.js: export const getUserDetails = (id) => async (dispatch, getState) => { try{ dispatch({ type: USER_DETAILS_REQUEST }) const { userLogin: { userInfo }, } = getState() const token = userInfo.token const config = { headers:{ 'Content-type': 'application/json', Authorization: 'Bearer'+token, } } const { data } = await axios.get( '/api/users/'+id, config ) dispatch({ type: USER_DETAILS_SUCCESS, payload: data }) }catch(error){ dispatch({ type:USER_DETAILS_FAIL, payload:error.response && error.response.data.detail ? error.response.data.detail : error.message, }) } } ProfileScreen.js: import React, {useState, useEffect} from 'react' import { Link, useNavigate, useParams, useLocation } from 'react-router-dom' import { Form, Button, Row, Col } from 'react-bootstrap' … -
Error When Parsing Incoming Email Via SendGrid
I am successfully set up a webhook with django/python to parse incoming SendGrid emails. However, I am getting an error and cannot parse the data I receive. The error suggest the body I am receiving is empty, which is not the case. @csrf_exempt def receive_email_hook(request): print("request.body: ",request.body) try: data = json.loads(request.body.decode('utf-8')) sender = data['from'] recipient = data['to'] subject = data['subject'] body = data['html'] print("SUBJECT: "+str(subject)) return HttpResponse(status=200) except Exception as e: print("ERROR: "+str(e)) return HttpResponse(status=400) My error is: ERROR: Expecting value: line 1 column 1 (char 0) When I print the request.body, I get: request.body: b'--xYzZY\r\nContent-Disposition: form-data; name="headers"\r\n\r\nReceived: (...) The full print has all the information from the email and all the data I would expect. Just seems to be an error on the parsing but can't figure it out. I asked Chat GPT but got some whack ass answers, so fellow human, can you help? -
I´m trying to include a local javascript in my react component, and the functionality of said component is inconsistent
I have a component in react called consentBottom, where I am trying to import an external javascript file called consent. I can get the functionality of the consent file to work, but once I press the "go back" button and then immediately "go forward" button in the browser, the functionality from the javascript file stops working. Bear in mind that there is no function to export manually from this file. It´s full of functions, using jquery, that get invoked when buttons or forms that have a particular class or id names are pressed or submitted. This is a file integraded from another environment, and the project is being transferred from flask to the setup with django on the backend and react on the frontend. The pipeline of my project now is: index.html -> (calls element by div with id=root) index.js -> has the following call to the App component: <React.StrictMode\> <App /> </React.StrictMode\> App.js -> has the following url routes: <BrowserRouter> <Route path='/' element={<Home languageState={languageState}/>} /> <Route path='/consent' element={<Consent languageState={languageState}/>}/> <Route path='/authenticate-presenter' element={<AuthenticatePresenter languageState= {languageState}/>}/> <Route path='/main-complaints' element={<MainComplaints languageState={languageState}/>}/> <Route path='/questions' element={<Questions languageState={languageState}/>}/> </BrowserRouter> Home (url="/") -> Has a main component homeMainPage, which calls another component homeBody inside the jsx … -
Cytoscape.js not loading graph in Django
I am trying to show graph in the HTML template of my Django application, I first tried with the actual data that I am working with (I am using the Neomodel to fetch the data from Neo4J and then transforming it to right JSON for cytoscape), but it did not work with it. After that I tried with the mock data but it did not after that either. I don't understand what I am doing wrong. This is my graph.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Graph View</title> <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.23.0/cytoscape.min.js" integrity="sha512-gEWKnYYa1/1c3jOuT9PR7NxiVI1bwn02DeJGsl+lMVQ1fWMNvtjkjxIApTdbJ/wcDjQmbf+McWahXwipdC9bGA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>--> <script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.8.4/cytoscape.min.js" integrity="sha512-gn5PcEn1Y2LfoL8jnUhJtarbIPjFmPzDMljQbnYRxE8IP0y5opHE1nH/83YOuiWexnwftmGlx6i2aeJUdHO49A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <style> #cy { width: 300px; height: 250px; display: block; background-color: #fff; } </style> </head> <body> {{data}} <div id="cy"></div> <div id="test"></div> <h2>Hello</h2> <script> var cy = cytoscape({ container = document.getElementById('cy'), elements: { nodes: [ { data: { id: 'a', name: 'Sheraton Cherry' } }, { data: { id: 'a1', name: 'Rosacea'}}, { data: { id: 'a2', name: 'Dentate' } }, { data: { id: 'a3', name: 'Pinnate' } }, { data: { id: 'b', name: 'Pineapple Guava' } }, { data: { id: 'b1', name: 'Myrtaceae'}}, { data: { id: 'b2', name: 'Entire' } }, { data: { id: 'a3', name: … -
Django Admin display Count of related field
I am building a Django project for a workshop (car/motorcycle). Have a customer class in models and a service class. In the admin I want to display the number of services per customer, I am taught to use the get_queryset and define a variable for that count, but it doesn't want to work, probably its like a really easy fix but I can't get my head around it! Hope someone here knows, thanks a lot! :-) MODELS.PY from django.db import models # Create your models here. class Fordonsregister(models.Model): regnr = models.CharField(max_length=6, primary_key=True, null=False, blank=False) namn = models.CharField(max_length=255, null=True, blank=True) tel = models.CharField(max_length=255, default='070-000 00 00', null=True, blank=True) email = models.EmailField(null=True, blank=True) kund_sedan = models.DateTimeField(auto_now=True) kund_points = models.IntegerField(default=0) def __str__(self) -> str: return self.regnr class Meta: ordering = ['regnr'] class ServiceTypes(models.Model): typ = models.CharField(max_length=255, primary_key=True, blank=False) pris = models.DecimalField(decimal_places=2, max_digits=6, null=False, blank=False) beskrivning = models.CharField(max_length=255, null=True, blank=True) def __str__(self) -> str: return self.typ class Meta: ordering = ['typ'] class FordonsService(models.Model): regnr = models.ForeignKey(Fordonsregister, on_delete=models.CASCADE) typ = models.ForeignKey(ServiceTypes, on_delete=models.CASCADE) service_datum = models.DateTimeField() bokat_datum = models.DateTimeField(auto_now=True) kommentar = models.CharField(max_length=1000) class Meta: ordering = ['-service_datum'] ADMIN.PY from django.contrib import admin from django.db.models import Count from django.http import HttpRequest from .models import Fordonsregister, ServiceTypes, FordonsService … -
How to change the time format when providing an initial value in Django?
I made a form in Django and provided an initial value to the time field when rendering the form, the format is HH:MM:SS but if I do not provide any initial value the format is HH:MM. I want to specify an initial value and want the format to be HH:MM. class SearchTimeSlotsForm(forms.Form): available_from = forms.TimeField( widget=TimeInput(attrs={'class': 'unbold-form'}), initial=time(0) ) available_till = forms.TimeField( widget=TimeInput(attrs={'class': 'unbold-form'}), initial=time(23,59,59) ) Can someone please help me with this? -
How to decrease an image size when loading the page in Django backed web application?
My classic Django application is a simple blog post website showing the posted images line on a start page. I allow users to upload images to their posts up to 100 Mb to have the ability to download the image if someone likes it. But I encountered a significant loading time on the start page due to image sizes. I use CSS object-fit feature to make images small for good fitting on a common start page, but the image size in Mb doesn't change. It is still downloading full-sized images and after just shaping them with CSS. As a result, I have very slow page loading. I used a standard model pattern in the Django backend: image = models.ImageField...and then just render it on a page template with post.image.url tag. So I want the original-sized image loads if users click on the image only. Please advise how to fix that. -
How to configure multiple sites with django and apache server with wsgi
I configure two sites in my server, but when trying access to my second site apache2 redirect me to first site, I want to serve tow sites in the same server but not working This is my configuration of my first site: GNU nano 5.4 first_site.com.conf <VirtualHost first_site.com:80> #ServerAdmin admin@soporte.localhost ServerName inscripcion.uepbi.com #ServerAlias www.first_site.com #DocumentRoot /home/sites/first_site #DocumentRoot /var/www ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /favicon.ico /home/sites/first_site/staticfiles/favicon.ico Alias /static/ /home/sites/first_site/staticfiles/ <Directory /home/sites/first_site/staticfiles> Require all granted </Directory> Alias /uploads/ /home/sites/first_site/uploads/ <Directory /home/sites/first_site/uploads> Require all granted </Directory> <Directory /home/sites/college_system/college_system> <Files wsgi.py> Require expr %{HTTP_HOST} == "first_site.com" Require expr %{HTTP_HOST} == "www.first_site.com" Options </Files> </Directory> WSGIDaemonProcess first_site python-path=/home/sites/first_site python-home=/home/sites/first_site_env #WSGIPythonHome /home/sites/first_site #WSGIPythonPath /home/sites/first_site WSGIProcessGroup first_site WSGIScriptAlias / /home/sites/first_site/first_site/wsgi.py process-group=first_site application-group=%{GLOBAL} Redirect "/" "https://first_site.com/ RewriteEngine on RewriteCond %{SERVER_NAME} =www.first_site.com [OR] RewriteCond %{SERVER_NAME} =first_site.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] #RewriteCond %{SERVER_NAME} !on [OR] #RewriteCond %{SERVER_NAME} ^www\. [NC] #RewriteRule ^ https://first_site.com%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> This my configuration for my second site: <VirtualHost second_site.com:8080> #ServerAdmin admin@soporte.localhost ServerName second_site.com #ServerAlias www.second_site.com #DocumentRoot /home/sites/second_site ErrorLog ${APACHE_LOG_DIR}/error_demo_college.log CustomLog ${APACHE_LOG_DIR}/access_demo_college.log combined Alias /favicon.ico /home/sites/second_site/staticfiles/favicon.ico Alias /static/ /home/sites/second_site/staticfiles/ <Directory /home/sites/second_site/staticfiles> Require all granted </Directory> <Directory /home/sites/second_site/static> Require all granted </Directory> Alias /uploads/ /home/sites/second_site/uploads/ <Directory /home/sites/second_site/uploads> Require all granted </Directory> <Directory /home/sites/second_site/second_site> <Files wsgi.py> Require expr … -
Django navigation problems because of url
I have created a web app using the Django framework. I created a function to iterate through my installed apps and display the desired apps as links to said app, without having to hard-code the link to each app (the function finds the link and displayed app name) On my home page I have links to my other apps, and they all work, but once I enter an app, the links to every other app do not. The function still does what it is supposed to, but when the links are clicked, the url of the clicked app is appended to the end of the current url instead of replacing it and directing me to the desired app. How to I get the clicked url to replace the current url and not just append to it? I designed the names of my urls and apps to work with this function, and that works, but I did not expect the clicked links to append themselves to the current url. -
DRF and Html {% render_form serializer %}
I worked with django rest framework and I have problem with generics.ListCreateAPIView when I want to add template_name for form I can't {% render_form serializer %} and I get error. in browser enter image description here in terminal enter image description here index.html {% load rest_framework %} <html><body> <form action="{% url 'post:posts' %}" method="POST"> {% csrf_token %} {% render_form serializer %} <input type="submit" value="Save"> </form> <li>{{ id }}</li> <li>{{ title }}</li> <li>{{ body }}</li> <ul> {% for list in results %} <li>{{ list.id }}</li> <li>{{ list.title }}</li> <li>{{ list.body }}</li> ------------ {% endfor %} </ul> </body></html> view.py class PostList(generics.ListCreateAPIView): # queryset = Post.objects.all() permission_classes = (IsAuthenticated,) serializer_class = PostSerializer # Add Template renderer_classes = [renderers.TemplateHTMLRenderer] template_name = 'index.html' filter_backends = [ DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter ] filterset_fields = ['id','title','body'] search_fields = ['id','title','body'] ordering_fields = ['id','title','body'] def perform_create(self, serializer): return serializer.save(owner=self.request.user) def get_queryset(self): return Post.objects.filter(owner=self.request.user) I would try with DRF documents, but I couldn't. -
Django and Js framework as FrontEnd
What is the best way to integrate Django with React or Vue.js Framework? Using the framework as a template (in the template folder) in Django or creating API and then consume with the framework? How does Django's integration with Js framework works in the real world projects? I'm new Django programmer and have this question. -
Application Error - Heroku logs - Need Help Interpreting
I created a django project months ago deployed it to Heroku. It functioned well for quite a few months, but when Heroku changed to a paid service my site was knocked off. I've been trying to resurrect it and have gotten part of the way. The website allows students to practice reading musical pitches on the note staff and finger board (for orchestra instruments). When I visit my site after deployment, it takes me to a landing page where I can choose to sign up, login, or go to a free games page. Both Login and Registration pages load, but when clicking submit the redirect times out. It should go to the main orch_quiz page which contains the quizzes for the students. Instead I get an Application Error page that suggests I use the heroku logs --tail command. When I run that, I understand the H12 is a timeout error code, but it does not explain why the timeout is happening. I'm a novice at building websites so any assistance or guidance would be greatly appreciated! The project is deployable and does without noticeable error. The issues seems to be in accessing the orch_quiz app. I've run pip freeze to … -
how to make the central postgres db handle these concurrent connexions more efficiently?
we have 100 separate python scripts connecting at the same time to a central postgres database to perform multiple operations like reads and writes postgres creates a separate process for each of these clients, which is not efficient and consumes too much resources. -
Django handler404 not called on raise Http404
I've setup a custom 404 handler in my Django views @api_view(["GET"]) def handler_404(request: HttpRequest, exception: Exception = None): return Response({"status": 404, "error": "Not Found"}, status=404) It works perfectly if I visit an invalid path; however it is not called when I raise Http404 exceptions, for example with the get_object_or_404 method - the default 404 response is returned instead. I implemented a workaround by adding a 404 handler in my middleware but I'd like to know if there's something I'm doing wrong and how to intercept Http404 exceptions with it def process_response(self, request, response): if response.status_code == 404: # for some reason views.handler_404 doesn't catch Http404 Exceptions return JsonResponse({"status": 404, "error": "Not Found"}, status=404) This is what my urls file looks like (as I said the handler works fine on most 404 responses) handler400 = api.views.handler_400 handler403 = api.views.handler_403 handler404 = api.views.handler_404 handler500 = api.views.handler_500 To sum it up, I tried adding the handler in my urls file but it is not called upon Http404 exceptions. Thank you for the help -
Fix mixed content from frontend or backend
I built the frontend of my website using React, and it is hosted on netlify. Here is an example of a call I make to my API. fetch(`http://....com/all/`, { method: "GET", headers: { 'Content-Type': 'application/json', } }).then((res) => { return res.json(); } ).then((data) => { let informations = data.restaurant; // do stuff with data }).catch((err) => { console.log(err); }) This site is hosted on an https domain, provided by netfily. Then, my backend is a Django app, built with Docker compose and hosted on digital ocean droplets, that serves via HTTP. But each time I can the API with the site, it returns that Mixed Content: The page at 'https://...' was loaded over HTTPS, but requested an insecure resource 'http:...'. This request has been blocked; the content must be served over HTTPS. How is it fixable? I am not able to figure out a way to put https into my backend, and the frontend is not working properly. Please help -
How can I consume and HTTP API in my HTTPS website
I built the frontend of my website using React, and it is hosted on netlify. Here is an example of a call I make to my API. fetch(`http://blabla.com/all/`, { method: "GET", headers: { 'Content-Type': 'application/json', } }).then((res) => { return res.json(); } ).then((data) => { let informations = data.restaurant; // do stuff with data }).catch((err) => { console.log(err); }) This site is hosted on an https domain, provided by netfily. Then, my backend is a Django app, built with Docker compose and hosted on digital ocean droplets, that serves via HTTP. But each time I can the API with the site, it returns that Mixed Content: The page at 'https://...' was loaded over HTTPS, but requested an insecure resource 'http:...'. This request has been blocked; the content must be served over HTTPS. How can I fix this? Is there anything that can be done on the frontend to allow it? Otherwise, how do I put the HTTPS stuff on digital ocean droplets and django? Because I spent almost three hours trying to figure it out, without being able to do so. Please help me -
Changing the location where my domain resolved to on a Nginx server
I have my DND set to my domain name and I want to load a installation of a Django website I have installed. When I load www.mywebsite.com it loads a mydomain but from /var/www/html but I want it to load from /home/myname/kkappDashboard; I'm using a Nginx server and here is the sites-available configuration server { listen 80; server_name 151.236.222.57 www.mywebsite.com mywebsite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myname/kkappDashboard; } location / { include proxy_params; proxy_pass http://unix:/home/myname/kkappDashboard/kkappDashboard.sock; } } server { listen 443 ssl http2; server_name www.mywebsite.com; # redirect return 301 https://mywebsite.com.com$request_uri; } server { listen 443 ssl http2; server_name mywebsite.com; } -
Django JWT token auth: What does JWT_AUTH_COOKIE do
I am trying to use JWT auth method for authentication. I checked dj-rest-auth has the setting JWT_AUTH_COOKIE and JWT_AUTH_REFRESH_COOKIE whats the role of these tokens. I dont see any mention of these tokens in the documentation of djangorestframework-simplejwt https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html