Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Making Downloaded Files a Parameter for Subsequent Functions in Django, Celery, and Digital Ocean Spaces Integration
How can I utilize Django with Celery to handle a scenario where a function downloads a file from Digital Ocean Spaces, and once the download is complete, I want to pass the downloaded file as a parameter to the StorageContext function? Something like, whenever it has the file, then proceed. Here is what i've tried: @celery_app.task() def download_file_from_digital_ocean(folder_key, local_folder): try: session = boto3.session.Session() client = session.client( "s3", region_name=settings.AWS_S3_REGION_NAME, endpoint_url=settings.AWS_S3_ENDPOINT_URL, aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, ) object_list = [ f"test/{folder_key}/docstore.json", f"test/{folder_key}/graph_store.json", f"test/{folder_key}/index_store.json", f"test/{folder_key}/vector_store.json", ] subfolder_path = os.path.join(local_folder, folder_key) os.makedirs(subfolder_path, exist_ok=True) for file_path in object_list: file_name = file_path.split("/")[-1] local_file_path = os.path.join(subfolder_path, file_name) client.download_file( Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=file_path, Filename=local_file_path, ) return True except Exception as e: print(f"Connection error: {e}") return False @celery_app.task() def llma_index_new_update(url, url_text, question): try: API_KEY = settings.APP_OPEN_AI_API_KEY url_id = url["id"] openai.api_key = API_KEY folder_key = f"storage{url_id}" local_folder = "local_test/" download_task = download_file_from_digital_ocean.delay(folder_key, local_folder) storage_context = StorageContext.from_defaults( persist_dir="local_test/storage" + str(url["id"]) ) index = load_index_from_storage(storage_context, index_id=url["url"]) query_engine = index.as_query_engine(response_mode="tree_summarize") response = query_engine.query(question) data = { "url": url_instance, "url_asked": url_text, "question": question, "response": response.response, } return_data = { "url_asked": url_text, "question": question, "response": response.response, } save_db = save_to_db_question(data) return return_data except Exception as e: print(e) any idea on how can I implement this? -
Come effettuare una verifica dell'input dell'utente con più campi di un modello django?
Premetto che sono neofita nel mondo della programmazione e da agosto di quest'anno ho iniziato a studiare da autodidatta Python e successivamente Django. Sto cercando di implementare una view per la cui se sei autenticato come utente django e se inserisci una chiave e un numero di telefono che corrispondono con quello registrato nel database allora hai accesso ad una risorsa url specifica. Gli step sarebbero i seguenti: In Homepage c'è un button che se cliccato reindirizza alla view access_to_events_by_secret che istanzia il form con i due campi da compilare. Quindi l'utente inserisce i dati e a quel punto vengono verificati i dati inseriti e se corrispondono al numero di telefono e alla chiave presenti nel database allora si viene reindirizzati ad uno specifico URL. Ecco il codice: Models.py from django.db import models from .utils import generate_code # Create your models here. class Secret(models.Model): name = models.CharField(max_length=50) key = models.CharField(max_length=15, blank=True, unique=True) phone_number = models.CharField(max_length=13) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name def save(self, *args, **kwargs): if self.key == "": self.key = generate_code() return super().save(*args, **kwargs) Utils.py import uuid def generate_code(): code = uuid.uuid4() code_mod = str(code).replace('-', '').upper()[:15] return code_mod Forms.py from django import forms from .models … -
(WAGTAIL) How to customize the FileField field?
I have a FileField field in my Wagtail model. In the administrative area, I intend to offer a single download button exclusively for this field. The rationale behind this decision is that the data will be pre-populated from the backend. class ReportCSV(models.Model): file = models.FileField( null=True, blank=True, verbose_name=_("File"), upload_to=csv_directory_path, ) -
re render a django view with change in context after POST request
I am trying to change content of a table by applying filters in a django template but I am unable to re render the same page again with change in context. I don't want to use javascript or class based views so could you please suggest a way to do it in django function based view. Below is sample code def Endtoendtrackerview(request,*args,**kwargs): def executefunction(orderobj,baseobj): 'somecode which returns a context dictionary return context if request.method = POST: 'some code orderobj = OrderModel.objects.filter(status = True) baseobj = BaseModel.objects.filter(process = process) context = executefunction(orderobj,baseobj) return render(request, "app/end_to_end_tracker.html",context) orderobj = OrderModel.objects.all() baseobj = BaseModel.objects.all() context = executefunction(orderobj,baseobj) return render(request, "app/end_to_end_tracker.html",context) -
Items not getting store in databse after submit
I am building this website in Django where I am storing locations as "items" inside a databse. Users are allowed to enter a detailed view of each location, and then press a "Rate" button which should open a form that lets them enter a rating. Later I want to display on each location an average of the users s ratings. I Stored the rating of users with respect to an object in a database called "Ratings". However, when I submit, items don t get stored in the "ratings". This is the views file: `from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from .models import Item from .forms import RateItemForm # Create your views here. def detail(request, pk): item = get_object_or_404(Item, pk = pk) related_items = Item.objects.filter(category = item.category, is_sold = False).exclude(pk=pk).order_by('-price')[0:3] items = Item.objects.filter(is_sold = False).order_by('-price')[0:6] highest_rated_item = items.first() return render(request, 'item/detail.html', { 'item': item, 'related_items' : related_items, 'highest_rated_item' : highest_rated_item }) @login_required(login_url='/login/') def rate(request, pk): item = get_object_or_404(Item, pk = pk) if request.method == "POST": form = RateItemForm(request.POST) if form.is_valid(): rating = form.save(commit=False) rating.user = request.user rating.item = item rating.save() return redirect('item:detail', pk = rating.id) else: print(form.errors) else: form = RateItemForm() return render(request, 'item/rate.html', { 'item': item, … -
Django sign up using OTP send to telegram
Iam using Django User model with extra phone number phone class CreateUserForm(UserCreationForm): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = forms.CharField(validators=[phone_regex], max_length=17) class Meta: model = UserProfile fields = ['username', 'email', 'phone', 'password1', 'password2'] and after, user add all the input need and press sign up button from template: {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div style=" position:absolute; top:62%; left:50%; padding:10px; -ms-transform: translateX(-50%) translateY(-50%); -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"> <form method="post"> {% csrf_token %}{{form|crispy}} <p>Have an account? Login <a href="/login">Here</a>!</p> <button type="submit" class="btn btn-success">Register</button> </form> </div> {% endblock %} and then i want to change user to verify code page that generate code and send that code to user through telegram. But because telegram need chat id so the bot can send message to user, i can't figure out how to get that id when user press get code in verify_code template: {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div style=" position:absolute; top:50%; left:50%; padding:10px; -ms-transform: translateX(-50%) translateY(-50%); -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"> <h1>Verify Code</h1> <a href="https://t.me/AccountToken_bot" target="_blank"> Get Code </a> <p>Enter the 6-digit code you received on Telegram:</p> <form … -
Override Django Admin Save Model
I want to override Django form save method to be able to create multiple objects at once. I have an AvailableHours model : class AvailableHours(models.Model): free_date = models.ForeignKey(AvailableDates,null=True, blank=True,on_delete=models.CASCADE,related_name='freedate') free_hours_from = models.IntegerField(null=True, blank=True) free_hours_to = models.IntegerField(null=True, blank=True,) status = models.BooleanField(null=True,default=True,) and I have a ModelForm for this class : class TimeGenerator(forms.ModelForm): class Meta: model = AvailableHours fields = ['free_date','free_hours_from','free_hours_to','status'] def save(self, commit=True): base_item = super().save(commit=False) frm = self.cleaned_data['free_hours_from'] to = self.cleaned_data['free_hours_to'] items = [ AvailableHours( free_date=base_item.free_date, status=base_item.status, free_hours_from=hour, free_hours_to=hour + 1, ) for hour in range(frm, to) ] if commit: AvailableHours.objects.bulk_create(items) return items I want to create multiple AvailableHours object like this: if the form is set free_hours_from = 13 and free_hours_to=16 so the save method creates 13-14 , 14-15, 15-16 I achieved this by overriding my ModelForm but now I want to override Admin Save model to do this from Django Admin. I tried by doing it like this in admin.py class AvailableHoursAdmin(admin.ModelAdmin): def save_model(self, commit=True): base_item = super().save(commit=False) frm = self.cleaned_data['free_hours_from'] to = self.cleaned_data['free_hours_to'] items = [ AvailableHours( free_date=base_item.free_date, status=base_item.status, free_hours_from=hour, free_hours_to=hour + 1, ) for hour in range(frm, to) ] if commit: AvailableHours.objects.bulk_create(items) return items admin.site.register(AvailableHours,AvailableHoursAdmin) but no luck. anyone has a solution for this ? -
Celery Task ECS Termination Issue - Need Help Updating Decorator for Handling ProtectionEnabled State Changes
Explanation: I have a Django application where I am running multiple Celery tasks on AWS Elastic Container Service (ECS), using SQS as the broker. I am encountering an issue where the Celery tasks are being started in an existing ECS task once the previous one is completed. The issue arises because my decorator changes the status of ProtectionEnabled from true to false, and after a couple of seconds, the ECS task is terminated. The newly started task then fails to work. Below is the command I am running to start celery task. celery -A myapp_settings.celery worker --concurrency=1 l info -Q sqs-celery I am using alerts on CloudWatch to check messages in broker and terminate those ECS tasks that are completed. The problem is that celery is starting task in existing ECS task once the previous one was completed. It would not be a problem but my decorator changes the status of ProtectionEnabled from true to false and after 20 seconds ECS task is terminated and newly started task is not working anymore. Question: I am considering updating my decorator to change back the ProtectionEnabled value from false to true if a new Celery task starts, but I am unsure how … -
Using stage_block API to upload file chunk is so slow when executing under Uwsgi request in Django
I am using python 2.7.18 with azure-storage-blob==12.3.2 and Django to implement file upload with small chunk, when calling stage_block API in interactive mode directly each chunk request takes less than a second. While under Uwsgi request , it was so slow and each chunk data need almost 90 seconds to complete. What are the possible reasons? # directly calling from azure.storage.blob import BlobClient import base64 import os container = "test" blob_name = "test" blob = BlobClient(account_url=******, container_name=container, blob_name=blob_name) chunk_size = chunk*1024*1024 block_ids = [] index = 0 with open(file_path, 'rb') as f: while True: data = f.read(chunk_size) if data: length = len(data) block_id = base64.encodestring(str(index)).strip() blob.stage_block(block_id, data) index += 1 else: break resp = blob.commit_block_list(block_ids) # Django request,uwsigi wrapped from azure.storage.blob import ContainerClient container = ContainerClient(account_url=********, container_name="test") def process_chunk(request): import base64 id = request.GET['id'] idx = request.GET['idx'] data = base64.b64decode(request.POST['data']) blob = container.get_blob_client(id) block_id = base64.encodestring(str(idx)).strip() try: blob.stage_block(block_id, data) return HttpResponse(status=200, content="ok", content_type='text/plain') except Exception, ex: import traceback logger.error(traceback.format_exc()) return HttpResponse(status=500, content="failure", content_type='text/plain') The uwsgi config is like below: master = true single-interpreter = true processes = 8 enable-threads = true threads = 20 socket = /tmp/instance.sock chmod-socket = 666 listen = 8192 harakiri = 90 vacuum = true buffer-size … -
Stepwise procedure to install django,nginx,gunicorn,supervisor and virtualenv on Fedora 38
Steps: NGINX 1.Installed ningx, added a test index page at /etc/nginx/sites.d Added an include /etc/nginx/sites.d/*.conf; in the main nginx conf.d file. It worked out of the box, (I didn't go for any of the sites-available sites-enabled symnliks alternative configurations which never worked and were downright complicated) POSTGRESQL 2. Installed postgresql, created db and owner and granted privs. Now my questions on how to continue: VIRTUALENV: a) I INSTALLED virtualenv, have not CREATED it yet to anywhere nor ACTIVATED it. I read it can be created anywhere, QUESTION: I read creating a webapps dir at the root is ok? b) once I have question 3.a) cleared, next topic: CLONING THE DJANGO APP FROM BITBUCKET I have my django app at bitbucket. QUESTION: do I have to place myself where the test index page is (step 1) to start the cloning from the repository? or do I do it from the webapps dir created at 3a) ? GUNICORN Since gunicorn is a python package, it has to have the virtualenv installed before (unlike postgresql and nginx who are self-contained) Still inside the activated virtualenv, I will install gunicorn. Since the configuration is very specific I will try that first myself. SUPERVISOR 6) … -
Integrating Databricks SQL Connector with Django ORM for CRUD Operations
I am working on a Django project that requires integration with Databricks, and I am currently exploring the use of the databricks-sql-connector Python package for connectivity. However, my concern is that utilizing this package might involve manual SQL query creation for CRUD operations within my Django project. Is there a method available that allows me to establish a connection to the Databricks database while still leveraging Django's ORM capabilities? I would like to achieve a connection similar to the following code snippet: sql.connect( server_hostname=connection_params["hostname"], http_path=connection_params["http_path"], access_token=connection_params["access_token"] ) Additionally, I would like to extract a cursor using the following snippet: connections["default"].cursor() My database settings are configured as follows: DATABASES = { 'default': { 'ENGINE': 'custom_engine_name', 'HOSTNAME': os.getenv('DATABRICKS_HOSTNAME'), 'NOTEBOOK_PATH': os.getenv('DATABRICKS_NOTEBOOK_PATH'), 'ACCESS_TOKEN': os.getenv('DATABRICKS_ACCESS_TOKEN'), } } My expectation is to find a method or solution that allows me to establish a connection to the Databricks database using Django's ORM, avoiding the need for manual SQL queries. If this requires writing a custom adapter, I would appreciate guidance on how to create one that effectively connects Django ORM with the "databricks-sql-connector." -
Place N number of points having height and width in the sector area of radii of the two concentric circles with radius r1 and r2
Place N number of points having height and width in the sector area of radii of the two concentric circles with radius r1 and r2 In given image i want to place 5 points inside the area enter image description here place it evenly like this : enter image description here using python code , assume that i have made circles and we have radius r1 and r2 and sector angle -
How to configure HSTS in django
I need to configure hsts in one of django app. I have read django doc and came to a point that if I set SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True It will set hsts header on all request headers which it didn't Additionally I got another key value SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') That I need to set if my app is behind proxy. I expect that on all of my django api request headers I see that hsts header. -
How to run Huey consumer on Windows IIS
I am working on a Django application which is deployed on a Windows Server using IIS. I want to use Huey to be able to run background tasks e.g. sending of emails and report generation. Celery does not support Windows hence my decision to use Huey. According to the documentation, you can run the consumer using the following command: ./manage.py run_huey My question is, how and where will I need to run this command to work with my setup i.e. Windows and IIS? It should also work when the server is restarted. -
How to check email validation using regex in Django
I'm trying to create a registration form for my Django project. I want to check if the user's email address is correct. I used built-in email validator, but it just check the domain. I need to prevent user to enter emails like this: john#doe@gmail.com etc. here is my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=300, null=True, blank=True) email = models.EmailField(max_length=200, null=True, blank=True, validators=[validate_email]) username = models.CharField(max_length=200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.user.username) forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = User fields = ['first_name', 'email', 'username', 'password1', 'password2'] labels = {'first_name':'Name',} signals.py @receiver(post_save, sender=User) def createProfile(sender, instance, created, **kwargs): if created: user = instance profile = Profile.objects.create( user = user, username = user.username, email = user.email, name = user.first_name, ) and views.py for registration def registerUser(request): page = 'register' form = CustomUserCreationForm() if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.username = user.username.lower() user.save() messages.success(request, 'User Account Was Created!') login(request, user) return redirect('profile') else: messages.error(request, 'An error has accurred during registration!') context = {'page' : page, 'form' : form} return render(request, 'users/login-register.html', context) -
KeyError at / 'daily'
current_weather_url = 'https://api.openweathermap.org/data/2.5/weather?q={}&appid={}' forecast_url = 'https://api.openweathermap.org/data/3.0/onecall?lat={}&lon={}&exclude=current,minutely,hourly,alerts&appid={}' def fetch_weather_and_forecast(city, api_key, current_weather_url, forecast_url): response = requests.get(current_weather_url.format(city, api_key)).json() lat, lon = response['coord']['lat'], response['coord']['lon'] forecast_response = requests.get(forecast_url.format(lat, lon, api_key)).json() weather_data = { 'city': city, 'temperature': round(response['main']['temp'] - 273.15, 2), 'description': response['weather'][0]['description'], 'icon': response['weather'][0]['icon'], } daily_forecasts = [] for daily_data in forecast_response['daily'][:5]: daily_forecasts.append({ 'day': datetime.datetime.fromtimestamp(daily_data['dt']).strftime('%A'), 'min_temp': round(daily_data['temp']['min'] - 273.15, 2), 'max_temp': round(daily_data['temp']['max'] - 273.15, 2), 'description': daily_data['weather'][0]['description'], 'icon': daily_data['weather'][0]['icon'], }) return weather_data, daily_forecasts --- THIS IS THE FORECAST REPONSE THAT I GET forecast_response {'cod': 401, 'message': 'Invalid API key. Please see ' 'https://openweathermap.org/faq#error401 for more info.'} Actually i am creating a weather app where i used api from https://home.openweathermap.org/ but while using the forecast url in the above function in the for loop for daily_forecasts it says that >>>KeyError at / 'daily' and the line having mistake is shown to be >>>for daily_data in forecast_response['daily'][:5]: In the for loop for daily_forecasts, I'm encountering a KeyError related to the 'daily' key in the OpenWeatherMap API response. I've verified my API key and the overall structure of the response, but I seem to be missing something crucial. please fix this it says that daily is not there but it is there . -
python manage.py runserver takes forever
I recently transfered my django project from a windows computer to a mac. The project is made up of 5 apps. Some are standalone while some has import from other apps. When I run python manage.py runserver the app never comes out of performing systems checks. I have noticed that this problem is majorly due to two apps out of the 5. This is becuase when I comment the url path from the projects main urls model the manage.py runs file. But once I uncomment it, the problems starts again. I have checked my paths and I belive the are accurate. Is there a what I can make the runserver command show me some output. Thank you for your help. -
Pre-Commit throwing Errors on Missing whitespace after ":"
I used the same pre-commit configuration on my windows pc, but since i switched to a macos, whenever i run a pre-commit on my python-django project, i get unexpected errors like missing whitespace after colon, even when the said colon iS at the end of a class definition or function definition or colons present in a url string, i know from the docs that a space is not needed after this cases, i believe this has something to do with the os switch or some misconfiguration with pre-commit on my new pc, Python VERSION: 3.12 pre-commit configuration exclude: "^docs/|/migrations/" default_stages: [commit] repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer # - id: check-yaml - repo: https://github.com/asottile/pyupgrade rev: v3.3.1 hooks: - id: pyupgrade args: [--py310-plus] - repo: https://github.com/psf/black rev: 22.12.0 hooks: - id: black - repo: https://github.com/PyCQA/isort rev: 5.12.0 hooks: - id: isort - repo: https://github.com/PyCQA/flake8 rev: 6.0.0 hooks: - id: flake8 args: ["--config=setup.cfg"] additional_dependencies: [flake8-isort] # sets up .pre-commit-ci.yaml to ensure pre-commit dependencies stay up to date ci: autoupdate_schedule: weekly skip: [] submodules: false Sample Error Message config/settings/production.py:109:21: E231 missing whitespace after ':' Acutal line pointed at in the code STATIC_URL = f"https://{aws_s3_domain}/{AWS_STORAGE_BUCKET_NAME}/payment/static/" Can anyone … -
For loop for users in Django
GoodEvening I have written a web app that list shooters scores. I have all of that working. I added a new app that will list the shooter average scores. But I can't figure out how to loop though the current users. I have use the built in User model and built another model call Scores for the individual scores. Sorry to have to ask for help. But i work on this for hours. Here is the model Scores from django.conf import settings from django.db import models from django.db.models import Avg rifle_type_choices = {("B", "B"), ("S", "S")} optic_type_choices = {("O", "O"), ("S", "S")} range_distance_choices = {("50", "50"), ("100", "100")} class Scores(models.Model): date = models.DateField() match_score = models.IntegerField() xcount = models.IntegerField() rilfe_type = models.CharField(max_length=1, choices = rifle_type_choices, default = "B") optic_type = models.CharField(max_length=1, choices = optic_type_choices, default = "O") range_distance = models.CharField(max_length=3,choices = range_distance_choices, default = "100" ) username = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) def __str__(self): return f' {self.username} {self.date}' Here is the view for the Average app # average/views.py from django.http import HttpResponse from django.template import loader from scores.models import Scores from django.db.models import Avg def index(request): template = loader.get_template("average.html"); context = { 'avg50': Scores.objects.filter(range_distance="50").aggregate(Avg("match_score")), 'avg100': Scores.objects.filter(range_distance="100").aggregate(Avg("match_score")), 'scores_list': Scores.objects.values('username') } return HttpResponse(template.render(context, request)) Here … -
Filtering select field options in Django Rest Framework
How can brand and type fields filter options based from the existing asset category chosen, and unit model filtering options based from the selected brand? This is my JS: $(document).ready(function() { const assetId = $('#asset_id').val(); axios({ method: 'get', url: `/api/assets/assets/${assetId}`, }).then(function(res) { let data = res.data; $('#id_name').val(data.name); $('#id_property_number').val(data.property_number); $('#id_serial_number').val(data.serial_number); $('#id_date_acquired').val(data.date_acquired); getAllBrand(data.brand) getAllUnitModel(data.unit_model) getAllStatus(data.status) getAllType(data.type) getAllUser(data.user) getAllDepartment(data.department) getAllArea(data.area) axios.get(`/api/assets/asset_details/`,{ params:{ asset: data.id } }).then(function(res) { const dataObj = res.data; const $formWrapper = $('#form_field_wrapper').empty(); dataObj.forEach(obj => { const assetObj = obj.asset_field; const fieldId = `id_${assetObj.field_name}`; const feedbackId = `feedback_${assetObj.field_name}`; const requiredInfo = obj.asset_form.is_required ? '<span class="text-danger">*</span>' : ''; const requiredClass = obj.asset_form.is_required ? 'form-required' : ''; switch(assetObj.field_type) { case 'radio': break; case 'checkbox': break; case 'text': var fieldData = new Object(); fieldData.assetFormId = obj.asset_form.id; // form id fieldData.assetFieldId = assetObj.id; // asset field id fieldData.assetDetailId = obj.id; // asset field id $formWrapper.append(` <div class="col-6 m-0"> <div class="form-floating mb-3"> <input type="text" class="form-control asset-form-field ${requiredClass}" id="${fieldId}" placeholder="${assetObj.field_label}" value="${obj.value}"> <label for="${fieldId}">${assetObj.field_label} ${requiredInfo}</label> <div class="invalid-feedback" id="${feedbackId}"></div> </div> </div> `); $(`#${fieldId}`).data(fieldData); break; case 'select': let fieldOptions = JSON.parse(assetObj.field_option); var fieldData = new Object(); fieldData.assetFormId = obj.asset_form.id; // form id fieldData.assetFieldId = assetObj.id; // asset field id fieldData.assetDetailId = obj.id; // asset field id $formWrapper.append(` <div class="col-6 m-0"> … -
How to resolve: Django make migrate not running in AWS ECS from Dockerfile
I have a Django project that runs in a Docker container. Locally when I have updated the project to include changes to the model, I have run python manage.py makemigrations and python manage.py migrate within the docker container. In particular, I would enter the container from the terminal and run python manage.py makemigrations and python manage.py migrate to execute the changes. This worked locally. However, now that I have pushed my code to production (AWS ECS) for some reason manage.py is not running to update the existing database. There is no evidence that manage.py is running at all, even though it is in my entrypoint.sh script. Are there any additional configs that I need to set up either in the Dajngo project or in AWS ECS to be able to run migrations in the AWS ECS environment? The project is otherwise running fine, so the docker container is up, just python manage.py migrate is never run. I have included the Dockerfile below for reference: FROM python:3.11-slim-bookworm ENV uid=1000 ENV gid=1000 ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV TZ=UTC ENV USER=app_user UID=$uid GID=$gid RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone RUN apt-get update \ && apt-get install -y … -
AWS Beanstalk container with Django app can't connect to RDS DB but it accessible from EC2 server and anothe container
My MySQL DB and EC2 instances where Elastic Beanstalk is running are in different VPCs. So I connect to DB via public IP and allow inbound connection in DB SG for my EC2 instance. But I still receive the error Access denied from DB. I tried to connect directly from that instance and even connect from another container(my Django app is crashing) and it works well. The strange things - everything works fine for one env, and doesn't work for another -
Custom authenticate function not working as expected
I have made my own backend for authenticating users with either an email or username. Now I have created a new class view in my app and im trying to authenticate a user. here is a fragment of my class view def post(self, request): dataRecieved = request.data user = authenticate(request, login = dataRecieved["login"], password = dataRecieved["password"]) return Response(user.username) try: login(request, user) return Response(status=200) except Exception: return Response("di[a") the authenticate here is from django.contrib.auth and inside it calls my authenticate function from my custom backend. I haven't changed anything here try: user = backend.authenticate(request, **credentials) except PermissionDenied: # This backend says to st.... Now here is my backend authenticator function def authenticate(self, login=None, password=None, **kwargs): if login is None or password is None: return None try: users = UserModel.objects.filter(username=login) | UserModel.objects.filter(email=login) except UserModel.DoesNotExist: return None else: for user in users: if user.check_password(password) and self.user_can_authenticate(user): return user and when i try to return the user all i get is a NoneType, what should I do? I have tried returning strings within both authenticate functions but it always comes out as a NoneType, im 100% its something wrong with my authenticate function but i have no clue what's wrong. -
i am trying to fetch data from my mongodb Database with django but keep getting : the JSON object must be str, bytes or bytearray, not OrderedDict
so i have an employes collection with a bunch of data that is in this format : { "_id": { "$oid": "511d0a9f181b16509ae5f7dd" }, "nom": "Leberre", "prenom": "Stephanie", "anciennete": 1, "adresse": { "numero": 79, "codepostal": 9500, "ville": "Toulouse", "rue": "Jean Moulin" }, "tel": 559608352, "prime": 1500 }, here is the models.py : from django.db import models class Employee(models.Model): nom = models.CharField(max_length=100) prenom = models.CharField(max_length=100) anciennete = models.IntegerField() adresse = models.JSONField() tel = models.CharField(max_length=20, blank=True, null=True) prime = models.IntegerField(blank=True, null=True) def __str__(self): return f"{self.nom}, {self.prenom}" serializers.py : from rest_framework import serializers from .models import Employee class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = '__all__' and finally views.py : from rest_framework.response import Response from rest_framework import generics from .models import Employee from .serializers import EmployeeSerializer class EmployeeListView(generics.ListAPIView): queryset = Employee.objects.all() serializer_class = EmployeeSerializer def list(self, request, *args, **kwargs): serializer = self.get_serializer(self.get_queryset(), many=True) return Response(serializer.data) i keep getting :"the JSON object must be str, bytes or bytearray, not OrderedDict ". i dont need a very specific solution, just any solution works even if it involves modifying all the files mentioned above -
Is there a solution to combine a multi tenancy django project and google authentication
I am facing a problem in my django project, i need to set up two type of users, 1- guest users ( log in with google authetication ) 2- partner users ( log in with their own e-mail but as multi tenant) if i run the project with only one them it works fine, but not together, settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition SITE_ID=2 SHARED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'tailwind', 'theme', 'sweetify', 'taggit', 'django_tenants', 'api', 'tenantapp', ] TENANT_APPS = [ # your tenant-specific apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'tailwind', 'theme', 'sweetify', #'django_browser_reload', 'taggit', 'django_tenants', 'agency', ] INSTALLED_APPS = list(SHARED_APPS) + [ app for app in TENANT_APPS if app not in SHARED_APPS ] SOCIALACCOUNT_PROVIDERS = { "google": { "SCOPE" : [ "profile", "email" ], "AUTH_PARAMS" : { "access_type":"online" } } } # possible options: 'sweetalert', 'sweetalert2' - default is 'sweetalert2' SWEETIFY_SWEETALERT_LIBRARY = 'sweetalert2' TAILWIND_APP_NAME = 'theme' INTERNAL_IPS = [ "127.0.0.1", ] MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', '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', #"django_browser_reload.middleware.BrowserReloadMiddleware", …