Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue with changing name of my heroku app in heroku cli
I can't change name of my heroku app from heroku cli: (ll_env) [arch@archlinux dj_proj]$ heroku apps:rename my_learning_log › ModuleLoadError: [MODULE_NOT_FOUND] require failed to load › /usr/lib/heroku/lib/commands/apps/rename.js: Cannot find module 'tmp' › Require stack: › - /usr/lib/heroku/lib/lib/ci/git.js › - /usr/lib/heroku/lib/commands/apps/rename.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/module-loader.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/help/util.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/help/formatter.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/help/command.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/help/index.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/flags.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/cli-ux/styled/table.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/cli-ux/styled/index.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/cli-ux/index.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/command.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/index.js › - /usr/lib/heroku/node_modules/@heroku-cli/command/lib/command.js › - /usr/lib/heroku/node_modules/@heroku-cli/command/lib/index.js › - /usr/lib/heroku/lib/global_telemetry.js › - /usr/lib/heroku/bin/run › Code: MODULE_NOT_FOUND I also tried change the name of the new name, but it didn't work. -
Issue with Google OAuth Login using Django Allauth - Bland Account Selection UI
I'm working on a Django project where I've integrated Google OAuth login using the django-allauth package. The functionality works in terms of authentication, but I'm encountering an issue with the user interface during the Google account selection process. please do tell me where i've made a mistake ,i'm a student please dont expect me to have good knowledge about django Problem: When users click on the "Sign in with Google" button, they are redirected to a Google page for authentication. However, instead of the usual Google account selection UI (which typically shows account avatars and a modern design), the page appears bland and basic, lacking any styling or proper UI elements. -
what is the best approach to generate sitemap with django rest_framework and nextjs?
I've come across similar questions on Stack Overflow, but none of the solutions worked for me. I'm looking to create an XML sitemap for my website, which has a Django-Rest-Framework backend and a Next.js frontend. I'm considering two options: Generating a sitemap using django-sitemap on the backend and then routing the URL to be displayed in https://mywebsite/sitemap.xml on the Frontend. Fetching the list of all articles and courses from the API, which is paginated with a max limit of 100. This would require multiple calls to the list API to generate the sitemap on the Frontend. I'm unsure about which option is the best choice. Is fetching the list of objects from the API suboptimal? How do large websites like Stack Overflow generate their sitemaps? I'd appreciate any guidance and please let me know if I'm on the wrong track. -
django consistently fails to load css on deployment
I was deploying a simple django application to kubernetes and encountered the error of not being able to load css and js. I have tried several times to change the dockerfile,change the volume path, but I can't fix it. I've spent 1 week still not finding the error, am I overlooking something? Here are my files and code main/settings.py BASE_DIR = Path(__file__).resolve().parent.parent env.read_env(os.path.join(BASE_DIR, 'main/.env')) .... STATIC_URL = '/static/' STATIC_ROOT = '/app/static' Dockerfile # Use the official Python image as the base image ARG ARCH= FROM ${ARCH}python:3.12-slim as builder WORKDIR /app COPY requirements.txt . RUN pip install --default-timeout=100 --no-cache-dir -r requirements.txt COPY . . FROM ${ARCH}python:3.12-slim WORKDIR /app COPY --from=builder /app /app COPY --from=builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages COPY --from=builder /usr/local/bin /usr/local/bin EXPOSE 8080 ENV PYTHONUNBUFFERED 1 # Specify the command to run your Django app CMD ["gunicorn", "--workers=3", "--bind=0.0.0.0:8080", "main.wsgi:application" ] deployment.yaml apiVersion: v1 kind: PersistentVolume metadata: name: static-files-pv spec: capacity: storage: 0.5Gi accessModes: - ReadWriteOnce hostPath: path: /mnt/static-files storageClassName: do-block-storage --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: static-files-pvc spec: accessModes: - ReadWriteOnce resources: requests: storage: 0.5Gi storageClassName: do-block-storage --- apiVersion: v1 kind: ConfigMap metadata: name: auth-db-config data: DB_NAME: auth DB_HOST: patroni.default.svc.cluster.local DB_PORT: "5432" --- apiVersion: v1 kind: Secret metadata: name: auth-db-secret … -
Error initializing boto3 session in Django application using DigitalOcean Spaces
I'm having an issue with my Django application when trying to configure it to use DigitalOcean Spaces for static and media files. Here is the relevant part of my settings.py file: import boto3 from botocore.exceptions import NoCredentialsError, PartialCredentialsError from botocore.client import Config from os import getenv AWS_ACCESS_KEY_ID = getenv('SPACES_KEY') AWS_SECRET_ACCESS_KEY = getenv('SPACES_SECRET') AWS_STORAGE_BUCKET_NAME = getenv('BUCKET_NAME') AWS_S3_REGION_NAME = "region" AWS_S3_ENDPOINT_URL = f"https://{AWS_S3_REGION_NAME}.digitaloceanspaces.com" AWS_S3_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_DEFAULT_ACL = 'public-read' AWS_S3_SIGNATURE_VERSION = 's3v4' STATIC_URL = f"{AWS_S3_ENDPOINT_URL}/{AWS_STORAGE_BUCKET_NAME}/static/" MEDIA_URL = f"{AWS_S3_ENDPOINT_URL}/{AWS_STORAGE_BUCKET_NAME}/media/" STATICFILES_STORAGE = 'name.custom_storages.StaticStorage' DEFAULT_FILE_STORAGE = 'name.custom_storages.MediaStorage' # Ensure the credentials are explicitly set for boto3 session = boto3.session.Session() s3_client = session.client( 's3', region_name=AWS_S3_REGION_NAME, endpoint_url=AWS_S3_ENDPOINT_URL, aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, config=Config(signature_version='s3v4') ) # Test connection to S3 def test_s3_connection(): try: print("Connecting to S3...") response = s3_client.list_objects_v2(Bucket=AWS_STORAGE_BUCKET_NAME) print("Connection successful. Contents:") for obj in response.get('Contents', []): print(obj['Key']) except NoCredentialsError: print("Error: No credentials found.") except PartialCredentialsError: print("Error: Incomplete credentials.") except Exception as e: print(f"Error: {e}") test_s3_connection() When I run the server using python3 manage.py runserver, I get the following error: Traceback (most recent call last): ... File "/Users/User/.aws/credentials" botocore.exceptions.ConfigParseError: Unable to parse config file: /Users/User/.aws/credentials I don't want boto3 to use the credentials from the ~/.aws/credentials file because I'm not using AWS, I'm using DigitalOcean Spaces. Any help … -
authentication method for django rest framework to mitigate XSS and CSRF attacks
I am using django rest framework for my backend and react for my front and they serve in different domain and subdomain and now I am completely confused what should I do for securing my APIs from XSS and CSRF attacks. I wish to use simple-JWT for the application but my research showed that it is vulnerable to XSS. and if I store them in http-only cookies they can't be accessible in front end to add them in authorization header and it would be like using sessions, what should I do? and what is the best practice for securing APIs? I would be glad to hear your suggestions -
How to handle multiform /form data and nested serializer in django rest framework
I have a Tender model and a Product model. There is a foreign key relationship between Tender and product. Now I want to update a tender instance where I provide tender and product data. The data format is multipart/form-data. But every time get the following error { "products": [ "This field is required." ] } I am providing the code so that you guys can understand things properly This is the view class @extend_schema(tags=[OpenApiTags.TMS_TENDER]) class TenderUpdateView(generics.UpdateAPIView): permission_classes = [] queryset = Tender.objects.all() serializer_class = TenderPreSubmissionSerializer lookup_field = "id" parser_classes = [MultiPartParser] def get_queryset(self): id = self.kwargs.get("id") return Tender.objects.filter(id=id) This is the serializer class TenderPreSubmissionSerializer(serializers.ModelSerializer): products = ProductSerializer(many=True) class Meta: model = Tender fields = [ "products", "is_open", "procuring_entity", "ministry", "bg_amount", "bg_attachment", "bg_issue_date", "bg_validity_date", "is_bg_extended", ] def update(self, instance, validated_data): # Extract products data products_data = validated_data.pop("products") # Update tender instance instance = super().update(instance, validated_data) # Create a mapping of existing products by ID existing_products = {product.id: product for product in instance.products.all()} # Update or create products for product_data in products_data: product_id = product_data.get("id") if product_id and product_id in existing_products: # Update existing product product = existing_products.pop(product_id) for attr, value in product_data.items(): setattr(product, attr, value) product.save() else: # Create new product … -
Ready-Made Restaurant Ordering System with POS, Loyalty Programs, Third Party Delivery Integrations
This will probably get taken down but we are in urgent need and I am freaking out and I don't know where else to go for a solution. We urgently need a comprehensive restaurant ordering system, similar to Restoplus, with essential features like restaurant login/signup, customizable menus with item variations, a POS interface, and access to sales data. The system must support both in-store pickup and dine-in notifications via SMS, as well as integrate with delivery services like Uber/DoorDash. Additionally, it should include a robust rewards system for users, allowing them to earn points with purchases and redeem them, similar to major fast-food chains' loyalty program. Instant receipt printing and order processing capabilities, mirroring the efficiency of modern restaurant system. We are looking to purchase a ready-made solution immediately, with a strong preference for off-the-shelf systems to meet our critical timeline. We need at least a partial deployment within the next 2 days. If you have an existing solution that fits these requirements, please contact us ASAP. Speed is of the essence in this project. We are looking for a ready-made solution that can be deployed immediately, with at least partial functionality within the next 2 days. The system must … -
Running Django on Google Colab: Error 204 Forbidden
I am trying to do some tests on Colab of my Python program and to use Django. I followed the instructions from this link . I made sure this is set in settings.py ALLOWED_HOSTS = ['*'] Ran this to get the link https://randomstrings.colab.googleusercontent.com/ from google.colab.output import eval_js print(eval_js("google.colab.kernel.proxyPort(8000)")) And then !python manage.py runserver 8000 which gave me a successful output, System check identified no issues (0 silenced). July 28, 2024 - 05:49:17 Django version 5.0.7, using settings 'test.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. However when opening the link https://randomstrings.colab.googleusercontent.com/ printed above, I get a 403. That's an error page. Is there any other settings that I have to do or steps that I missed? -
Country field not being populated on sign up in Django
When the user signs up, I want to add their country to their profile. But, the field remains blank in the database and doesn't get populated with the country. I am new to authentication in Django, so it may be wrong in other ways.I think the order may be the problem? I am really unsure. Views.py def get_country(ip): if ip in ['127.0.0.1', 'localhost', '::1']: return 'Localhost' # Perform GeoIP lookup g = GeoIP2() try: result = g.city(ip) country = result["country_name"] except Exception as e: print(f'Error: {e}') country = "Unknown" return country def signup_view(request): if request.method == 'POST': form = UserCreateForm(request.POST) if form.is_valid(): user = form.save() # Get the user's IP address x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0].strip() else: ip = request.META.get('REMOTE_ADDR') # Determine the user's country country = get_country(ip) # Create the profile with the country information username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') Profile.objects.create(user=user, country=country) user = authenticate(username=username, password=raw_password) login(request, user) return redirect('/') else: form = UserCreateForm() return render(request, 'signup.html', {'form': form}) models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField( default='profile_pics/default.jpg', upload_to='profile_pics') country = models.CharField(max_length=100) def __str__(self): return f'{self.user.username} Profile' … -
Google Picker API giving Null user before completing authorization
I am using the google picker api example code from https://developers.google.com/drive/picker/guides/sample and when I tried authenticating with google, it always gives me back a null access token before I even complete the authorization part. Here is the following code I used for authorizing: let tokenClient; let accessToken = null; let pickerInited = false; let gisInited = false; document.getElementById('authorize_button').style.visibility = 'hidden'; document.getElementById('signout_button').style.visibility = 'hidden'; /** * Callback after api.js is loaded. */ function gapiLoaded() { gapi.load('client:picker', initializePicker); } /** * Callback after the API client is loaded. Loads the * discovery doc to initialize the API. */ async function initializePicker() { await gapi.client.load('https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'); pickerInited = true; maybeEnableButtons(); } /** * Callback after Google Identity Services are loaded. */ function gisLoaded() { tokenClient = google.accounts.oauth2.initTokenClient({ client_id: CLIENT_ID, scope: SCOPES, callback: '', // defined later }); gisInited = true; maybeEnableButtons(); } /** * Enables user interaction after all libraries are loaded. */ function maybeEnableButtons() { if (pickerInited && gisInited) { document.getElementById('authorize_button').style.visibility = 'visible'; } } /** * Sign in the user upon button click. **/ function handleAuthClick() { tokenClient.callback = async (response) => { if (response.error !== undefined) { throw (response); } accessToken = response.access_token; document.getElementById('signout_button').style.visibility = 'visible'; document.getElementById('authorize_button').innerText = 'Refresh'; await createPicker(); … -
Building a Dynamic Quest and Badge Evaluation System in Django
Models Quest class Quest(models.Model): name = models.CharField(max_length=255) description = models.TextField(blank=True) criteria = models.JSONField() # Store criteria as JSON reward_points = models.IntegerField(default=0) def __str__(self): return self.name Badge class Badge(models.Model): name = models.CharField(max_length=255) description = models.TextField(blank=True) criteria = models.JSONField() # Store criteria as JSON reward_points = models.IntegerField(default=0) def __str__(self): return self.name UserQuestProgress class UserQuestProgress(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) quest = models.ForeignKey(Quest, on_delete=models.CASCADE) current_value = models.IntegerField(default=0) target_value = models.IntegerField() completed = models.BooleanField(default=False) completed_at = models.DateTimeField(null=True, blank=True) def save(self, *args, **kwargs): if self.current_value >= self.target_value: self.completed = True if not self.completed_at: self.completed_at = timezone.now() super().save(*args, **kwargs) UserBadgeProgress class UserBadgeProgress(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) badge = models.ForeignKey(Badge, on_delete=models.CASCADE) current_value = models.IntegerField(default=0) target_value = models.IntegerField() completed = models.BooleanField(default=False) completed_at = models.DateTimeField(null=True, blank=True) def save(self, *args, **kwargs): if self.current_value >= self.target_value: self.completed = True if not self.completed_at: self.completed_at = timezone.now() super().save(*args, **kwargs) I'm working on a social media platform where users can earn rewards (quests and badges) based on their activities. My goal is to create a flexible system that can evaluate these rewards dynamically, without needing to hardcode new conditions every time we introduce a new quest or badge. What We Have Done So Far: Models for Quests and Badges: We have defined models for Quest, … -
Static Files Not Loading in Production with Django and Docker
I'm running a Django application in a Docker container, and I'm having trouble serving static files in production. Everything works fine locally, but when I deploy to production, the static files don't load, and I get 404 errors. Here are the relevant parts of my setup: Django settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '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/' MEDIA_URL = '/media/' STATIC_ROOT = '/vol/web/static' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'build', 'static')] After running collectstatic, the volume /vol/web/static is correctly populated. However, the browser shows 404 errors for the static files, e.g., GET https://www.aloconcursos.com/static/js/main.db771bdd.js [HTTP/2 404 161ms] GET https://www.aloconcursos.com/static/css/main.4b763604.css [HTTP/2 404 160ms] Loading failed for the <script> with source “https://www.aloconcursos.com/static/js/main.db771bdd.js”. These files exist in the build/static directory, but I thought the browser should use the static files collected into /vol/web/static. Nginx Configuration: server { listen ${LISTEN_PORT}; location /static { alias /vol/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } Dockerfile: FROM python:3.9-alpine ENV PYTHONUNBUFFERED 1 ENV PATH="/scripts:${PATH}" RUN pip install --upgrade "pip<24.1" COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache postgresql-client jpeg-dev \ && apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev … -
'SignInForm' object has no attribute 'request'
I'm trining to set remember_me in forms.py insted of views.py via def clean_remember_me. but it dosn't work and give me error ! remember_me = forms.BooleanField(widget=forms.CheckboxInput(),label=_('Remember me'), required=False) def clean_remember_me(self): remember_me = self.cleaned_data['remember_me'] if not remember_me: self.request.session.set_expiry(0) -
can I use the slug from a different urls.py file?
I'm trying to access a slug field from a different urls.py file, and I'm getting this error FieldError at /new-api/tournaments/fifa-world-cup/teams/ Unsupported lookup 'custom_url' for ForeignKey or join on the field not permitted. I'm wondering if the reason I'm getting this error is because you cant do that or if it's another reason I have 2 files for urls, one includes the other in it, urls.py (tournament) urlpatterns = [ path("", views.getNewTournaments, name="tournaments"), path("<slug:custom_url>/", views.getNewTournament, name="tournament"), path("create/", views.postNewTournament, name="post-tournament"), path("<slug:custom_url>/teams/", include("teams.urls"), name="tournament-teams"), ] urls.py (teams) urlpatterns = [ path("", views.teams.as_view(), name="teams"), ] Here are the views.py files views.py (tournaments) @api_view(["GET"]) def getNewTournaments(request): tournaments = NewTournament.objects.all() serializer = NewTournamentSerializer(tournaments, many=True) return Response(serializer.data) views.py (teams) class teams(APIView): def get(self, request, custom_url): teams = Team.objects.filter(tournament__custom_url=custom_url) serializer = TeamSerializer(teams, many=True) return Response(serializer.data) -
Django JWT authentication TokenObtainPairView issue
I am trying to use CustomTokenObtainPairView to receive my username in token. #views: `if user.check_password(password): # refresh = RefreshToken.for_user(user) # refresh.access_token['username'] = user.username # token = str(refresh.access_token) request.data = { 'username': username, 'password': password } token_response = CustomTokenObtainPairView.post(request=request.data) response = Response() response.set_cookie(key='jwt', value=token_response.data['access'], httponly=True, secure=True) response.data = { 'access': token_response.data['access'] } return response else: return Response({'message': 'Wrong password!'}, status=400)` I tried to generate token and adding username in it but it didnot work. If anybody knows how to use TokenObtainPairView in correct way in your function please help. -
How to properly assign a value to a Django choice field
I am trying to assign a value to a ChoiceField in a Django form. # forms.py MONTH_CHOICES = ( ("JANUARY", "January"), ("FEBRUARY", "February"), #... ("DECEMBER", "December"), ) class SomeMonthSelectingform(forms.Form): month = forms.ChoiceField(choices=MONTH_CHOICES) def __init__(self, *args, **kwargs): month = kwargs.pop("month") super(SomeMonthSelectingform, self).__init__(*args, **kwargs) self.fields['month'] = month The selected value of the choice field named month should be the actual month (e.g. right now it would be 'JULY') # views.py def month_view(request: HttpRequest): month = datetime.now().month monthIndex = month - 1 monthChoice = MONTH_CHOICES[monthIndex][0] monthForm = SomeMonthSelectingform(month=monthChoice) if request.method == 'POST': filledForm = SomeMonthSelectingform(data=request.POST) if not filledForm.is_valid(): raise Exception("Month form was invalid") monthForm = filledForm args = { 'monthForm': monthForm } return render(request, 'month.html', 'args') <!-- month.html --> {% extends 'base.html' %} {% block content %} <h2>Month</h2> <form action="{% url '...' %}" method="post"> {% csrf_token %} {{ monthForm }} <input type="submit" name="..." value="Show"> </form> {% endblock %} Sadly, I keep getting the error 'str' object has no attribute 'get_bound_field'. I am quite sure it is because, I should not assign 'JULY' to self.fields['month'] inside the constructor of the form. But I can not find another solution. -
How To Redirect In Post Request Response
i wanna redirect to success page but it seems i should use different way in post request response. views.py : def uploader(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): return redirect("download",link = 'test') else: form = UploadFileForm() return render(request, 'uploader/pages/upload.html', {'form': form}) def downloader(request,link) : return render(request, 'uploader/pages/download.html',) urls.py : urlpatterns = [ re_path(r'^admin/', admin.site.urls), re_path(r'^$', views.uploader, name='upload'), re_path(r'^(?P<link>[\w-]+)/', views.downloader, name='download'), ] log in terminal : [27/Jul/2024 17:43:37] "POST / HTTP/1.1" 302 0 [27/Jul/2024 17:43:37] "GET /test/ HTTP/1.1" 200 46 I've tried HttpResponseRedirect('test') and HttpResponseRedirect(reverse('download', kwargs={'link': 'link'})) to -
How to implement Bootstrap Card Layout in Django: Achieving Desired Design vs. Current Output
I'm working on a Django application. I'm mostly working on the backend because of that in the frontend I'm terrible. I want to create a page that contains a couple of cards. I want to create this structure in the image-1 but I'm able to create image-2. I'll attach my code, can you help me to implement the first image? (the images in the picture is not important they can change) I'm using bootstrap 4.6 <div class="col-lg-5 col-md-12"> <img class="ca-icon" src="{% static 'images/list-icon.svg' %}" alt="List"> <div class="row ca-border mb-3 align-items-center ca-side-context"> <div class="col-6 "> <div class="row">Text-1</div> <div class="row "><img class="icon sound-icon" src="{% static 'images/sound-icon.svg' %}" alt="Sound Icon"></div> </div> <div class="col-6 ca-border"><img class="img-fluid" src="{% static 'images/temp.png' %}" alt="List"></div> </div> <img class="ca-icon" src="{% static 'images/parent-icon.svg' %}" alt="List"> <div class="row ca-border mb-3 align-items-center ca-side-context"> <div class="col-6 "> <div class="row">Text-2</div> <div class="row "><img class="icon sound-icon" src="{% static 'images/sound-icon.svg' %}" alt="Sound Icon"></div> </div> <div class="col-6 ca-border"><img class="img-fluid" src="{% static 'images/temp.png' %}" alt="List"></div> </div> </div> <style> .ca-border { border: 12px solid #ffdd43; border-radius: 20px; padding: 10px; } .ca-icon { width: 10%; height: 10%; } .sound-icon { width: 50%; height: 50%; } .play-icon{ width: 90%; height: 90%; } .clock-icon{ width: 50%; height: 50%; } .subject-title { margin-left: … -
Why Gemini API function calling response using old function definition even after changing tools in genai.GenerativeModel?
I want to build a django application that uses Google Gemini API at the backend. The challenge I have is that , the function call parameters change ( though very rarely ) based on a database entry. consider I have an enum as input arg to the function and whenever a new row is created I want to add new enum to this function definition. so this change take place quickly. but unfortunately this doesn't happen, instead the Gemini responds with response that looks it doesn't know about the change. Note I have configured the the flow to call genai.GenerativeModel for every new request and verified that self.function_collection.getdef() returns the updated function definition when I update the a row. self.model = genai.GenerativeModel( model_name=config('GEMINI_MODEL_NAME'), generation_config={ "temperature":config('TEMPERATURE',cast=float), "top_p": config('TOP_P',cast=int), "top_k": config('TOP_K',cast=int), "max_output_tokens": config('MAX_OUTPUT_TOKENS',cast=int), "response_mime_type": "text/plain", }, tools=[{ 'function_declarations': self.function_collection.getdef(), }], ) If I restart django development server this change will be quickly considered. but I can't do this in production. Also I have verified this change is available to the model using the following chat_session = self.model.start_chat(history=self.history) print("tools avaialbe",self.model._tools.to_proto()) print("function def",self.function_collection.getdef()) print("tools avaialbe in session before ",chat_session.model._tools.to_proto()) response = chat_session.send_message(query) print("tools avaialbe in session after ",chat_session.model._tools.to_proto()) I verified that the updated function … -
Django send just an alter in response instead of a full template
How can I send just an alert message in response to a request instead of having to send a template made just for the alert? I am using Javascript async call. I only need the alert html response to render an InnerHTML. View @login_required(login_url="/login/") @csrf_protect def usersave(request): msg = messages.add_message(request, messages.WARNING, "This is a demo. First complete all info to save.") return render(request, msg) # Want to send just msg instead of a template for an alert. -
Django modal window
I have a modal window for deleting comments. It looks like this: <div id="deleteModal" class="modal"> <div class="modal-content"> <img class="modal-image" src="{% static 'img/icon-modal-delete.png' %}" alt="DELETE"> <h1 class="modal-title">Delete comment?</h1> <div class="modal-block"> <form method="POST"> {% csrf_token %} <button class="modal-sucsess" type="submit">Delete</button> </form> <a class="modal-cancel" onclick="closeModal()">Cancel</a> </div> </div> </div> I include it with the include tag in the django template. There is also a js script for opening and closing the modal window, which looks like this: function openModal() { var modal = document.querySelector('.modal'); modal.style.display = 'block'; } function closeModal() { var modal = document.querySelector('.modal'); modal.style.display = 'none'; } In the django template I have a cycle where I display comments to the publication and each comment has a delete button, which on click calls a modal window, it looks like this: <a class="main-row-content-comments-users-info-delete" onclick="openModal()" >Delete</a> I wrote a view to delete a comment, but it needs to pass the comment id. If I were doing this directly via a link in a template tag, I would simply pass comment.pk, but how do I pass the key to the modal so that when I click the delete button in the modal, the delete view is called? I tried to solve this using Ajax requests, but … -
Lightsail deployment logging; Invalid HTTP_HOST header:You may need to add '****' to ALLOWED_HOSTS
I am deploying a containerised application on Lightsail and whilst the deployment itself is successful, logging shows hundreds of these messages from the same ip address, my assumption is this is some sort of automated process that's failing. I have set the allowed_hosts to just the Lightsail generated url (w/o https//.com etc.) and so I have no idea where this extra ip is coming from. I can't find anything which says I need to have an extra ip on allowed_hosts. Tried to deploy containerised application to Lightsail -
I cant understand this python script clearly?
Python script to load .dat files import csv from django.core.management.base import BaseCommand from recommender.models import User, Artist, Tag, UserArtist, UserTaggedArtist, UserFriend import os from django.conf import settings # Define the path to the database directory Database_path = os.path.join(settings.BASE_DIR, 'mldata') class Command(BaseCommand): help = 'Load data from .dat files into the databases' def handle(self, *args, **kwargs): self.create_default_users() self.load_artists() self.load_tags() self.load_user_artists() self.load_user_tagged_artists() self.load_user_friends() def create_default_users(self): users = [ {'username': 'User1', 'email': 'user1@example.com'}, {'username': 'User2', 'email': 'user2@example.com'} ] for user in users: User.objects.get_or_create(username=user['username'], email=user['email']) def load_artists(self): with open(os.path.join(Database_path, 'artists.dat'), 'r', encoding='utf-8', errors='replace') as file: reader = csv.reader(file, delimiter='\t') next(reader) for row in reader: artist_id, artist_name = row[0], row[1] Artist.objects.get_or_create(artist_id=artist_id, defaults={'artist_name': artist_name}) def load_tags(self): with open(os.path.join(Database_path, 'tags.dat'), 'r', encoding='utf-8', errors='replace') as file: reader = csv.reader(file, delimiter='\t') next(reader) for row in reader: tag_id, tag_name = row[0], row[1] Tag.objects.get_or_create(tag_id=tag_id, defaults={'tag_name': tag_name}) def load_user_artists(self): with open(os.path.join(Database_path, 'user_artists.dat'), 'r', encoding='utf-8', errors='replace') as file: reader = csv.reader(file, delimiter='\t') next(reader) for row in reader: user_id, artist_id, listening_count = row[0], row[1], row[2] user = User.objects.get(id=user_id) artist = Artist.objects.get(artist_id=artist_id) UserArtist.objects.get_or_create(user=user, artist=artist, defaults={'listening_count': listening_count}) def load_user_tagged_artists(self): with open(os.path.join(Database_path, 'user_taggedartists.dat'), 'r', encoding='utf-8', errors='replace') as file: reader = csv.reader(file, delimiter='\t') next(reader) for row in reader: user_id, artist_id, tag_id, timestamp = row[0], row[1], row[2], row[3] user … -
Cannot display image with JavaScript from Django Base
I am attempting to get a customer logo to load when a user signs into my app. To do that I am using the views function below to generate the logo url: Views: def view_company_logo(request): print("GETTING LOGO") client = Client.objects.get(user=request.user) logo = "" try: logo = client.customer.first().logo.logo.url print("GOT LOGO") return JsonResponse({"logo": logo, "media_url": settings.MEDIA_URL}, safe=False) except Exception as e: print(e) print(f'ERROR FOR LOGO {e}') return JsonResponse({"logo": logo}, safe=False) The function is attached the url below: url(r"^get/company_logo/$", views.view_company_logo), This is called in the base.html file in order to show the $(document).ready(function () { document.getElementById("logo").src = get_company_logo(); function get_company_logo() { log('TEST'); $.ajax({ url: '/get/company_logo/', method: 'GET', success: function (data) { console.log(data); console.log(data['logo']); return data.logo }, error: function () { console.log('HERE IS THE ERROR!!!') log('HERE IS THE ERROR!!!') }, }) } Which connects to the source of this image that gets generated when the pages loads: <img class="img-square center" id="logo" alt="logo" style="opacity: 1" height="45" width="125"> Could someone tell me why the image is not loading? It seems like the function is never called and I am not sure why.