Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO - index.html or any of the react code that is in the frontend is not found
enter image description here following a youtube video and now i am getting this error. project not running when calling python manage.py runserver below it's the settings.py and urls.py thanks for any help in advance. Just trying to learn how to combine both a django and a react app settings. py 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', 'api.apps.ApiConfig', 'rest_framework', 'corsheaders' #added ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'todo_drf.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, '/frontend/build') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = 'static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'frontend/build/static')] CORS_ORIGIN_WHITELIST = [ "http://localhost:3000", ]#added urls.py from django.contrib import admin from django.urls import path, include # view to render react build index.html from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('', TemplateView.as_view(template_name='index.html')), ] -
Update dropdown button without submit button in Django
I'm using Django and I have dropdown button that shows the current selected value and the rest of items in dropdown list. How can I make the user change the selection and reflect that change on the db without having to press update button. My models are usecase, and kpi (fk of usecase) my views.py: @user_login_required def view_usecase_details(request,ucid): usecase_details = Usecase.objects.filter(usecase_id=ucid).all() usecase_details = usecase_details.prefetch_related("usecaseids") uckpi = Kpi.objects.all() context = {'usecase_details': usecase_details, "uckpi": uckpi} return render(request, 'UsecaseDetails.html', context) my template: {% if usecase_details is not none and usecase_details %} <div class="card card-body shadow-sm mb-4 mb-lg-0"> {% for result in usecase_details %} <div class="d-flex align-items-center"> <svg class="mr-svg stc-color" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-bookmark-fill" viewBox="0 0 16 16"> <path d="M2 2v13.5a.5.5 0 0 0 .74.439L8 13.069l5.26 2.87A.5.5 0 0 0 14 15.5V2a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2z"></path> </svg> <h2 class="header-card h5">{{result.usecase_id}} - {{result.usecase_name}}</h2> </div> <ul class="list-group list-group-flush"> <li class="list-group-item d-flex align-items-center justify-content-between px-0 border-bottom"> <div> <h3 class="h6 mb-1 mt-15">Usecase description:</h3> <p class="small pe-4">{{result.usecase_description}}</p> </div> </li> </ul> <ul class="list-group list-group-flush"> <li class="list-group-item d-flex align-items-center justify-content-between px-0 border-bottom"> <div class="btn-group"> <button type="button" class="btn btn-secondary">KPI: {{result.kpi.kpi_name}}</button> <button type="button" class="btn btn-secondary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false"> <svg class="icon icon-xs" fill="currentColor" viewBox="0 0 20 … -
Django Group By Aggregation works until additional fields added
I'd like to group the following track variations at the given circuit so on an index page I only have a single entry for each circuit. On a subsequent circuit detail page I will show the various configurations. If I keep the query simple as below it works. track_listing = (Tracks.objects .values('sku', 'track_name') .annotate(variations=Count('sku')) .order_by() ) However adding other fields such as track_id or location breaks or changes the grouping. track_listing = (Tracks.objects .values('sku', 'track_name', 'track_id') .annotate(variations=Count('sku')) .order_by() ) Is there a way to keep the group while including other fields. The location is not unique to each row and having one example of track_id allows me to retrieve a track image. Thanks -
How to insert links into a js file in django so that the function changes the style files?
I'm trying to make a button that changes the site to a dark/light theme. In vs code, my code works completely, but nothing happens in pycharm on django. script.js file: let switchMode = document.getElementById("switchMode"); switchMode.onclick = function () { let theme = document.getElementById("theme"); if (theme.getAttribute("href") == "dark-mode.css") { theme.href = "light-mode.css"; } else { theme.href = "dark-mode.css"; } } button: <li class="nav-item" id="switchMode"> <img class="header__moon" src="{% static "img/Moon.svg" %}" alt="" > </li> -
Object of type is not JSON serializable Django
Django project - sending email. There is a view function that receives a POST request, loops through all the emails from the database and passes the request parameters to the Celery task. The Celery task is sending an email through the standard Django function, but the emails are not sent. Displays an inscription in the terminal: Object of type is not JSON serializable. I do not understand how to fix this so that everything works? view.py: from django.shortcuts import render, redirect from django.core.mail import send_mail from .forms import * from .models import * from . import tasks from djsender.settings import API_KEY import requests def send_some_email(request): if request.method == 'POST': form = EmailForm(request.POST) if form.is_valid(): from_mail = form.cleaned_data['from_mail'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] cat = form.cleaned_data['cat'] limit = form.cleaned_data['limit'] for element in Emails.objects.filter(active=True, category__name=cat)[:limit]: try: tasks.send.delay(from_mail, subject, message, element.address) except Exception as ex: print(ex) return redirect('error') print(str(element)) element.active = False element.save() return redirect('home') else: form = EmailForm() return render(request, 'emails/index.html', {'form': form}) tasks.py import time from django.core.mail import send_mail @shared_task def send(from_mail: str, subject: str, message: str, to_email: str): time.sleep(20) send_mail(subject=subject, from_email=from_mail, message=message, recipient_list=[to_email, ]) return True I tried to cycle through the models directly in the Celery task, but … -
Making a robust django chatterbot
I've been practicing with Django Chatterbot by integrating it with a Rest API but I've been having some problems with the functionality. The API is recipe based so the Chatbot View is set up to communicate with the user and find them the perfect recipe to match their inputed ingredients. Here's what the code looks like (sorry its long): class RecipeBot(APIView): def post(self, request): message = request.data['message'] # Initialize a chatbot instance bot = ChatBot('Bot') # Train the chatbot with recipes and their ingredients recipes = Recipe.objects.all() trainer = ListTrainer(bot) for recipe in recipes: trainer.train([recipe.recipe] + [ri.ingredient.ingredient for ri in recipe.ingredients.all()]) # Extract the ingredients from the user message def extract_ingredients(message): ingredient_list = [ingredient.ingredient.lower() for ingredient in UserIngredient.objects.all()] words = nltk.word_tokenize(message.lower()) ingredients = [] for word in words: if word in ingredient_list: ingredients.append(word) return ingredients # Filter recipes by ingredients def filter_recipes_by_ingredients(ingredients): recipes = Recipe.objects.all() filtered_recipes = [] for recipe in recipes: recipe_ingredients = [ri.ingredient.ingredient.lower() for ri in recipe.ingredients.all()] if all(ingredient.lower() in recipe_ingredients for ingredient in ingredients): filtered_recipes.append(recipe) return filtered_recipes state = 'searching' # Define the get_response() function outside of the post() function def get_response(message, state, filtered_recipes): # Search for recipes based on ingredients if state == 'searching': ingredients = … -
Iam trying to connect my android application and my django server for sending data from androiod application to django server but an error is occured
2023-03-12 11:22:06.372 26197-26197/com.example.demo_app_java W/System.err: com.android.volley.NoConnectionError: java.net.SocketException: socket failed: EPERM (Operation not permitted) 2023-03-12 11:22:06.372 26197-26197/com.example.demo_app_java W/System.err: at com.android.volley.toolbox.NetworkUtility.shouldRetryException(NetworkUtility.java:173) 2023-03-12 11:22:06.372 26197-26197/com.example.demo_app_java W/System.err: at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:145) 2023-03-12 11:22:06.372 26197-26197/com.example.demo_app_java W/System.err: at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:132) 2023-03-12 11:22:06.372 26197-26197/com.example.demo_app_java W/System.err: at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:111) 2023-03-12 11:22:06.372 26197-26197/com.example.demo_app_java W/System.err: at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:90) 2023-03-12 11:22:06.372 26197-26197/com.example.demo_app_java W/System.err: Caused by: java.net.SocketException: socket failed: EPERM (Operation not permitted) 2023-03-12 11:22:06.372 26197-26197/com.example.demo_app_java W/System.err: at java.net.Socket.createImpl(Socket.java:517) 2023-03-12 11:22:06.372 26197-26197/com.example.demo_app_java W/System.err: at java.net.Socket.getImpl(Socket.java:577) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at java.net.Socket.setSoTimeout(Socket.java:1203) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:116) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:186) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:262) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at com.android.volley.toolbox.HurlStack.createOutputStream(HurlStack.java:319) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at com.android.volley.toolbox.HurlStack.addBody(HurlStack.java:301) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:285) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:257) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at com.android.volley.toolbox.HurlStack.executeRequest(HurlStack.java:89) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:104) 2023-03-12 11:22:06.373 26197-26197/com.example.demo_app_java W/System.err: ... 3 more Connection between android app and django n server -
What is settings, asgi, urls, wsgi in Django project?
i recently started learning django and ran into a lot of problems, firstly when i create a django project, i get a lot of files like asgi, settings, urls, i have no idea what that means! Can someone explain in the simplest terms? I'm trying to figure it out! -
How to save a json object in django
i am trying to develop a system which displays a list of experts in a topic when that particular topic is searched. The search function is working and the list of experts (result) is generated from an API which is in form of a list of json objects as shown below: result={ "experts":[ { "thumbnail": "https://scholar.googleusercontent.com/citations?view_op=small_photo&user=JicYPdAAAAAJ&citpid=2", "name": "Geoffrey Hinton", "link": "https://scholar.google.com/citations?hl=en&user=JicYPdAAAAAJ", "author_id": "JicYPdAAAAAJ", "email": "Verified email at cs.toronto.edu", "affiliations": "Emeritus Prof. Comp Sci, U.Toronto & Engineering Fellow, Google", "cited_by": 638900, "interests": [ { "title": "machine learning", "serpapi_link": "https://serpapi.com/search.json?engine=google_scholar_profiles&hl=en&mauthors=label%3Amachine_learning", "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:machine_learning" }, { "title": "psychology", "serpapi_link": "https://serpapi.com/search.json?engine=google_scholar_profiles&hl=en&mauthors=label%3Apsychology", "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:psychology" }, { "title": "artificial intelligence", "serpapi_link": "https://serpapi.com/search.json?engine=google_scholar_profiles&hl=en&mauthors=label%3Aartificial_intelligence", "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:artificial_intelligence" }, { "title": "cognitive science", "serpapi_link": "https://serpapi.com/search.json?engine=google_scholar_profiles&hl=en&mauthors=label%3Acognitive_science", "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:cognitive_science" }, { "title": "computer science", "serpapi_link": "https://serpapi.com/search.json?engine=google_scholar_profiles&hl=en&mauthors=label%3Acomputer_science", "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:computer_science" } ] }, { "thumbnail": "https://scholar.googleusercontent.com/citations?view_op=small_photo&user=kukA0LcAAAAJ&citpid=3", "name": "Yoshua Bengio", "link": "https://scholar.google.com/citations?hl=en&user=kukA0LcAAAAJ", "author_id": "kukA0LcAAAAJ", "email": "Verified email at umontreal.ca", "affiliations": "Professor of computer science, University of Montreal, Mila, IVADO, CIFAR", "cited_by": 605714, "interests": [ { "title": "Machine learning", "serpapi_link": "https://serpapi.com/search.json?engine=google_scholar_profiles&hl=en&mauthors=label%3Amachine_learning", "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:machine_learning" }, { "title": "deep learning", "serpapi_link": "https://serpapi.com/search.json?engine=google_scholar_profiles&hl=en&mauthors=label%3Adeep_learning", "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:deep_learning" }, { "title": "artificial intelligence", "serpapi_link": "https://serpapi.com/search.json?engine=google_scholar_profiles&hl=en&mauthors=label%3Aartificial_intelligence", "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:artificial_intelligence" } ] } ] } Now this "result" object is directly passed to an appropriate html … -
seems some files are not found , how to fix it
when i try to post new post and upload files or images from admin panel it still loading and at end it show error 500 request timeout and I have found in error_log file this error , i am using django 3.0.3 + python 3.7 + namecheap shared hosting the error : Internal Server Error: /admin/blog_app/trainer/add/ Traceback (most recent call last): File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 106, in _get_response response = middleware_method(request, callback, callback_args, callback_kwargs) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/middleware/csrf.py", line 294, in process_view request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 102, in _get_post self._load_post_and_files() File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/http/request.py", line 326, in _load_post_and_files self._post, self._files = self.parse_file_upload(self.META, data) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/http/request.py", line 286, in parse_file_upload return parser.parse() File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/http/multipartparser.py", line 236, in parse for chunk in field_stream: File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/http/multipartparser.py", line 376, in __next__ output = next(self._producer) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/http/multipartparser.py", line 508, in __next__ for bytes in stream: File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/http/multipartparser.py", line 376, in __next__ output = next(self._producer) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/http/multipartparser.py", line 439, in __next__ data = self.flo.read(self.chunk_size) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/http/request.py", line 355, in read return self._stream.read(*args, **kwargs) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 40, in read result = self.buffer + self._read_limited(size - len(self.buffer)) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 28, in _read_limited result = self.stream.read(size) SystemError: <method 'read' of … -
Django, retrieve and display posts under the same category as the post in the details view
I'm trying to create a side menu for all the posts that are under the same category as the post being viewed, like a "Related Posts" menu type of thingy. What would be the best approach to achieve this? Thanks in advance. ~ Shimmy Ko-ko Bop -
Nested For Loops through certain attributes in Django Templates
I want to use a nested for loop to iterate through all the items of my model, but also through the selection of the fields I decide in this model only! The idea is to display all the items in a data table but only with the fields I have chosen. Here is what I have tried: ` <table class="table table-bordered" id="example" style="text-align: center; font-size: 14px;"> <thead class="table-success"> <tr> {% for verb in verbose %} <th>{{ verb }}</th> {% endfor %} </tr> </thead> <tr> {% for test in tests %} {% for f in fields %} <td class="body-table" style="padding: 1px;">{{test}}.{{f}} </td> {% endfor %} {% endfor %} </tr> </table> I let the error which I think is self explainable{{test}}.{{f}}` Thanks a lot in advance! Its my first post here ;) -
How to use a map function insted of a Loop Python
I am working on django project. I would like to avoid use Loop because of a number of row in the file to upload. With a loop, I have this (it's nicely working with small files): my_list = [] for ligne in my_json: network = Network( x1=ligne["x1"], x2=ligne.get("x2", None), x3=ligne.get("x3", None), ) my_list.append(network) I try to use python map fucntion like: my_map = map( lambda x: (x["x1"], x.get("x2"), x.get("x3")), my_json) list(my_map) How can I do that with map -
how to implement login using JWT Authentication
class LoginView(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def post(self,request): email = request.data.get('email') password = request.data.get('password') token = request.data.get('token') user = TokenAuthentication(email=email,password=password,token=token) if user is not None: return Response(user,status=status.HTTP_200_OK) this is the function of login via regular tokens but i want to use JWT tokens but can't figure out how. -
why when I use Inlineformset do I have many fields diplayed in template?
i'am beginner on django and i try to use and understand how an single page, It is possible to display questions from a model and response from another model which is related to the first with a FK. So, I use inlineformset in my views, but in my template I have 4 fields with the same label. my models.py class Studiesquestion(models.Model): title = models.CharField(max_length=255, null=False) question = models.TextField(null=False) information = models.CharField(max_length=500, null=True, blank=True) class Studiesresponse(models.Model): question = models.ForeignKey(Studiesquestion, on_delete=models.CASCADE) response = models.TextField(null=True, blank=True) my view def marketstudiesResponse(request): question = Studiesquestion.objects.get(pk=3) BookFormSet = inlineformset_factory(Studiesquestion, Studiesresponse, fields = ["response"]) print(BookFormSet) if request.method == "POST": formset = BookFormSet(request.POST, instance=question) if formset.is_valid(): formset.save() print("ok") return HttpResponseRedirect('/thanks/') else: formset = BookFormSet(instance=question) print(formset) return render(request, "marketing/marketstudiesResponse.html", {'formset': formset }) my template <form method="POST"> {% csrf_token %} {{formset.as_p}} <button type="submit" class="btn btn-primary">submit</button> </form> my html do it <form method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value="GtyCWorBXXzGWz5qYTC2GZfREjPMqmFZyn0n4yIgCqpVb5E1JMSJs5maeuJcdrjW"> <input type="hidden" name="studiesresponse_set-TOTAL_FORMS" value="3" id="id_studiesresponse_set-TOTAL_FORMS"><input type="hidden" name="studiesresponse_set-INITIAL_FORMS" value="0" id="id_studiesresponse_set-INITIAL_FORMS"><input type="hidden" name="studiesresponse_set-MIN_NUM_FORMS" value="0" id="id_studiesresponse_set-MIN_NUM_FORMS"><input type="hidden" name="studiesresponse_set-MAX_NUM_FORMS" value="1000" id="id_studiesresponse_set-MAX_NUM_FORMS"> <p><label for="id_studiesresponse_set-0-response">Response:</label> <textarea name="studiesresponse_set-0-response" cols="40" rows="10" id="id_studiesresponse_set-0-response"></textarea></p> <p><label for="id_studiesresponse_set-0-DELETE">Delete:</label> <input type="checkbox" name="studiesresponse_set-0-DELETE" id="id_studiesresponse_set-0-DELETE"><input type="hidden" name="studiesresponse_set-0-id" id="id_studiesresponse_set-0-id"><input type="hidden" name="studiesresponse_set-0-question" value="3" id="id_studiesresponse_set-0-question"></p> <p><label for="id_studiesresponse_set-1-response">Response:</label> <textarea name="studiesresponse_set-1-response" cols="40" rows="10" id="id_studiesresponse_set-1-response"></textarea></p> <p><label for="id_studiesresponse_set-1-DELETE">Delete:</label> <input type="checkbox" name="studiesresponse_set-1-DELETE" id="id_studiesresponse_set-1-DELETE"><input type="hidden" name="studiesresponse_set-1-id" id="id_studiesresponse_set-1-id"><input type="hidden" … -
Resizing image in javascript before uploading to server doesn't work
In my Django project, I used a form in a template html allowing users to upload images to the server. I used basic Django **ModelForm** with **ImageField** model and a basic view. Nothing special. I attached the following **JavaScript** file to that template: // Get the file input element const input = document.getElementById('id_image'); // Listen for the "change" event on the file input input.addEventListener('change', (event) => { // Get the selected file const file = event.target.files[0]; console.log(file); // Create a new FileReader object const reader = new FileReader(); // Set the onload event handler reader.onload = (event) => { // Create a new image object const img = new Image(); // Set the onload event handler img.onload = () => { // Set the maximum size of the image const max_size = 800; // Calculate the new width and height while maintaining aspect ratio let width, height; if (img.width > img.height) { width = max_size; height = img.height * (max_size / img.width); } else { height = max_size; width = img.width * (max_size / img.height); } // Create a canvas element const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; // Draw the resized image onto the canvas const … -
Django child model's Meta not available in a @classmethod
I am trying to write a check for django abstract base model that verifies some facts about the inner Meta of a derived class. As per documentation the check is a @classmethod. The problem is that in the method the cls parameter is the correct type of the derived class (Child1 or Child2), but its Meta is the Base.Meta and not the Meta of the appropriate child class. How can I access the inner Meta of a child model in a base model's @classmethod? I've tried both with a simple Meta class (no base class - Child1 below) and with one that derives from the base class' Meta (Child2) - as per https://docs.djangoproject.com/en/4.1/topics/db/models/#meta-inheritance from django.db import models class Mixin: @classmethod def method(cls): print(f"{cls=}, {cls.Meta=}") print([attr for attr in dir(cls.Meta) if not attr.startswith("__")]) class Base(Mixin, models.Model): name = models.TextField(blank=False, null=False) age = models.IntegerField(blank=False, null=False) class Meta: abstract = True class Child1(Base): city = models.TextField(blank=True, null=True) class Meta: db_table = "city_table" verbose_name = "12345" class Child2(Base): city = models.TextField(blank=True, null=True) class Meta(Base.Meta): db_table = "other_city_table" verbose_name_plural = "qwerty" Child1.method() Child2.method() In both cases the output is: cls=<class 'mnbvc.models.Child1'>, cls.Meta=<class 'mnbvc.models.Base.Meta'> ['abstract'] cls=<class 'mnbvc.models.Child2'>, cls.Meta=<class 'mnbvc.models.Base.Meta'> ['abstract'] While I want cls.Meta to be … -
Avoid simultaneous concurrent sessions django
I am developing a website which authenticates it's users based on mobile number already registered in external application's database and allows further journey on the website. How do I avoid users to authenticate with same mobile number from two different devices at the same time. I am using django framework for website's development?. Note: Django's auth model is not being used here. Also each session will timeout after 30 mins of inactivity, which is being handled by django-session-timeout library. Use of custom database and tables is allowed. -
A timeout error occurred when trying to upload an image in a Django application that is hosted on a cPanel server
Request Timeout This request takes too long to process, it is timed out by the server. If it should not be timed out, please contact the administrator of this web site to increase 'Connection Timeout'. -
Generating a unique code/string in Django database
All I want is to generate a unique code preferably a mix of both letters and numbers when I create a Model Class called Competition in django. I want to use this code as a reference code for users to be able to fill in a form that will allow them to join that specific Competition. I have this code in my models.py: class Competition(models.Model): name = models.CharField(max_length=100) location = models.CharField(max_length=50) no_of_rounds = models.IntegerField(validators= [MinValueValidator (1, message='Please enter a number greater than or equal to 1'), MaxValueValidator (30, message='Please enter a number less than or equal to 30')]) gates_per_round = models.IntegerField(validators= [MinValueValidator (1), MaxValueValidator (30)]) ref_code = models.CharField( max_length = 10, blank=True, editable=False, unique=True, default=get_random_string(10, allowed_chars=string.ascii_uppercase + string.digits) ) def __str__(self): return self.name Preferably I don't want the unique code field to be a primary key if possible and that's why I have that field called ref_code. I tried creating a competition, which generated me this code LZDMGOQUFX. I am also wondering why the code only consists of letters. Anyways I tried creating a different competition but it raises an IntegrityError that says UNIQUE constraint failed in my ref_code field. Someone send help, thanks. -
django finding file in custom static folder returns none
trying to find file in custom static folder and it returns none i created a folder named 'static_test' in the project folder and added 'STATICFILES_DIRS' in settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = [ ("test",os.path.join(BASE_DIR, 'static_test')) ] also added static_url to urlpatterns in the main folder urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and when i call on find a file (in the folder) it return none from django.contrib.staticfiles import finders ... value = 'file.png' finders.find(value) i checked 'finders.searched_locations' and the folder is there is there anything i'm missing or .. ?? -
In which it is better to make an e-commerce shopping cart function in django or js
Hi I'm wondering if my way of making a shopping cart is good, all the tutorials I see on the web rather insist on doing it using js rather than recording it in a model table. class Cart(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def total(self): user_cart = Cart.objects.get(user=self.user) items_in_cart = CartItem.objects.filter(cart=user_cart) total_price = 0 for item in items_in_cart: total_price += item.product.price return total_price def quantity_of_items(self): user_cart = Cart.objects.get(user=self.user) items_in_cart = CartItem.objects.filter(cart=user_cart) return len(items_in_cart) class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) view to save class ProductDetailView(View): def get(self, request, pk): product = Product.objects.get(id=pk) context = {'object': product} return render(request, "products/detailview.html", context) def post(self, request, pk): if not request.user.is_authenticated: messages.success(request, "You must be logged in") return redirect('Login') cart, created = Cart.objects.get_or_create( user=request.user, ) cart.save() added_item = Product.objects.get(id=pk) added_item.popularity += 1 added_item.save() item_in_cart = CartItem.objects.filter(cart=cart) for item in item_in_cart: if item.product.title == added_item.title: messages.success(request, "It's already in the basket") return redirect('ProductDetail', pk=pk) new_item_in_cart = CartItem.objects.create( product=added_item, cart=cart, ) new_item_in_cart.save() added_item.quantity -= 1 if added_item.quantity == 0: added_item.is_available = False added_item.save() messages.success(request, "Add to cart") return redirect('home') With the help of redis I check every hour the time of the last change of the basket if it is greater than 1 hour … -
locate Error in django templates with multi inheritance
The issue occures when i'm rendering a template from a view, the template itself is including other templates, that also needs other templates and so forth, when an error happened at some leve.The console shows ONLY that there is an error when rendering the main template from the view, and it takes a lot of time to know exactly which template in the chain has the error, not like if the error happend in the .py file where it gives the exact file with the error. My current approach to help me debbuging is to use a function that is called from each file that is called each time, so at least i mimise the scope, are there better ways to do the job. -
Django Custom Commands Not Creating New Entries
I'm pretty new to Django, and I'm working on a simple app that generates json forecast data for a list of locations daily. This data is then used to display the forecasts to the user. I have a startjobs.py set up to run some functions that generate the json data I need for my app. I'm running into a problem where the jobs are successfully running, however, no new entries are added and no new json files created. I've looked through some similar questions, but couldn't find any solutions that work for my case. Here are my models: class Location(models.Model): location = models.CharField(max_length = 75, unique = True) def __str__(self): return f"{self.location}" INTERVAL_CHOICES = [ ('today', 'Today'), ('hourly', 'Hourly'), ('daily', 'Daily'), ] class Forecast(models.Model): location = models.ForeignKey(Location, on_delete = models.CASCADE) date = models.DateField() interval = models.CharField(max_length = 6, choices = INTERVAL_CHOICES, default = 'today') filename = models.FileField(upload_to = 'test/') def __str__(self): return f"Forecast for max wave height - {self.interval} in {self.location} on {self.date}" And my startjobs.py (I have my job running every 2 minutes for testing): locations = Location.objects.values_list("location", flat=True) def save_new_forecasts(): date = dt.date.today().strftime("%Y-%m-%d") for location in locations: if not Forecast.objects.filter(date = date).exists: daily_data = create_daily_forecast(location) hourly_data = create_hourly_forecast(location) … -
Why is refresh token not being returned from TokenRefreshView?
I'm using DRF-simple-jwt to implement auth. Since I want the tokens to be returned in a cookie instead of the response, I'm using the code I found in this github issue, where people have a workaround for sending the token in the cookie (as this is not implemented in the package). The issue for me is, in the CookieTokenRefreshView, "refresh" is not present in the response data. Because of which I'm getting a 500. The specific error is: ValueError: The view team.views.auth_viewset.view didn't return an HttpResponse object. It returned None instead None is being returned because the else condition is not being handled in the finalize_response of CookieTokenRefreshView. Why is it not present? The CookieTokenRefreshView: class CookieTokenRefreshView(TokenRefreshView): def finalize_response(self, request, response, *args, **kwargs): print("REFRESH -> ",response.data.get("refresh")) if response.data.get("refresh"): cookie_max_age = 3600 * 24 * 14 response.set_cookie( "refresh_token", response.data["refresh"], max_age=cookie_max_age, httponly=True, secure=True, samesite='Strict' ) # don't return tokens in response del response.data["refresh"] return super().finalize_response(request, response, *args, **kwargs) serializer_class = CookieTokenRefreshSerializer Apologies if this is a dumb question, I'm very new to both django and backend in general.