Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Channels does not connect to redis on heroku
I am using django chanels for sending real time notification, on the local development server it works fine with redis url redis://127.0.0.1:6379 but when I go to production on Heroku it couldn't connect meanwhile celery works fine on the same redis url on Heroku. this is the channel layer I am using and the REDIS_URL is set properly in the environment variables both locally and on production. CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [env('REDIS_URL', default='redis://localhost:6379')], }, }, } The Error I get is the following: 2023-03-12T13:15:29.051013+00:00 app[web.1]: ERROR 2023-03-12 13:15:29,047 server 2 140084942075712 Exception inside application: Error 1 connecting to ec2-50-17-163-82.compute-1.amazonaws.com:7550. 1. 2023-03-12T13:15:29.051015+00:00 app[web.1]: Traceback (most recent call last): 2023-03-12T13:15:29.051016+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/redis/asyncio/connection.py", line 603, in connect 2023-03-12T13:15:29.051016+00:00 app[web.1]: await self.retry.call_with_retry( 2023-03-12T13:15:29.051016+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/redis/asyncio/retry.py", line 59, in call_with_retry 2023-03-12T13:15:29.051017+00:00 app[web.1]: return await do() 2023-03-12T13:15:29.051017+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/redis/asyncio/connection.py", line 640, in _connect 2023-03-12T13:15:29.051017+00:00 app[web.1]: reader, writer = await asyncio.open_connection( 2023-03-12T13:15:29.051018+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/streams.py", line 52, in open_connection 2023-03-12T13:15:29.051019+00:00 app[web.1]: transport, _ = await loop.create_connection( 2023-03-12T13:15:29.051019+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/base_events.py", line 1090, in create_connection 2023-03-12T13:15:29.051019+00:00 app[web.1]: transport, protocol = await self._create_connection_transport( 2023-03-12T13:15:29.051019+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/base_events.py", line 1120, in _create_connection_transport 2023-03-12T13:15:29.051020+00:00 app[web.1]: await waiter 2023-03-12T13:15:29.051020+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/sslproto.py", line … -
Cutting stock problem methods and techniques
I have taken an interest in creating a web app using React based on cutting stock problem. I have some questions about the topic: Should i pair React with Django or is there better alternative? I'm gonna implement two algorithms each for 1 Dimensional and 2 Dimensional (So 4 in total). What algorithms should i implement? Is there any recommended resources online that will aid me in my work? Result: A simple cutting stock problem app -
Django not displaying images through pagination container bootstrap class
Django images are only showing icons not full image when a user tries to post a new image onto the platform. i created a products function that was supposed to post onto the main home page of my ecommerce django application product images with prices, only that the prices and all the other information is shown, but for the images, the links to the specific images are working, but the display of the real images is not working. Views.py def products(request): if request.method == 'POST': pagination_content = "" page_number = request.POST['data[page]'] if request.POST['data[page]'] else 1 page = int(page_number) name = request.POST['data[name]'] sort = '-' if request.POST['data[sort]'] == 'DESC' else '' search = request.POST['data[search]'] max = int(request.POST['data[max]']) cur_page = page page -= 1 per_page = max # Set the number of results to display start = page * per_page # If search keyword is not empty, we include a query for searching # the "content" or "name" fields in the database for any matched strings. if search: all_posts = Product.objects.filter(Q(content__contains = search) | Q(name__contains = search)).exclude(status = 0).order_by(sort + name)[start:per_page] count = Product.objects.filter(Q(content__contains = search) | Q(name__contains = search)).exclude(status = 0).count() else: all_posts = Product.objects.exclude(status = 0).order_by(sort + name)[start:cur_page * max] … -
Problems with installing Django project on hosting.(Error: Web application could not be started)
I used hosting Beget. Relying on this instruction of my hosting i tried to locally install this versions of Python==3.7.2 Django==3.2.13. I successfully installed Python and Django. I also configured .htaccess and passenger_wsgi.py files, following this instruction. passenger_wsgi.py: # -*- coding: utf-8 -*- import os, sys sys.path.insert(0, '/home/n/nurtugur/nurtugur.beget.tech/coolsite') sys.path.insert(1, '/home/n/nurtugur/nurtugur.beget.tech/djangoenv/lib/python3.7/site-packages') os.environ['DJANGO_SETTINGS_MODULE'] = 'coolsite.settings' from django.core.wsgi import get_wsgi_application .htaccess: PassengerEnabled On PassengerPython /home/n/nurtugur/nurtugur.beget.tech/djangoenv/bin/python3.7 Error that i got I haven't any ideas of why it doesn't work. I guess only ones that can help me are people who have experience in using Beget hosting. -
Having a error while running a django project from github in vscode editor, Error goes as follows that was displayed on localhost:
Environment: Request Method: POST Request URL: http://127.0.0.1:8000/result/ Django Version: 2.2.13 Python Version: 3.9.0 Traceback: File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/predictor/views.py" in model_form_upload 35. meta = getmetadata(uploadfile) File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/predictor/Metadata.py" in getmetadata 6. y, sr = librosa.load(filename) File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/lazy_loader/init.py" in getattr 77. attr = getattr(submod, name) File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/lazy_loader/init.py" in getattr 76. submod = importlib.import_module(submod_path) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/init.py" in import_module 127. return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>" in _gcd_import 1030. <source code not available> File "<frozen importlib._bootstrap>" in _find_and_load 1007. <source code not available> File "<frozen importlib._bootstrap>" in _find_and_load_unlocked 986. <source code not available> File "<frozen importlib._bootstrap>" in _load_unlocked 680. <source code not available> File "<frozen importlib._bootstrap_external>" in exec_module 790. <source code not available> File "<frozen importlib._bootstrap>" in _call_with_frames_removed 228. <source code not available> File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/librosa/core/audio.py" in <module> 17. from numba import jit, stencil, guvectorize File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/numba/init.py" in <module> 42. from numba.np.ufunc import (vectorize, guvectorize, threading_layer, File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/numba/np/ufunc/init.py" in <module> 3. from numba.np.ufunc.decorators import Vectorize, GUVectorize, vectorize, guvectorize File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/numba/np/ufunc/decorators.py" in <module> 3. from numba.np.ufunc import _internal Exception Type: SystemError at /result/ Exception Value: initialization of _internal failed without raising … -
Javascript for dynamically revealing Django formset forms
I'm trying to add/remove forms from formsets dynamically on button press. I am looking at an older example for JS to perform this action but I have multiple formsets but when I delete all of the forms for one of the formsets, obviously the addForm command no longer works as there are no forms to clone. That being said, I think a functional method would be to start with a hidden form and then copy the hidden form and display that form on demand. I just don't know how exactly to do that. Ideally, I'd like to not show any forms until the button press but not certain about how to do it. My current setup is shown below. HTML: <div class="selection"> <div class="forms"> <!-- {% for dict in formset.errors %} {% for error in dict.values %} {{ error }} {% endfor %} {% endfor %} --> <form id="general-formset" method="POST"> {% csrf_token %} {{ generalFormset.management_form }} {% for form in generalFormset %} <div class="formset"> {{ form.as_table }} <button id="remove-form" type="button" onclick="removeForm(this)" display="None">Remove Constraint</button> </div> {% endfor %} <button id="add-form" type="button" onclick="addForm(this)">Add Constraint</button> </form> <form id="specific-formset" method="POST"> {% csrf_token %} {{ specificFormset.management_form }} {% for form in specificFormset %} <div class="formset"> … -
Why is the drf login page showing me an error of wrong credentials even though i'm using the right credentials?
I'm working on a DRF project and was working on the Custom User Model. I can launch the server without errors and see all the API endpoints. However, after registering a new user, when I try to log in with the user's credentials, I get the error of giving the wrong email or password. I'm using dj-rest-auth for registering new users. Upon going into the admin, I see the notification of a new user being created, but for some reason, my code isn't letting them log in. Here's my models.py file:- import uuid from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import BaseUserManager # Create your models here. GENDER_CHOICES = [ ('M','Male'), ('F','Female'), ('R','Rather not say'), ] class UserManager(BaseUserManager): def create_user(self,First_name:str,Last_name:str,Email:str,password:str,username:str,is_staff = False,is_superuser = False) -> 'User': if not Email: raise ValueError('User must have an Email') if not First_name: raise ValueError('User must have a First Name') if not Last_name: raise ValueError('User must have a Last Name') user = self.model(Email = self.normalize_email(Email)) user.First_name = First_name user.Last_name = Last_name user.set_password(password) user.username = username user.is_active = True user.is_staff = is_staff user.is_superuser = is_superuser user.save() return user def create_superuser(self,First_name:str,Last_name:str,Email:str,password:str,username:str)-> 'User': user = self.create_user( First_name = First_name, Last_name = Last_name, Email=Email, username=username, password=password, … -
Does django have lazy queries in foreign reverse lookup?
I have this code: def get_percentage_completions(task: Task, date_start: date, date_end: date): result = {} execution_percents = task.execution_percents.all() if execution_percents.exists(): year, week, _ = date_start.isocalendar() task_execution_percent = execution_percents.filter(year__lte=year, week__lte=week) \ .order_by('year', 'week').last() execution_percent = task_execution_percent.percent if task_execution_percent else 0 while date_end >= date_start: year, week, _ = date_start.isocalendar() if execution_percents.filter(year=year, week=week).exists(): task_execution_percent = execution_percents.filter(year=year, week=week).first() execution_percent = task_execution_percent.percent key = f"{year}_{week}" result[key] = round(execution_percent) date_start += timedelta(days=7) return result I get related objects from my model "Task". I thoght I hit to db once on second line when I define execution_persents variable, but actually my debug toolbar decrease amount of queries when I comment all lines after execution_persents variable. It means I hit to db inside while loop. Can I hit to db only once on the second line? -
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 …