Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Strategies for Integrate Webpack 5 into a Typical Django Project
I currently use Django Pipeline, which I want to remove and switch to using Webpack 5. I've made some headway in learning Webpack but am currently trying figure out the best project file structure and workflow. A typical Django project file structure like this: ├── django_project │ ├── accounts │ │ ├── migrations │ │ ├── static │ │ │ ├── accounts │ │ │ │ ├── css │ │ │ │ │ ├── custom.css │ │ │ │ │ └── another.css │ │ │ │ ├── img │ │ │ │ │ ├── something.png │ │ │ │ │ └── default.jpg │ │ │ │ ├── js │ │ │ │ │ ├── index.js │ │ │ │ │ └── custom.js │ │ │ │ └── scss │ │ │ │ ├── bootstrap.scss │ │ │ │ └── _custom.scss │ │ ├── templates │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── forms.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ ├── anotherapp │ │ ├── migrations │ │ ├── ... │ ├── django_project │ │ ├── __init__.py │ │ ├── asgi.py │ │ … -
Issue with combining data from multiple Django apps into a single form option in admin back office
I'm a fairly novice developer, but I'm aiming to master Django by developing a multi-tenant SaaS application that lets users create their own online stores. I'm still at the beginning of the project, but I've already run into a problem that's blocking me. My aim is to offer basic categories common to all users, while allowing them to create their own customized categories to classify their products. To achieve this, I've set up a multi-tenant architecture with Django-tenants, where each user has his own subdomain, store and categories. However, I'm having trouble grouping shared and custom categories in the user administration interface form, just where they can add a product (and choose the related category). I want users to be able to choose the category of their products from a list that includes both, shared categories and their own custom categories. I've tried several approaches, including the use of ManyToMany fields and custom widgets, but so far I haven't managed to get the desired result. Shared categories are not properly integrated into the category selection field, which limits the functionality of my application. If you have any suggestions, ideas or pointers on how best to solve this problem and group … -
two django user types
How do you create a doctor and a patient as users in your Django Python project with one view? how do I go about creating the two users? I have tried the role one but it is not working. please if you have tried another one let me see how you did it. -
"SHORT_DATETIME_FORMAT" and "SHORT_DATE_FORMAT" don't work in Django Templates while "DATETIME_FORMAT", "DATE_FORMAT" and "TIME_FORMAT" do
I use DateTimeField(), DateField() and TimeField in MyModel class as shown below. *I use Django 4.2.1: # "models.py" from django.db import models class MyModel(models.Model): datetime = models.DateTimeField() # Here date = models.DateField() # Here time = models.TimeField() # Here def __str__(self): return "MyModel" Then, I set DATETIME_FORMAT, DATE_FORMAT and TIME_FORMAT and set USE_L10N False to make DATETIME_FORMAT, DATE_FORMAT and TIME_FORMAT work in settings.py as shown below: # "settings.py" LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = False # Here USE_TZ = True DATETIME_FORMAT = "m/j/Y, P" # 10/25/2023, 2:30 p.m. # Here DATE_FORMAT = "F jS, Y" # October 25th, 2023 # Here TIME_FORMAT = "H:i:s" # 14:30:15 # Here Then, from a MyModel objcet, I get datetime, date and time and pass them to index.html in test() in views.py as shown below: # "views.py" from django.shortcuts import render from .models import MyModel def test(request): obj = MyModel.objects.all()[0] return render( request, 'index.html', {"datetime": obj.datetime, "date": obj.date, "time": obj.time} ) Then, I show datetime, date and time in index.html as shown below: # "index.html" {{ datetime }}<br/> {{ date }}<br/> {{ time }} Now, all DATETIME_FORMAT, DATE_FORMAT and TIME_FORMAT work according to browser as shown below: 10/25/2023, 2:30 … -
How to save each user's index from Llama index in chatGPT clone app
I am trying to make a chatGPT clone that can answer on external data (private data) using React, Django, OpenAI API, PostgreSQL, and Llama index, precisely speaking, in context learning. Then, my question is, how can I save each user's data (= index in the context of llama index)to PostgreSQL database? I Would like to know which method to store the data in the database is suitable in this case. I find it difficult to store a file or a folder to the database... -
How do I calculate the total number of likes for a user's posts in Django?
I'm working on a Django project and I'm trying to calculate the total number of likes for a user based on their posts (i.e if a user has post with 10 likes and another with 5, the total likes must display 15) . I've tried various approaches, but I haven't been able to get it working. Here is my models.py: class User(AbstractUser): username = models.CharField(...) first_name = models.CharField(...) last_name = models.CharField(...) email = models.EmailField(...) bio = models.CharField(...) ... class Post(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) text = models.CharField(max_length=280) created_at = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, related_name="user_post") def total_likes(self): return self.likes.count() class Meta: ordering = ["created_at"] And here I am trying to display the total number of likes for all posts from a specific user inside this html file (user profile): ... <p>Total likes: {{ post.likes.all.count }} </p> ... views.py @login_required def show_user(request, user_id): try: user = User.objects.get(id=user_id) posts = Post.objects.filter(author=user) except ObjectDoesNotExist: return redirect('user_list') else: return render(request, 'show_user.html', {'user': user , 'posts' : posts, 'request_user': request.user}) Here's what I've tried so far: Initially, I attempted to use the {{ post.likes.all.count }} template tag to display the total number of likes for each post. However, this didn't work as it didn't return … -
Why does Django raise a NoReverseMatch error when using the 'entry' iterator in a For loop and url method?
NoReverseMatch at / Reverse for 'entry' with keyword arguments '{'title': ''}' not found. 1 pattern(s) tried:['wiki/(?P[^/]+)\Z'] Line 12. index.html {% for entry in entries %} <li><a href="{% url 'entry' title=entry %}">{{entry}}</a></li> I am trying to print a list of entries with their links, but Django complains about the iterator 'entry' in the For cycle, it can actually print the elements of the list, but when using the url django method, it won't render the page 'cause that error. urls.py The path: path("wiki/str:title", views.entry, name="entry"), views.py Please a hand. -
Django DRF Serializer slice amount in list of nested field based on user
I want to ask how to slice a nested lists in DRF. I have models Store, Manager, Products. Serializer returns store object with a nested fields. What I want to do is to slice the values, to NOT return all, just to return Store, with top 3 managers and top3 products for each manager. And to do this based on User, if this is supervisor, then return full list, if manager, then only limited. I guess anyway I need to use different serializer for each use type, but how to slice nested value, that only return top 3? Kind regards, -
Django strange static behavior
I launched the small Polls app from Django tutorial here: https://docs.djangoproject.com/en/4.1/intro/tutorial06/ The first time i wrote it, all worked fine. Then I tried to add the same style to all other html files in the same dir as index.html: results.hmtl, votes.html and detail.html and then the strangest thing happened. No styles were added to these files also when i tried to change the style of polls/static/polls/style.css , nothing happened. I even renamed the style.css and the styles added to index.html remained unchanged. This means django looks for styles elsewhere. So where is this place? My settings are standard: settings.py: STATIC_URL = 'static/' STATIC_ROOT = "" index.html: {% load static %} <link rel="stylesheet" href="{% static 'polls/style.css' %}"> urls.py: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('polls/', include('polls.urls')), path('', include('polls.urls')), path('admin/', admin.site.urls) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) No effect whatsoeveer. I read the documentation, read comments here, nothing flashes, so I'm asking here, hoping for a chance to repair my static. Thanks! -
Integrating Firebase authentication with Django (DRF)
I am developing a Django (DRF)/React web application and have integrated Firebase authentication using the email/password provider. The application requires additional user data, and I aim to link the Firebase user database with the Django user model. The primary objective is to implement a secure and efficient authentication system. Workflow: Web client: Users sign up with their email and password, followed by the receipt of a verification email. Web client: Retrieve the ID token and send it, along with extra user data (e.g., first name, last name, organization, role), to the server. Server: Verify the ID token and authenticate the request using the FirebaseAuthentication class. Server: Check if the user exists in the Firebase database. Server: Create a user record in the Django user model if the user exists, ensuring data consistency between Firebase and Django. I have implemented a Django authentication backend using the FirebaseAuthentication class, as shown below: default_app = initialize_app() class FirebaseAuthentication(BaseAuthentication): def authenticate(self, request): auth_header = request.META.get("HTTP_AUTHORIZATION") if not auth_header: raise NoAuthToken("No auth token provided") id_token = auth_header.split(" ").pop() decoded_token = None try: decoded_token = auth.verify_id_token(id_token) except Exception: raise InvalidAuthToken("Invalid auth token") if not id_token or not decoded_token: return None try: uid = decoded_token.get("uid") except Exception: … -
how to create dynamic and interactive(clickable) collapsible topology graph using django
how to create dynamic and interactive(clickable) collapsible topology graph using django i have 3 csv files. 1 icon folder for png files. 1- relational object csv such as below SName|TName|SIcon xxxxx| |M yyyyy|xxxxx|F zzzzz|xxxxx|F aaaaa|yyyyy|D bbbbb|yyyyy|E .... .... 2-major problem csv file enter code here PName|Occtime|ClTime bbbbb|12.12.22| bbbbb|13.05.23|02.06.23 yyyyy|01.06.23|04.06.23 zzzzz|02.03.23| .... .... 3-information csv file PName|LastEvent|Createdby|solution|etc... bbbbb|12.12.22|danaaaaaaa|fromchatg|bla bla... ccccc|11.05.23|dsadadadsa|fromstackov|bla bla.. ..... ..... I want to draw graphs by reading files. if ClTime is not blank in problem csv files i want to change icons's circle colors. also I want to give some informations from the information file when someone clicks any icon. Objects should be static on the page (user should not move objects around on the page). objects should not oscillate. I have little django very little js ,html knowledge but i know python. I searched on the internet, what can I use for this? they suggest treant.js , d3.js, vis.js, networkx. I tried it in sample data but I didn't get the result what I wanted. I don't expect you to give the code. what is the correct method? where should i start and how should i sort it? I created some charts using treantjs. but I couldn't … -
Python/flask/django. I want to make a program similar to discord/teamspeak 3 using django/flask. Question below:
Which libraries should be used in order to make voice chats like in discord/teamspeak and how can this be implemented in the program code (by clicking on the voice. chat a person enters it)? I made text chats only for my messenger, but I didn't find anything for voice chats -
null value in column "name" of relation "contact_contact" violates not-null constraint
DETAIL: Failing row contains (9, null, miarisoa00@yahoo.de, , null). IntegrityError at /contact/contact/ null value in column "name" of relation "contact_contact" violates not-null constraint DETAIL: Failing row contains (9, null, miarisoa00@yahoo.de, , null). Request Method: POST Request URL: http://127.0.0.1:8000/contact/contact/ Django Version: 3.2.15 Exception Type: IntegrityError Exception Value: null value in column "name" of relation "contact_contact" violates not-null constraint DETAIL: Failing row contains (9, null, miarisoa00@yahoo.de, , null). Exception Location: D:\MKSD_SITE\MKSD_WEB\site\lib\site-packages\django\db\backends\utils.py, line 84, in _execute Python Executable: D:\MKSD_SITE\MKSD_WEB\site\Scripts\python.exe Python Version: 3.9.13 Python Path: ['D:\MKSD_SITE\MKSD_WEB\site\src', 'C:\Program Files\Python39\python39.zip', 'C:\Program Files\Python39\DLLs', 'C:\Program Files\Python39\lib', 'C:\Program Files\Python39', 'D:\MKSD_SITE\MKSD_WEB\site', 'D:\MKSD_SITE\MKSD_WEB\site\lib\site-packages'] Server time: Sun, 04 Jun 2023 16:39:42 +0000 # views.py: def Kontact(request): if request.method == 'POST': contact = Contact() message_name = request.POST.get('message-name') from_email = request.POST.get('from-email') ville = request.POST.get('ville') message = request.POST.get('message') contact.name = message_name contact.email = from_email ville = ville contact.subject = message contact.save() message = f""" Name: {message_name} From: {from_email} Stadt: {ville} New message: \n\n{message} """ # Send email send_mail( message_name, #subject message, #message from_email, #from email ['kontakt.mksd@gmail.com'], #to email fail_silently=False, ) return render(request, 'contact.html', {'message_name': message_name}) else: return render(request, 'contact.html', {}) models.py: class Contact(models.Model): name = models.CharField(max_length=50) email = models.EmailField(max_length=50) ville = models.CharField(max_length=100) subject = models.TextField(max_length=355) def __str__(self): return self.name template: <div class="row"> <form method="post" class="was-validated"> … -
Adding request.user to model field in django rest framework upon form submission
I am working on an app using Django and React and I use DRF to create APIs. I have a form that contains a field called submittedUser that I want it to define the user that posted the form in models.py class User(AbstractUser): pass class entry(models.Model): title = models.CharField(max_length=600) submittedUser = models.ForeignKey('User',blank=True,null=True, on_delete=models.CASCADE, related_name='submitteduser') serializers.py: class EntryFormSerializer(serializers.ModelSerializer): class Meta: model = entry fields = ['id','title', 'submittedUser'] views.py: class EntryFormViewSet(APIView): permission_classes = [AllowAny] authentication_classes = [TokenAuthentication] parser_classes = [MultiPartParser, FormParser, JSONParser] @csrf_exempt def post(self, request, format=None): data = request.data serializer = EntryFormSerializer(data=data) if serializer.is_valid(): serializer.save(submittedUser = self.request.user) return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I want upon posting data, the submittedUser field is the loggedin user (request.user in normal django view) but when I post data it gives me error obj = self.model(**kwargs) eError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7f94a584dd80>": "entry.submittedUser" must be a "User" instance. Update: This is the view of the form page itself def formsPage(request): if request.user.is_authenticated: theUser = request.user theUserProfile = userInfo.objects.get(user = theUser.id) if theUserProfile.is_admin: return render(request, 'frontend/index.html') else: return render(request, "frontend/login.html", { "message": " login to continue" }) else: return render(request, "frontend/login.html", { "message": "login to continue" }) so how can I solve this -
Problem with Django Forms to filter by models' field with many to many relationship
I have a problem with a form in Django that would like to filter objects from a Dish model. I would like to filter by objects from the Dish model through the main_ingredient field which has a many-to-many relationship with the MainIngredient model The form now allows you to display separate forms for each of the main_ingredient types However, the bug is in the filter_dishes method. I want this form to return only dish objects for which the main_ingredient selected by the user is 60% of all main_ingredients in the Dish object. For example, the program should return a Dish1 object that has the main_ingredient objects [x1, x2, x3, x4, x5, x6, x7, x8, x9, x10] only when the user selects 6 of these objects in the form. If the user would only select e.g. 4 objects or 10 objects other than those assigned to Dish1 then Dish1 should not be returned. enter image description here **class Dish(models.Model):** name = models.CharField(max_length=50) author = models.ForeignKey(CustomUser, on_delete=models.CASCADE) **main_ingredient = models.ManyToManyField(MainIngredient)** **class MainIngredient(models.Model):** name = models.CharField(max_length=50) type = models.ForeignKey(Type, on_delete=models.CASCADE) def __str__(self): return self.name **class Type(models.Model):** name = models.CharField(max_length=50) def __str__(self): return self.name **class DishFilterForm(forms.Form):** def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) types = … -
Receive input in file format from swagger form (Django)
# model class User(AbstractBaseUser, PermissionsMixin, CommonModel): phone = models.CharField(max_length=20, unique=True) nickname = models.CharField(max_length=20, unique=True) certification_profile = models.URLField(null=True) objects = UserManager() USERNAME_FIELD = "phone" # view class UserCreateView(generics.CreateAPIView): serializer_class = UserCreateSerializer parser_classes = (MultiPartParser,) # serializer class UserCreateSerializer(serializers.ModelSerializer): certification_profile = serializers.FileField(required=False) class Meta: model = get_user_model() fields = ( 'phone', 'nickname', 'certification_profile', ) def create(self, validated_data): certification_profile = validated_data.pop('certification_profile', None) user = get_user_model().objects.create(**validated_data) if certification_profile is not None: image_uuid = str(uuid4()) ## upload file ... user.certification_profile = certification_profile_url user.save() self._create_interests(interests, user) return user The certification_profile column of the User model is URLfield. I would like to receive certification_profile in the form of a file and save it in the form of a url later. So, I specified certification_profile = serializers.FileField(required=False) in UserCreateSerializer. However, as shown in the picture below, the swagger form continues to receive string input. How can I receive input in the form of a file in swagger form? thanks for reading the long post! -
'User matching query does not exist' when adding a like to database
As the title says, I'm trying to make a like button as a many to many where if a certain verse(or post) is liked by a certain user, a like is added to the database, and if a user unlikes a verse, a like is deleted from the database. I have deleteUserLike working, but am not able to create a like on the frontend, as when I do I get the error above on the backend, and user_id appears null in the payload under the network tab in dev tools. VerseCard: const handleCheckChange = (event) => { const { checked } = event.target; if (checked) { createUserLike({ verseId: id, ...userId }); console.warn(userId); } else { const userLike = userLikesArray.find((ul) => ul.verse_id === id); if (userLike) { deleteUserLike(userLike.id); } } }; return ( <> <Card className="text-center" style={{ width: '25rem' }}> <Card.Header>{firstName} {lastName}</Card.Header> <Card.Body> <Card.Title>{verse}</Card.Title> <Card.Text>{content}</Card.Text> <Card.Footer>{version}</Card.Footer> <div style={{ margin: 'auto', display: 'block', width: 'fit-content', }} > <FormControlLabel control={( <Checkbox icon={<FavoriteBorder />} checkedIcon={<Favorite />} name="checkedH" checked={!!userLikesArray.find((ul) => id === ul.verse_id)} onChange={handleCheckChange} /> )} /> userLikeData: const createUserLike = (userLike) => { const userLikeObj = { verse_id: Number(userLike.verseId), user_id: Number(userLike.userId), }; return fetch(`${clientCredentials.databaseURL}/userlikes`, { method: 'POST', body: JSON.stringify(userLikeObj), headers: { 'Content-Type': 'application/json', }, … -
cant pass data between Django and Chartjs
I wanted to pass an array to chartjs for a chart the data is getting passed but for some strange reason the data gets changed, the array contains days of the month [1,2,3,so on] but on chart it displays "[ 0 1 3 5 7 9 0 so on ]" the data is good when I print it to console return render(request, 'notes/home.html',{ 'day':daysOfMonth, }) <div class="mainChart"> <canvas id="myChart"></canvas> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script> const ctx = document.getElementById('myChart'); const days = '{{day}}'; new Chart(ctx, { type: 'bar', data: { labels: days, datasets: [{ // label: '# of Votes', data: [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,], borderWidth: 10 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> </div> -
Unable to see Django project on domain/ip address after Linode deployment - what could be wrong?
I am trying to deploy my django project on linode for my domain address.But I couldn't see project on domain/ip address. I created the existing domain on Linode servers. I set the records as default (A/AAAA Record, MX Record, NS Record and SOA Record). Added the Linode name servers to domain ragistrar's dns settings. I added domain name as reverse dns under Linode Network. In the Django project, I added domain name, and ip address as allowed hosts to settings.py. I've been getting the "This site can't be reached" error for a long time. I used to see the default django page before, now I can't see it either. What could be problem? -
django use aws bucket for static and media files
I've got custom admin panel and api rest-framework django project. S create aws account, user, S3 bucket. My django aws settings: AWS_USERNAME = 'my_username' AWS_GROUP_NAME = 'django_s3_group' # Aws config AWS_ACCESS_KEY_ID = config("SERVER_AWS_ACCESS_KEY_ID", '') AWS_SECRET_ACCESS_KEY = config('SERVER_AWS_SECRET_ACCESS_KEY', '') AWS_FILE_EXPIRE = 200 AWS_PRELOAD_METADATA = True AWS_QUERYSTRING_AUTH = True AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'photo_crm.aws.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'photo_crm.aws.utils.StaticRootS3BotoStorage' S3_DEFAULT_BUCKET = config("S3_DEFAULT_BUCKET", "") AWS_STORAGE_BUCKET_NAME = config('SERVER_AWS_STORAGE_BUCKET_NAME', S3_DEFAULT_BUCKET) S3DIRECT_REGION = 'us-east-1' S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = S3_URL + 'media/' STATIC_URL = S3_URL + 'static/' # ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' ADMIN_MEDIA_PREFIX = STATIC_URL AWS_S3_FILE_OVERWRITE = False two_months = datetime.timedelta(days=61) date_two_months_later = datetime.date.today() + two_months expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT") AWS_HEADERS = { 'Expires': expires, 'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()),), } I move all env to .env file I've got folders in my bucket after command: python manage.py collectstatic It looks like some default staff rest_framework/ django_extensions/ ckeditor/ admin/ In my project I save staticfiles in local static folder: css/ fonts/ js/ img/ svg/ I open template index.html and see that all static imports lights up. So as I understand, django didn't match the static files and S3 bucket. Just example of the file import in … -
How to calculate the number of hours spend inside and the number of hours spend outside for the employee face recognition attendance?
In my company we need to develop an application for the employee face recognition attendance. Per day, an employee after his first entry at 7:30AM can exit and entry several times before the leaving time (3:30PM). So, in this application, we need to record the entries and exits times per employee and per day and calculate the duration hours inside and outside. Here is ours models: class Profile(models.Model): first_name = models.CharField(max_length=70) last_name = models.CharField(max_length=70) date = models.DateField() phone = models.BigIntegerField() email = models.EmailField() # ranking = models.IntegerField() # profession = models.CharField(max_length=200) agence = models.ForeignKey(Agence, on_delete=models.CASCADE, null=True) direction = models.ForeignKey(Direction, on_delete=models.CASCADE, null=True) status = models.CharField(choices=types,max_length=20,null=True,blank=False,default='employee') present = models.BooleanField(default=False) image = models.ImageField() updated = models.DateTimeField(auto_now=True) # shift = models.TimeField() def __str__(self): return self.first_name +' '+self.last_name class LastFace(models.Model): last_face = models.CharField(max_length=200) date = models.DateTimeField(auto_now_add=True) entry = models.TimeField(blank=True, null=True) exit = models.TimeField(blank=True, null=True) def __str__(self): return self.last_face This function code is bellow is working but it just records last_face id and the date however it is recording the entry and exit time. def scan(request): global last_face known_face_encodings = [] known_face_names = [] profiles = Profile.objects.all() for profile in profiles: person = profile.image image_of_person = face_recognition.load_image_file(f'media/{person}') person_face_encoding = face_recognition.face_encodings(image_of_person)[0] known_face_encodings.append(person_face_encoding) known_face_names.append(f'{person}'[:-4]) video_capture = cv2.VideoCapture(0, cv2.CAP_DSHOW) … -
Langchain cannot create index when running inside Django server
I have a simple Langchain chatbot using GPT4ALL that's being run in a singleton class within my Django server. Here's the simple code: gpt4all_path = './models/gpt4all_converted.bin' llama_path = './models/ggml_model_q4_0.bin' embeddings = LlamaCppEmbeddings(model_path=llama_path) print("Initializing Index...") vectordb = FAISS.from_documents(docs, embeddings) print("Initialzied Index!!!") This code runs fine when used inside the manage.py shell separately but the class instantiation fails to create a FAISS index with the same code. It keeps printing the llama_print_timings 43000ms with the ms increasing on every print message. Can someone help me out? -
Can someone please fix my search bar in Flutter?
I'm trying to make a searchbar, where I can search data from my Django API. Right now I can find shows by name, and when I'm deleting my prompt it doesn't update. I would also like to find shows by their directors for example. Can someone help me with this? This is my search screen: List<ShowsModel> showsList = []; List<DirectorModel> directorList = []; Future<void> getShows() async { showsList = await APIHandler.getAllShows(); setState(() {}); } Future<void> getDirectors() async { directorList = await APIHandler.getAllDirectors(); setState(() {}); } @override void didChangeDependencies() { getShows(); getDirectors(); super.didChangeDependencies(); } void updateList(String value) { setState(() { showsList = showsList .where((element) => element.name.toLowerCase().contains(value.toLowerCase())) .toList() ; //i would like to add more elements here but don't know how }); } //skipping widget build // my search bar Container( padding: const EdgeInsets.all(2), decoration: BoxDecoration( color: const Color.fromRGBO(244, 243, 243, 1), borderRadius: BorderRadius.circular(15), ), child: TextField( onChanged: (value) => updateList(value), decoration: const InputDecoration( border: InputBorder.none, prefixIcon: Icon( Icons.search, color: Colors.black87, )), ), ), -
Why is my React app not getting data from the Django backend after uploading to the server?
After uploaded the React app to the server, it does not get data from Django Backend. I uploaded my Django backend to the server. After that I checked the API endpoint, it works. Then uploaded the React frontend and replaced the '.htaccess' code with this bunch of codes Old htaccess PassengerAppRoot "/home/mod**/mainapp" PassengerBaseURI "/" PassengerPython "/home/mod**/virtualenv/mainapp/3.8/bin/python" PassengerAppLogFile "/home/mod**/logs/passengar.log)" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END # DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION BEGIN <IfModule Litespeed> </IfModule> New htaccess Options -MultiViews </br> RewriteEngine On </br> RewriteRule ^(get-ticket)($|/) - [L] </br> RewriteCond %{REQUEST_FILENAME} !-f </br> RewriteRule ^ index.html [QSA,L] </br> After the rewrite htaccess everything redirect to index.html. How can I solve this issue? does anyone help? Where should I neeed to change? Before the react app upload, django works fine. I checked it. -
Django+docker compose+NGINX+aws+RDS+postgreSQL deployment and ports flow
Hi I developed a simple personal blog with Django and Nginx as a reverse proxy server and want to deploy It with AWS in the most costo effettive way. Which Is It? And I don't understand the ports flow between localhost, Django (uwsgi+gunicorn), Nginx, docker (compose), postgrSQL and AWS RDS...can someone give me help or advice on this? Other infos (this is how I imagined it and tried to put all in a flow but I think there's something wrong, and sorry for the bad formatting but I didn't know ho to do it, i'm a beginner coder): AWS RDS’s endpoint:5432 Client’s requests(incoming/inbound traffic):80 <-- LB(Load Balancer):8000 <-- Nginx <-- (Gunicorn + uwsgi (django app/web container)) 0.0.0.0:8000:9000 <-- docker container:8000 <-- (localhost(0.0.0.0):8000 <-- Gunicorn) django_app:8000 <-- uwsgi:9000 <-- Nginx80:8000 <-- load balancer:8000 (defaults traffic from listener HTTP port 80 redirect to 443 (HTTPS) and then from this to TG1):8000 <-- TG1(Target Group 1) <-- TG2 <-- Client Some debugging logs: $ docker-compose -f docker-compose-prod.yml up nginx_1 | 2023/06/02 15:20:44 [error] 10#10: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.18.0.1, server: , request: "GET /wpad.dat HTTP/1.1", upstream: "uwsgi://172.18.0.3:9000", host: "wpad.homenet.telecomitalia.it" nginx_1 | 172.18.0.1 - - [02/Jun/2023:15:20:44 +0000] …