Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, gunicorn workers, scaling on Kubernetes
Kind of related to this post, we're in a similar position where we have a django application using gunicorn WSGI running on a Kubernetes cluster. I have read the official docs on how to configure num of workers (see design), but I still don't understand how this converts to a kubernetes pod running on a cluster utilising shared CPU? I have done various load tests on our test environment and the following is an idea of metrics I get and the resources in use: Django deployment containing 3 pods minimum but can scale to 20 Each pod has 1 CPU in Kubernetes config Each pod runs 3 gunicorn WSGI workers currently Pods run across Kubernetes nodes, each node has 4 CPUs Simple load testing suggests, we reach about 20-25rps maximum and then workers begin to restart, which seems quite bad! Scaling kicks in but its a lot slower than I'd like, despite optimisations, although we are slowed down a little by the istio-proxy side containers which have to start first before the app container Does anyone have any similar issues when it comes to scaling django apps? I know there can be a lot of differences depending on code, API … -
Image Upload Django with Ckeditor Failed Undefined
I'm trying to create a blog page with Django. I'm using CKEditor to add text. When I upload images locally, I don't have any issues, but I encounter a problem when I deploy the project to the server. When I go to the image upload section in CKEditor and click "Send to Server," I receive an "undefined" error in the popup that appears. failed but I don't get this error when I start the project in my local. Ckeditor -v = django-ckeditor==6.7.0 Django -v = Django==4.2.4 CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_STORAGE_BACKEND = 'django.core.files.storage.FileSystemStorage' FILEBROWSER_REMOVE_DIALOG_TABS = 'image:Upload' CKEDITOR_CONFIGS = { 'default': { 'filebrowserUploadUrl': '/ckeditor/upload/', 'filebrowserBrowseUrl': '/ckeditor/browse/', 'toolbar': 'Full', # Toolbar ayarları düzeltildi 'toolbar_Full': [ ['Styles', 'Format', 'Bold', 'Italic', 'Underline', 'Strike', 'SpellChecker', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['Image', 'Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['NumberedList', 'BulletedList'], ['Indent', 'Outdent'], ['Maximize'], {'name': 'about', 'items': ['CodeSnippet']}, {'name': 'tools', 'items': ['Maximize', 'ShowBlocks']}, ], 'tabSpaces': 4, 'fillEmptyBlocks': False, 'extraPlugins': 'justify,liststyle,indent,codesnippet,devtools,uploadimage', # Resim eklentisi eklendi 'uploadUrl': '/ckeditor/upload/', # Resim yükleme URL'si eklendi }, } Have you encountered this problem? I would like your comments on the topic. enjoy your work I didn't expect to run into a problem here. It is interesting that … -
Sending email with Celery and Redis cloud
I am trying to send an email using celery queue @shared_task as below: # removed imports for clarity # For debugging @shared_task(bind=True, name="send_email", max_retries=3, default_retry_delay=10) def send_email(self, subject, message, from_email, to_email, **kwargs): """Send an email""" try: send_mail(subject, message, from_email, [to_email], **kwargs) except Exception as e: logger.error(e) # configured logger class Command(BaseCommand): help = "Send test email" def handle(self, *args, **options): try: send_email.delay( "Test email", "This is a test email", settings.EMAIL_HOST_USER, "validemail@examle.com", fail_silently=False, ) self.stdout.write(self.style.SUCCESS("Email queued successfully")) except Exception as e: raise CommandError(e) And I get ...celery stack trace raise SMTPRecipientsRefused(senderrs) smtplib.SMTPRecipientsRefused: {'validemail@example.com': (550, b'Please turn on SMTP Authentication in your mail client. 333.kpservers.com\n(altar56.supremepanel56.com) [cpanel_server_ip]:43036 is not permitted to\nrelay through this server without authentication.')} However when I use direct send_mail without shared_task it is successful (so it doesn't seem to be a server error) How do I resolve this error? I am using redis database redis://default:*******@********.cloud.redislabs.com:13122 -
Django anon cart system not working on first visit to site
I wanted to implement an anonymous cart system to my django site. I saw on internet that I can achieve with the following javascript code: function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); function uuidv4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } let device = getCookie('device') if (device == null || device == undefined){ device = uuidv4() } document.cookie ='device=' + device + ";domain=;path=/" Which is embedded at the end of 'base.html' which is a template every other html uses. like this: <script src="{% static 'js/cookies.js'%}"></script> Followed by this home page code: class HomeView(ListView): template_name = "index.html" def get(self, *args, **kwargs): context = get_base_lists(self.request) ... return render(self.request, self.template_name, context) ... def get_base_lists(request): ... cart, created = … -
Updating objects in queryset computed with filter clears the query
I have: jobs = Job.objects.filter(detected__isnull=True).order_by('submitted') print(f"Detected {len(jobs)} jobs") jobs.update(detected=ms_now()) try: print(jobs[0].id) except: print("No objects!") Output: Detected 865 jobs No objects! It seems like the filter is re-computed due to the update, but why does this happen? -
correct response code for role management
I’ve a user model and have some roles through other models (admin , doctor , patient, manager models ... etc) . I’ve one login endpoint for all . the patient, doctor only login with mobile number (didn’t handle it yet “means if he has email can login too”). patient only uses mobile application ... doctors on the web. all endpoints of each role are guarded with it’s related model , Like all users can login successfully as long as they’ve a User model , But when they try to access the admin , doctor… etc, they must have a related relation of the role … like if a user need to access the doctor endpoints , he must have a doctor instance . A user can have many roles (can register as many roles). What’s the best response code for this case if a user tried to access doctor endpoints without having a doctor instance ? 404 (user not found ) or 403 (unauthorized) and why please give a detailed response . Thanks I've implemented the response as a 403 , but "considering the doctor can be a patient" when he (doctor) logins through mobile (as patient) while he doesn't … -
I am trying to make website where users can see user specific data, but I can get the user's data in my in order to pass it my template
On my photo album website each user should see only the images that he uploaded, however when I specify user in my get_context_data method my context object becomes empty. I tried various methods that I found in the internet, but nothing works -
How to show the video with mediapipe in html in django?
my html and views.py are refer to https://roytuts.com/upload-and-play-video-using-django/, but i want to change the display video to video with mediapipe,what should i do or change in my code? mediapipe code in views.py: def process_video(filename): input_video_path = filename output_video_path = f"processed_{filename}" cap = cv2.VideoCapture(input_video_path) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fourcc = cv2.VideoWriter_fourcc(*'MP4V') out = cv2.VideoWriter(output_video_path, fourcc, 20.0, (width, height)) while cap.isOpened(): ret, frame = cap.read() if not ret: break image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) results = holistic.process(image) # Draw landmarks and connections mp_drawing = mp.solutions.drawing_utils mp_drawing.draw_landmarks(image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS, mp_drawing.DrawingSpec(color=(121, 22, 76), thickness=2, circle_radius=4), mp_drawing.DrawingSpec(color=(121, 44, 250), thickness=2, circle_radius=2)) mp_drawing.draw_landmarks(image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS, mp_drawing.DrawingSpec(color=(80, 22, 10), thickness=2, circle_radius=4), mp_drawing.DrawingSpec(color=(80, 44, 121), thickness=2, circle_radius=2)) mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS, mp_drawing.DrawingSpec(color=(245, 117, 66), thickness=2, circle_radius=4), mp_drawing.DrawingSpec(color=(245, 66, 230), thickness=2, circle_radius=2)) out.write(image) cap.release() out.release() cv2.destroyAllWindows() -
Can I be full stack with django in backend [closed]
everyone knows that in order to be a full stack, you need to have a frontend and a backend, in the backend you usually use php, java, c # and others. The question is can I be a full stack with Django read up read up read up -
Migrate a django project to new server with already exists postgresql database of anotehr django project
I have 2 django apps on separate servers. Both have completely different models The database name of app1 is xxxx1 The database name of app2 is xxxx2 how to migrate xxxx2 to server1 without damage anything ? -
Languages Selection process [closed]
I want to be a smart front ended web developer. In future, I will shift in full stack development journey. Now, I want to enter market place because I need to earn money immediately. I have completed following languages: HTML CSS vanila js Bootstrap So please suggest me, in this step which language I should shift now so that I can start earning. Thanks to all my lovely friends. I am looking for a market place to earn money. -
Django ORM for custom python function
I have following two models class Membership(models.BaseModel): user = models.ForeignKey(User) package = models.ForeignKey(Package, on_delete=models.PROTECT, blank=True, null=True, related_name="package_membersips") benefit_end = models.DateField() benefit_start = models.DateField() class Package(models.BaseModel): name = models.CharField(max_length=40) description = models.CharField(max_length=200, null=True, blank=True) class PackageTier(BaseModel): package = models.ForeignKey(Package, on_delete=models.CASCADE, related_name='package_tiers') min_members = models.IntegerField() max_members = models.IntegerField() retail_price = models.DecimalField(max_digits=5, decimal_places=2) wholesale_price = models.DecimalField(max_digits=5, decimal_places=2) The wholesale_price and retail_price calculation consists of some logic, that is difficult to perform using ORM: def get_package_price(package_instance): count = package_instance.package_memberships.count() tier = package_instance.package_tiers.filter( min_members__lte=count + 1, max_members__gte=count + 1 ).first() if not tier: tier = package_instance.package_tiers.order_by('id').first() return tier.retail_price if tier else 0 def get_package_wholesale_price(package_instance): count = package_instance.package_memberships.count() tier = package_instance.package_tiers.filter( min_members__lte=count, max_members__gte=count ).first() if not tier: tier = package_instance.package_tiers.order_by('id').first() return tier.wholesale_price if tier else 0 These are business logic and I need to aggregate the result based on the year basis. # sample response: {"data": [ { "year": 2021, "commission": 1.0 }, { "year": 2022, "commission": 8.2 }, { "year": 2023, "commission": 11.0 }, ]} Is there any way that I can use get_package_price and get_package_wholesale_price inside Django ORM ? I used following ORM to get membership for each year: Membership.objects.all().annotate(year=ExtractYear('benefit_start')).values('year').order_by('year') The custom function need to be called in this ORM. -
Why is caching not improving the performance in my django view?
I am trying to improve performance of a view by caching a given linear algebra expression and its corresponding result. I am using memcached and pymemcache but for some reason theres no performance gain. Heres my view: @api_view(['POST']) @login_required(login_url='/api/login/') @csrf_exempt def compute_lalg_expression(request): form = LinearAlgebraExpForm(request.POST) if form.is_valid(): new_expr = form.save(commit=False) data_expr = form.cleaned_data data_expr = data_expr['exp'] exp_hash = hashlib.md5(data_expr.encode()).hexdigest() alg_exp = cache.get(exp_hash) if not alg_exp: parsed_exp = parser.parse(data_expr) eval_data = evaluate(parsed_exp) expr_model = LinearAlgebraExpression(exp=eval_data) expr_model.save() create_action(request.user, 'computed an expression', expr_model) serializer = LinearAlgebraExpSerializer(expr_model) cache.set(exp_hash, serializer.data) return Response(serializer.data) return Response(alg_exp) And here is the client I am testing it with. I am testing it by removing the lines associated with caching above so I am removing exp_hash, alg_exp and so on so I remove the if statement that checks whether alg_exp is true or false and i remove cache_set. Anyways heres my client import aiohttp import asyncio import time async def make_request(session): url = 'http://127.0.0.1:8000/api/compute/' payload = {'exp': exp + '*' + exp2} # Replace with your POST data async with session.post(url, data=payload, auth=aiohttp.BasicAuth('jobpink', 'hello123')) as response: return await response.text() async def main(): # Adjust these values as needed num_requests = 5000 # Number of requests to send concurrency = 10 … -
'403 Forbidden: CSRF verification failed. Request aborted.' in Django deployment with Railway
I am trying to deploy a Django app on Railway. I have {% csrf_token %} in each form, yet am still getting the '403 Forbidden: CSRF verification failed. Request aborted.' each time. I have inspected the page to verify the hidden csrf is being created (it is) and that the cookie exists (it does). Here is my settings.py and my full repo for reference """ Django settings for rpisite project. """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'rpiapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'rpisite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'rpisite.wsgi.application' # Database import dj_database_url DATABASE_URL = os.environ['DATABASE_URL'] DATABASES = { "default" : dj_database_url.config(default=DATABASE_URL, conn_max_age=1800) } # … -
Django forms.ModelForm Failed lookup for key [form]
I'm getting error with forms.ModelForm Failed lookup for key or empty form, any suggestions, please? VariableDoesNotExist at /timesheets/ Failed lookup for key [form] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'view': <django.views.generic.base.TemplateView object at 0x00000201195B1F50>}] forms.py from django import forms from .models import TimeSheet from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Row class TimeSheetForm(forms.ModelForm): class Meta: model = TimeSheet fields = "__all__" def __init__(self, *args, **kwargs): super(TimeSheetForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'AddNewEntry' self.helper.form_method = 'post' self.helper.layout = Layout( Row('date_time_start', 'date_time_end', 'project_code', 'user', 'milage', 'project_type', 'activities', 'expenses', Submit('submit', 'Submit') ) ) add_timesheet.html {% load crispy_forms_tags %} <div id="timesheet-form-container" class="d-none d-flex flex-row flex-nowrap justify-content-between"> <form id="timesheet-form" method="post" class="w-100"> {% csrf_token %} {% crispy form %} <button type="submit" class="btn btn-primary">Submit</button> </form> </div> views.py from django.contrib.auth.decorators import login_required from django.http import JsonResponse from django.shortcuts import render from .forms import TimeSheetForm from .models import TimeSheet def add_timesheet(request): if request.method == 'POST': form = TimeSheetForm(request.POST) if form.is_valid(): form.save() return {'success': True} else: form = TimeSheetForm() return render(request, 'timesheets/add_timesheet.html', {'form': form}) timesheets/urls.py from django.urls import path from django.views.generic import TemplateView from . import views urlpatterns = [ path('', TemplateView.as_view( template_name='timesheets/timesheets_main.html'), name='timesheets'), path('add_timesheet/', views.add_timesheet, name='add_timesheet'), path('get_timesheets/', views.get_timesheets, name='get_timesheets'), ] I`m tried … -
Creating new filter in django
I would like to use a range filter in django. Something like this : <br> <table> <thead> <tr> <th>Revenue streams</th> <th>Units</th> <th>Description</th> {% for num in 2022|range:2027 %} <th>{{ num }}</th> {% endfor %} </tr> </thead> So I have created a templatetags folder in my app and added file custom-filters.py that contains : from django import template register = template.Library() @register.filter def range(start, end): return range(start, end + 1) but the page returns : Any idea of what is mising? -
Paygreen integration with Django
I am a little bit lost with the integration of PayGreen payment gateway. I can't search nothing in Google, someone have one link or some example. I need to make via API with Python, I don't have another language knowledge, for the JS integration I mean. If someone can help me, it would be great. I am lost. I have done integrations of Stripe or Monei following instructions and tutorials, but I can't find nothing for PayGreen and I need this one. -
Django cors headers not working with POST requests
My stack is: axios for the javascript client, apache2 reverse proxy, gunicorn, django. I have setup the django-cors-headers plugin. I am able to perform GET requests to the django application. However, when I try to perform a POST query, I have a CORS error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://[...]/move_item. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://[...]/move_item. (Reason: CORS request did not succeed). Status code: (null) How is it possible that changing the http method breaks? I have not set a value to the CORS_ALLOW_METHODS from django-cors-headers. Even if I explicitly do (CORS_ALLOW_METHODS = ("DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT",)), the error persists. My apache config is straightforward. <VirtualHost *:443> ServerName [...] ProxyPass /.well-known ! ProxyPass / http://localhost:8000/ ProxyPassReverse / http://localhost:8000/ ProxyPreserveHost On SSLEngine on SSLCertificateFile /etc/letsencrypt/live/[...]/cert.pem SSLCertificateKeyFile /etc/letsencrypt/live/[...]/privkey.pem SSLCertificateChainFile /etc/letsencrypt/live/[...]/fullchain.pem Alias /.well-known /home/cliclock.justescape.fr/www/.well-known/ <Directory [...]/www/.well-known> Options FollowSymLinks MultiViews AllowOverride All Require all granted </Directory> LogLevel debug ErrorLog [...]/logs/error.log CustomLog [...]/logs/access.log combined Gunicorn is used with this command gunicorn myapp.wsgi How can I fix the situation? -
Django error: "Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomUser'" [closed]
Estoy en un curso de Django y me siento estancado. Vi varias soluciones, pero sigo sin poder solucionar el problema. Error "Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomUser'" Views.py: from django.urls import reverse_lazy, reverse from django.contrib.auth import get_user_model from django.contrib.auth.views import PasswordChangeView, PasswordChangeDoneView from django.views.generic import CreateView, DetailView, UpdateView, DeleteView from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login, authenticate from .forms import UserUpdateForm # Devuelve el modelo de usuario requerido User = get_user_model() class RegistroEInincioDeSesion(CreateView): form_class = UserCreationForm template_name = "accounts/signup.html" success_url = reverse_lazy("blog:index") # sobreescribimos el medodo form_valid def form_valid(self, form): # validar y registrar datos response = super().form_valid(form) # obtener los datos validos username = form.cleaned_data.get("username") raw_pw = form.cleaned_data.get("password") # comprobar si la contraseña es correcta (que si, por obvias razones) # y obtener el usuario user = authenticate(username=username, password=raw_pw) # iniciar sesion login(self.request, user) # devolver una respuesta HTTP return response class UserDetail(DetailView): model = User template_name = 'accounts/user_detail.html' class UserUpdate(UpdateView): model = User form_class = UserUpdateForm template_name = 'accounts/user_edit.html' # se ejecuta si la actualizacion es exitosa def get_success_url(self): # toma el argumento pk definido en la ruta y redirige a la pagina de detalles # del usuario usando el mismo argumento => user_detail/<int:pk> … -
Why is my Docx converter returning 'None'
I am new to web development and trying to create a language translation app in Django that translates uploaded documents. It relies on a series of interconversions between pdf and docx. When my code ouputs the translated document it cannot be opened. When I inspect the file type I saw it identified as XML and docx and it could be opened and read by MS Word when I changed the extension to docx(But it couldn't be read by any PDF readers). When I used my code python to analyze the file by printing the type and the contents of it I got NoneType and None. A working PDF of the file is found in mysite/mysite folder but the one output by my reConverter function that is sent to the browser is the problem file. I tried manually converting it using: wordObj = win32com.client.Dispatch('Word.Application') docObj = wordObj.Documents.Open(wordFilename) docObj.SaveAs(pdfFilename, FileFormat=wdFormatPDF) docObj.Close() wordObj.Quit() but got a CoInitialization error. My original So I've completely narrowed it down to the reConverter function returning a NoneType. Here is my code: from django.shortcuts import render from django.http import HttpResponse from django.http import JsonResponse from django.views.decorators.csrf import csrf_protect from .models import TranslatedDocument from .forms import UploadFileForm from django.core.files.storage … -
User Based Views
I am working on a project whereby I would like to generate a report which has the ability to have a drop down list of users, such that the data in the report changes depending upon the user being selected. I'm looking at this from an admin perspective. I know how to create such a view for request.user, but I'm not entirely sure how to create the functionality for a drop down list of users and then the output changes. Any thoughts as to how to do this? I do have an example of existing code I can provide to show what I am trying to achieve; however it won't necessarily answer my question. Best, Neil -
Navigation bar icon does not center correctly
In my navigation bar the element of the class "fa fa-address-card" is a dropdown menu, but it doesn't line up correctly next to the other two elements next to it ("fa fa-heart" and "fa fa-shopping-cart"), it sits a little above. How do I make it behave like the other two elements next to it? I'm using boostrap 5.0.2 and Jquery 3.7.0 My HTML: <nav class = "navbar navbar-expand-lg navbar-light bg-white py-4 "> <div class = "container barra_navegacao"> <a class = "navbar-brand d-flex justify-content-between align-items-center order-lg-0" href = "{% url 'home' %}"> <img src = "{% static 'base\img\shopping-bag-icon.png' %}" alt = "site icon"> <span class = "text-uppercase fw-lighter ms-2">Pytudo</span> </a> <div class="search-form d-flex justify-content-center align-items-center flex-grow-1"> <form class="d-flex" action="{% url 'listar_produtos' %}" method="GET"> <input type="text" class="form-control me-2" name="nome" placeholder="O que você procura?"> </form> <div class="dropdown"> <a class="nav-link text-uppercase text-dark dropdown-toggle" href="#" role="button" id="categoriasDropdown" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Categorias </a> <ul class="dropdown-menu" aria-labelledby="categoriasDropdown"> {% for categoria in categorias %} <li><a class="dropdown-item" href="#">{{ categoria }}</a></li> {% endfor %} </ul> </div> </div> <div class = "order-lg-2 nav-btns"> <div class="dropdown"> <button type="button" class="btn position-relative dropdown-toggle" id="PainelDropdown" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fa fa-address-card" aria-hidden="true"></i> </button> <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="PainelDropdown"> {% if request.user.is_authenticated %} <li><a href="{% url 'account_logout' … -
Django-Docker: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known
First-time docker-user: I recently added a cron job to my Django project and dockerized it. When I run docker-compose up --build, the system builds and runs the cron job, which exits with a code 137 (which is expected, since I'm running locally). When I try to run the cron job manually to troubleshoot methods of lowering the cron's CPU usage, I am met with: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known This error is odd to me, since everything is fine upon build, but it seems like the command no longer knows what the database is outside of the build even with the project running. Also, does this mean my cron job can't execute in its designated time The following are links to similar posts that may be helpful to others with a similar issue, but have not solved my problem: Why this error, docker operational error (django project)? How to fix this error django.db.utils.OperationalError: could not translate host name "db" to address . Docker Docker-compose with django could not translate host name "db" to address: Name or service not known Docker run, after docker-compose build could not translate host name “db” to … -
Assign model permissions of Model1 to a Model2 in django using django guardians
I am using Django Guardians in my project and it works fine so far, but there is some problem: I need to assign permissions from model1 to the instance of the model2. Real example: The shop has some contracts and the shop owner wants to assign his employees permission to change contract fields (e.g. field1). So we have 3 models now: Shop, Contract, and User, and each model has it's own defined permissions per field like: can_change_field1, ... All permissions that employee can have must be related to the Shop model because when a shop owner assign contract permissions to his employee (to change field1 in contract in shop1), it mustn't affect another shop (So user will not be able to change that field e.g. field1 in shop2,...). 1st solution can be: to create all permissions in shop model (for all models: Contract,...). But it seems kinda of messy to me. What do you think? Please, Can you suggest some nice solution to this problem? -
angular display status_text differently on local vs prod
I have a simple login method in angular that calls the service API and I want to display the error to the alert service. However, the response parsed from the server is not same local vs prod in cloud environment. this.authService .login(this.f.username.value, this.f.password.value) .pipe(first()) .subscribe({ next: () => { // get return url from query parameters or default to home page this.alertService.success("Login successful"); const returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; this.router.navigateByUrl(returnUrl); }, error: (error) => { this.alertService.error(error); this.loading = false; }, }); this works well locally the response shows { "headers": { "normalizedNames": {}, "lazyUpdate": null }, "status": 401, "statusText": "Unauthorized", "url": "http://localhost:4200/api/v1/token/", "ok": false, "name": "HttpErrorResponse", "message": "Http failure response for http://localhost:4200/api/v1/token/: 401 Unauthorized", "error": { "type": "client_error", "errors": [ { "code": "no_active_account", "detail": "No active account found with the given credentials", "attr": null } ] } however, in prod it is giving me different statusText somehow { "headers": { "normalizedNames": {}, "lazyUpdate": null }, "status": 401, "statusText": "OK", "url": "https://remoteurl-cloudrun-app/api/v1/token/", "ok": false, "name": "HttpErrorResponse", "message": "Http failure response for https://simpledc-tkbsnc6b4a-uc.a.run.app/api/v1/token/: 401 OK", "error": { "type": "client_error", "errors": [ { "code": "no_active_account", "detail": "No active account found with the given credentials", "attr": null } ] } I can't understand why. …