Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stop Django cache clearing on server refresh
In my Django project I want to stop the cache from clearing whenever the server is restarted. Such as when I edit my views.py file, the cache is cleared and I get logged out which makes editing any features exclusive to logged in users a pain. settings.py SESSION_ENGINE = "django.contrib.sessions.backends.cache" What configurations would stop cache clearing on server refresh? -
I cannot show media images in templates
I cannot show media images in the templates. I looked up similar issues on Stackoverflow but those solutions did not work for me. I have tried adding load static at the beginning of the template. Also, I tried adding a media root with the static method in the urls.py module. Additionally, I have been attempting to use {{object.image.url}} template tag. I used all these mentioned options to view images in the template, but without the success. Here is the code sample. models.py import os from business.models import Business from django.conf import settings from django.db import models def image_upload(instance, filename): file_path = os.path.join(settings.MEDIA_ROOT, instance.req_object, "deals") if not os.path.exists(file_path): os.makedirs(file_path) return os.path.join(file_path, filename) class Deal(models.Model): business = models.ForeignKey( to=Business, on_delete=models.CASCADE, related_name="business_deal" ) title = models.CharField(max_length=120) description = models.TextField() excerpt = models.CharField(max_length=120) image = models.ImageField( upload_to=image_upload, null=True, blank=True, max_length=250 ) from_date = models.DateTimeField() to_date = models.DateTimeField() member_only = models.BooleanField(default=False) req_object = None forms.py from deals.models import Deal from django import forms class DealForm(forms.Form): image = forms.FileField(required=False) title = forms.CharField(required=True) description = forms.CharField(required=True, widget=forms.Textarea) excerpt = forms.CharField(required=True) from_date = forms.DateField(required=True) to_date = forms.DateField(required=True) urls.py from the core directory from core import views from django.conf import settings from django.conf.urls.static import static from django.contrib import admin … -
What is wrong with my list and why does it give an error?
enter image description here what is wrong with my list and why does it give an error? what is wrong with my list and why does it give an error? -
Are API fetch requests indexed by search engines?
I'm creating a personal blogging site using Django and React. I was planning on blog post content using the JavaScript fetch API, and i was wondering if the body text of the blog posts would appear in search engine content? -
How do I create a follow - follow system in my django project?
I'm trying to create a follow - following system like instagram / twitter but i'm struggling to get the POST action to work and change the follows field. I've created the models.py, the url.py and a button form on the profile.html template, but cannot get the views.py to work with my class based detail profile view. If I update the follows in the admin panel, the button shows the right info, e.g if logged in user is following the viewed user profile it shows 'unfollow', and if they're not followed, it shows 'follow' But everytime I click "follow" button, on the users profile, it throw: [10/Mar/2023 08:26:06] "POST /user/peter HTTP/1.1" 405 0 and the browser does not load. I do not know if the profile function should be part of the detailed profile view, or separate so it can be applied to any list views of users, or maybe there's a better way for class based views — first time posting here, any help making this work is appreciated. Users can also create 'products' which is a separate model in models.py, which are shown on the users profile. Model.py if I update in the backend the correct follow button is … -
How to show options in Django-select2 ModelSelect2MultipleWidget
I want to implement the ModelSelect2MultipleWidget, what i get in the template is an text field where i can type. However no options are shown as a dropdown. If i print the "value" in the CustomCheckboxSelectMultiple i get nothing. So the problem is i dont get the options. I need to change the id_contract with the value. class CustomCheckboxSelectMultipleWidget(s2forms.ModelSelect2MultipleWidget): search_fields = ["functie__icontains"] def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): option = super().create_option(name, value, label, selected, index, subindex=subindex, attrs=attrs) ////--> print(value) is not giving me anything contract = Contract.objects.get(pk=f"{value}") option['attrs']['id'] = f'id_contract_{value}' option['label'] = f"{contract.werknemer.first_name} {contract.person.last_name} | {contract.functie}" return option And the form: class EventForm(forms.ModelForm): contract = forms. ModelMultipleChoiceField( queryset=Contract.objects.all(), widget=CustomCheckboxSelectMultiple(), --> here i select the custom widget ) class Meta: model = PlanningEvent fields = '__all__' In the template is did add the media thing {{ form.media.css }} {{ form.media.js }} -
source code of crystal report on online examination system project in python
source code for making crystal report on topic online examination system in python. . Don't know the source code of making crystal report. -
Cargo, the Rust package manager, is not installed or is not on PATH Django app deployment on vercel error
Error: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt error: subprocess-exited-with-error × Preparing metadata (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [6 lines of output] Cargo, the Rust package manager, is not installed or is not on PATH. This package requires Rust and Cargo to compile extensions. Install it through the system's package manager or via https://rustup.rs/ Checking for Rust toolchain.... [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed BUILD_FAILED: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt error: subprocess-exited-with-error × Preparing metadata (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [6 lines of output] Cargo, the Rust package manager, is not installed or is not on PATH. This package requires Rust and Cargo to compile extensions. Install it through the system's package manager or via https://rustup.rs/ Checking for Rust toolchain.... [end of output] note: This error originates from a subprocess, and is likely not a problem with pip.error: metadata-generation-failed× Encountered error while generating package metadata.╰─> See above for output.note: This is an issue with the package mentioned above, not pip.hint: See above for details.Collecting anyio==3.6.2 Downloading anyio-3.6.2-py3-none-any.whl (80 … -
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 …