Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implementing a search query inside a filter
I've been trying to implement a search bar inside my application, but I don't know how to query for similar names inside my db. Here is my view.py queryprms = request.GET name = queryprms.get('name') status = queryprms.get('status') if name: moderatorRoom = PokerRoom.objects.values("id", "first_name_user", "date", "name", "status", "styleCards", "datetime", 'slug' ).filter(Q(user=user), Q(name=name)).order_by("-datetime") The problem is that when the user search for a similar word, say "Alch" for "Alchemy", the query returns empty even if "Alchemy" object exist inside my db. I want that the query returns similar objects for the user's search. How can I do that? By the way, I'm using Postgre and Django 3.1.5. -
Retrieve all dynamic fields from dynamic html form in Django
I created a dynamic html form. Now I want to retrieve the dynamic data in my django view function can anyone guide me on how to do that. This is the HTML of the dynamic section: <div class="dynamic-section" name="dynamic-section" id="dynamic-section"> <div class="single-container" id="single-container-1"> <div class="triple"> <div class="sub-triple"> <label>Relation</label> <select name="relation-1" id="relation-1"> <option value="Mentions">Mentions</option> <option value="Does not mention">Does not mention</option> </select> </div> <div class="sub-triple"> <label>Category</label> <select name="category-1" id="category-1"> <option value="Person">Person</option> <option value="Organization">Organization</option> <option value="Time">Time</option> <option value="Location">Location</option> </select> </div> <div class="sub-triple"> <label>Value</label> <input type="text" name="value-1" id="value-1" placeholder="Name.." required/> <ul class="value-1-list"></ul> </div> <div class="close-btn"> <button class="danger" onclick="removeTriple('single-container-1')" id="close-1"> <i class="fa fa-close"></i> </button> </div> </div> </div> </div> This is the javascript function to add more fields in this dynamic section: function addTriple() { triple_index += 1; var single_section = document.createElement('div'); let sectionID = 'single-container-' + triple_index; single_section.setAttribute("id", sectionID); single_section.setAttribute("class", "single-container"); var andOrSelect = document.createElement('select'); let andOrSelectID = 'andOr-' + triple_index; andOrSelect.setAttribute("name", andOrSelectID); andOrSelect.setAttribute("id", andOrSelectID); newAndOrHtml = ` <option value="and">and</option> <option value="or">or</option> ` newTripleHTML = ` <div class = "triple"> <div class = "sub-triple"> <label>Relation</label> <select name="relation-` + triple_index + `" id="relation-` + triple_index + `"> <option value="Mentions">Mentions</option> <option value="Does not mention">Does not mention</option> </select> </div> <div class = "sub-triple"> <label>Category</label> <select name="category-` + triple_index … -
Django CacheOps - Secondary read-only redis node
We use both the default django cache and CacheOps. All backed by Redis, the default cache has some nice docs on setting up a secondary ReadOnly node (https://django-redis-cache.readthedocs.io/en/latest/advanced_configuration.html#master-slave-setup) but can't find the same instructions for Cacheops. Any pointer? Redis is not in cluster mode, managed by AWS. -
django.core.exceptions.FieldError: Unknown field(s) specified for User
I have a hard time understanding the whole registration, login, edit profile part. I feel that I get very confused when writing the code. I was following a tutorial to be able to make a page to edit the profile but I get this error: django.core.exceptions.FieldError: Unknown field(s) (fax, phone1, zip, alternativeContact, city, address, socialMedia1, phone2, socialMedia2, website, state, country) specified for User But at no point do I see where those fields are, I don't have it, even in EditProfileForm there are only two fields "state and zip" could you give me a guide to know what is happening url path('profile/edit-profile/',UserEditView.as_view(),name='edit-profile'), models.py class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,default=0) image=models.ImageField(default='profilepic.jpg',upload_to='profile_pictures') location=models.CharField(max_length=100,default=0) phone1=models.IntegerField(default=0) phone2=models.IntegerField(default=0) fax=models.IntegerField(default=0) email=models.CharField(max_length=100,default=0) website=models.CharField(max_length=100,default=0) socialMedia1=models.CharField(max_length=100,default=0) socialMedia2=models.CharField(max_length=100,default=0) socialMedia3 = models.CharField(max_length=100,default=0) alternativeContact=models.CharField(max_length=100,default=0) country = models.CharField(max_length=100, default=0) address=models.CharField(max_length=100, default=0) city=models.CharField(max_length=100,default=0) state=models.CharField(max_length=100,default=0) zip=models.CharField(max_length=10,default=0) def __str__(self): return self.user.username views.py class UserEditView(generic.UpdateView): form_class=EditProfileForm template_name='Usuarios/edit-profile.html' success_url=reverse_lazy('profile') def get_object(self): return self.request.user forms.py class EditProfileForm(UserChangeForm): state = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) zip = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model=User fields = ('state', 'zip') -
Cannot update a Django user profile
I have a react app interacting with django to create and update user profiles. I am encountering this error message when I try to update a user profile, specifically the first name and last name properties I get a response that indicates that my user profile has not been updated {"username":"***","email":"emmanuelsibanda21@gmail.com","password":"****","first_name":"","last_name":""} This is what I have in my urls.py: path('update_profile/<int:pk>', views.UpdateProfileView.as_view(), name='update_profile'), UpdateProfileView: class UpdateProfileView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UpdateUserSerializer def profile(request): if request.method == 'PUT': try: user = User.objects.get(id=request.user.id) serializer_user = UpdateUserSerializer(user, many=True) if serializer_user.is_valid(): serializer_user.save() return Response(serializer_user) except User.DoesNotExist: return Response(data='no such user!', status=status.HTTP_400_BAD_REQUEST) UpdateUserSerializer: class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) class Meta: model = User fields = ['username', 'email', 'password', 'first_name', 'last_name'] extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}} def validate_email(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(email=value).exists(): raise serializers.ValidationError({"email": "This email is already in use."}) return value def validate_username(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(username=value).exists(): raise serializers.ValidationError({"username": "This username is already in use."}) return value def update(self, instance, validated_data): user = self.context['request'].user if user.pk != instance.pk: raise serializers.ValidationError({"authorize": "You don't have permission for this user."}) instance.first_name = validated_data['first_name'] instance.last_name = validated_data['last_name'] instance.email = validated_data['email'] instance.username = validated_data['username'] … -
Django REST API - Forbidden CSRF Cookie not set
When I try to login into my angular aplication occurs the error in the image bellow. I have already tried to comment django.middleware.csrf.CsrfViewMiddleware in the settigns.py file and already put @csrf_exempt on the Django method("login_view") but the error keeps occurring. I'm using an HTTP service and not HTTPS settings.py ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True ... views.py @csrf_exempt @api_view(["POST",]) @permission_classes([AllowAny]) def login_view(request): ... -
Django models: which field to use for position/order of an object
My project is a basic scrum board with a model Column, of which there can be unlimited instances. Each column is displayed side by side, and I want the order of the columns to be customizable. My thought was to use an IntegerField to determine numerical position, but I'm struggling with how to set the max_value equal to the total number of columns since it varies by board. Here's how I set it up: class Column(models.Model): name = models.CharField(max_length=25) board = models.ForeignKey(Board, on_delete=models.CASCADE) position = models.IntegerField(unique=True,min_value=1, max_value=???) My problem was what to use as the max_value. I tried solving it by doing this: class Column(models.Model): max_value = Column.objects.get(board=board).count() name = models.CharField(max_length=25) position = models.IntegerField(unique=True,min_value=1, max_value=max_value) I know this obviously won't work. Could I somehow use class Meta to set constraints instead, or what would be a good way to approach this? -
Django: Method Not Allowed (GET)
I'm creating an e-commerce project just for studies, all the apps created in django are working perfectly, except where the account creation would be. The problem: I don't get any exceptions in the code, but when I try to view the page in the browser there's nothing but a blank page, as if django couldn't get to the .html. My views.py: from django.views import View from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView from django.contrib.auth.models import User from django.contrib.auth import authenticate, login import copy from . import models, forms class AccountBase(View): template_name = 'account/create.html' def setup(self, *args, **kwargs): super().setup(*args, **kwargs) self.cart = copy.deepcopy(self.request.session.get('cart', {})) self.account = None if self.request.user.is_authenticated: self.account = models.Account.objects.filter( user=self.request.user).first() self.context = { 'userform': forms.UserForm( data=self.request.POST or None, user=self.request.user, instance=self.request.user, ), 'accountform': forms.AccountForm( data=self.request.POST or None, instance=self.account ), } else: self.context = { 'userform': forms.UserForm( data=self.request.POST or None ), 'accountform': forms.AccountForm( data=self.request.POST or None ), } self.userform = self.context['userform'] self.accountform = self.context['accountform'] self.renderer = render(self.request, self.template_name, self.context) def get(self, *args, **kwargs): return self.renderer class Create(View): def post(self, *args, **kwargs): if not self.userform.is_valid() or not self.accountform.is_valid(): return self.renderer username = self.userform.cleaned_data.get('username') password = self.userform.cleaned_data.get('password') email = self.userform.cleaned_data.get('email') if self.request.user.is_authenticated(): user = get_object_or_404(User, username=self.request.user.username) … -
How do I use the virtual env in Arch Linux?
enter image description here How do I create a virtual environment in Arch Linux? -
How do i make Django get text after comma for editing?
my form before clicking the edit button my form after clicking the edit button the input isn't showing all the strings after comma ``` def UpdateMainCategory(request, slug): maincat = MainCategories.objects.get(slug=slug) if request.method == 'POST': if len(request.FILES) != 0: if len(maincat.icon) > 0: os.remove(maincat.icon.path) maincat.icon = request.FILES['iconimage'] maincat.name = request.POST.get('maincat') maincat.status = request.POST.get('catstatus') maincat.meta_title = request.POST.get('metatitle') maincat.meta_keywords = request.POST.get('metakeywords') maincat.meta_description = request.POST.get('metadescription') maincat.save() messages.success(request, "Main Category Updated Successfully.") return redirect('/products/categories/')``` my .html code sample ``` <input type="text" name="maincat" class="form-control" placeholder="Baby Products..., Electronics..." maxlength="100" value={{ maincat.name }} required data-validation-required-message="This field is required" />``` -
Django filter, if only last value in a query is true
How to filter all objects of the ViewModel if only the last InfoModel.check_by_client_a is True ? I have the structure like this: class InfoModel(model.Models): ... service = ForeingKey(ServiceModel) check_by_client_a = BooleanField() check_by_client_b = BooleanField() check_date = DateTimeFiled() ... class ServiceModel(model.Models): ... class ViewModel(model.Models): ... service = ForeingKey(ServiceModel) ... -
Problems trying to improve performance on ModelResource
We have a model, with almost 200k objects and an Export button on Admin that was getting timeout. The resource was dehydrating properties and accessing to DB many times, so I thought that create annotations to those known fields should fix I tried to override the get_queryset on my class that extends from resources.ModelResouce but without success, this override never had been called, I tried next to override the admin.ModelAdmin.get_queryset and then I had some changes and the export was way better than before, but the load on this Admin became to be too slow What is the better way to keep Admin on same performance and apply the annotations only on Resource class? -
TypeError: reverse() takes exactly 2 arguments (1 given)
For some weird reason, reverse function is not working even though my url has no arguments. Url.py: from django.urls import path from . import views urlpatterns = [ path("api/v2/app/nextdialog", views.NextDialog.as_view(), name="app-next-dialog"), ] views.py: class StartAssessment(generics.GenericAPIView): def post(self, request, *args, **kwargs): data = request.data request = build_rp_request(data) response = post_to_app_start_assessment(request) path = get_path(response) step = get_step(response) data["path"] = path data["step"] = step request = build_rp_request(data) app_response = post_to_app(request, path) message = format_message(app_response) return Response(message, status=status.HTTP_200_OK) functions.py: def get_endpoint(payload): head = { "Content-Type": "application/json", } url = reverse("app-next-dialog") response = requests.post(url, data=json.dumps(payload), headers=head) return response When I run this I get the following error. url = reverse("app-next-dialog") TypeError: reverse() takes exactly 2 arguments (1 given) Please does anyone have an idea what's wrong here. I wouldn't think I need to add any other arguments. Thanks -
Django & HTMX - after GET show only section of html template
I want to create an instagram clon. I created a post.html which includes a post-card.html file for all posts and a post-filter.html to filter the posts. <!-- simple post.html view --> <div> <div> {% include '_includes/bars/post-filter.html' %} </div> <div id="more-posts-wrapper"> {% for post in posts %} {% include '_includes/cards/post-card.html' %} {% endfor %} </div> </div> Now I added htmx to load more posts after clicking load more button. I tried to load the new posts after the existing one inside the div with id=more-posts-wrapper: <div> <div> {% include '_includes/bars/post-filter.html' %} </div> <div hx-get="?page={{ page_obj.next_page_number }}" hx-trigger="click" hx-swap="innerHTML" hx-target="#more-posts-wrapper"> <p>LOAD MORE</p> </div> <div id="more-posts-wrapper"> {% for post in posts %} {% include '_includes/cards/post-card.html' %} {% endfor %} </div> </div> Unfortunately, if I press the button, the correct reponse post gets delivered but the whole post.html document gets loaded after the div with id=more-posts-wrapper. I only want to load the post-card.html file and not reload the post-filter.html file. Does anyone know what I can do? -
My sheduled emails(django_q) not working on heroku
I want to mention that everything runs perfectly on my machine localy: I run py manage.py runserver with py manage.py qcluster and then I'm creating task with a deadline and getting an email at certain time, when my task is approaching the deadline, but it is not working on heroku. The problem is certainly not in smtp settings, because I'm getting regular mails through my app I'm using django_q library and sqlite3 as my db. I never deployed any apps before, so I was expecting issues, but I can't find any soution that works for me. I've just started to learn about async tasks, so I would also appreciate any good book/guide/etc. that can clarify how to work with schedulers and deploy all this stuff. Here is my settings.py: from pathlib import Path import os import sys # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent sys.path.insert(0, os.path.join(BASE_DIR, 'apps')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-*z=f*cev*k!rz(g7z9_m3m*%%6%^0box%9sey+5^l520_b-h(q' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True #heroku and localhost ALLOWED_HOSTS = ['ttl-nosov.herokuapp.com', '127.0.0.1'] … -
Django + Celery. Communication of microservices
I have 2 separate microservices. One django server and the other is a celery beat which should send an API request to django once a minute. Docker-compose version: '3' services: # Django application web: build: ./WebService container_name: web_mysite command: python manage.py runserver 0.0.0.0:8000 volumes: - ./WebService/:/Microservices/first/WebService/ ports: - "8000:8000" depends_on: - db_1 env_file: - ./WebService/.env networks: - main # PostgresSQL application db_1: image: postgres:latest container_name: web_postgres restart: always volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=password - POSTGRES_DB=user_balance ports: - "5432:5432" networks: - main # Redis Broker application redis: image: redis container_name: redis ports: - "6379:6379" networks: - main # Celery application celery_worker: restart: always build: context: ./StatisticsService container_name: celery_worker command: celery -A celery_app worker --loglevel=info volumes: - ./StatisticsService/:/Microservices/first/StatisticsService/ - .:/StatisticsService/data depends_on: - redis - db_2 networks: - main # Celery-Beat application celery_beat: restart: always build: context: ./StatisticsService container_name: celery_beat command: celery -A celery_app beat --loglevel=info volumes: - ./StatisticsService/:/Microservices/first/StatisticsService/ - .:/StatisticsService/data depends_on: - redis - db_2 networks: - main volumes: postgres_data: networks: main: Celery-beat func @celery.task() def monitoring(): print("Monitoring balance...") with requests.Session() as session: res = session.get("http://127.0.0.1:8000/api/v1/transaction/current_balance/", data={"user_id": total}) if res.status_code == 200: res_json = res.json() print(res_json) And in celery worker and beat i got Error: requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8000): Max … -
Is the server running on host "db" (172.28.0.2) and accepting TCP/IP connections on port 5432? Docker
django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "db" (172.28.0.2) and accepting TCP/IP connections on port 5432? docker-compose version: '3.9' services: backend: build: ./backend command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - ./backend:/app/backend ports: - "8000:8000" env_file: - backend/.env.dev depends_on: - db db: image: postgres:14-alpine volumes: - postgres_data:/var/lib/postgresql/data/ ports: - "5432:5432" env_file: - backend/.env.dev volumes: postgres_data: Dockerfile: FROM python:3.9.10-alpine ENV PYTHONUNBUFFERED 1 WORKDIR /app/backend COPY requirements.txt /app/backend RUN pip install --upgrade pip RUN apk add --update --no-cache postgresql-client RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev RUN pip install -r requirements.txt RUN apk del .tmp-build-deps EXPOSE 8000 CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] Database setting: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": os.environ.get("POSTGRES_DB"), "USER": os.environ.get("POSTGRES_USER"), "PASSWORD": os.environ.get("POSTGRES_PASSWORD"), "HOST": os.environ.get("POSTGRES_HOST"), "PORT": 5432, } } .env : POSTGRES_USER=user POSTGRES_PASSWORD=password POSTGRES_DB=my_db POSTGRES_HOST=db -
Django QuerySet Regex with MongoDB
I am trying to use Django QuerySet/Filter with Regular Expression to filter the records in my MongoDB database. For the Python packages, I'm using: Django 4.0.3 djongo 1.3.6 pymongo 3.12.6 Here's my current attempt (code): import re from .models import User regex = re.compile(pattern) result = User.objects.filter(name__iregex=regex.pattern) However, I get djongo.exceptions.SQLDecodeError every time I use the filter like above. After looking through StackOverflow, I find out that I can filter by using Django raw but I still want to know if there are any other ways to make the above codes viable. -
Django Cookiecutter Channels3 - connection opens, doesn't send
I started a a project with Django Cookiecutter w/ Docker: https://cookiecutter-django.readthedocs.io/en/latest/ I'm trying to add Channels and follow the tutorial in their docs: https://channels.readthedocs.io/en/stable/tutorial I added Channels 3.0.4 to requirements.txt, rebuilt the docker container. I added channels to settings/base.py, and this: WSGI_APPLICATION = "config.wsgi.application" ASGI_APPLICATION = "config.asgi.application" I updated my config/asgi.py file: import os import sys from pathlib import Path from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from the_pub.chat import routing ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent sys.path.append(str(ROOT_DIR / "the_pub")) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") django_application = get_asgi_application() from config.websocket import websocket_application # noqa isort:skip application = ProtocolTypeRouter({ "https": django_application, "websocket": AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ), }) async def application(scope, receive, send): if scope["type"] == "http": await django_application(scope, receive, send) elif scope["type"] == "websocket": await websocket_application(scope, receive, send) else: raise NotImplementedError(f"Unknown scope type {scope['type']}") created a config/websocket.io file async def websocket_application(scope, receive, send): while True: event = await receive() if event["type"] == "websocket.connect": await send({"type": "websocket.accept"}) if event["type"] == "websocket.disconnect": break if event["type"] == "websocket.receive": if event["text"] == "ping": await send({"type": "websocket.send", "text": "pong!"}) views: # chat/views.py from django.shortcuts import render def index(request): return render(request, 'chat/index.html') def index(request): return render(request, 'chat/index.html', {}) def room(request, room_name): return render(request, 'chat/room.html', { 'room_name': … -
display data in a Multiplechoicefield using a database, forms and bootstrap template
I'm new to Django. I would like to know how to do this manipulation. I have data in my database that I would like to retrieve in a SELECT using forms.py and display that on template (control-form) how to proceed? Thank you I'm a beginner, I want to know -
Intregrity Error In Django after removing one filed
After removing one column from one table i am getting Intregrity error,How to solve the issue, from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('cricket', '1_tennis_ball'), ] operations = [ migrations.RemoveField( model_name='movie', name='application', ), ] -
Chart js multiple pie chart on one page
Iam building my portfolio website and i build a simple stocktracker. I added some charts from Chart.js, but somehow only one gets rendered when I excecute the code. I managed to assign all the divs and data dynamically by making the variables dynamic. I did this by adding the portfolio id in the for loop. I can't figure out why its not working. Appreciate any help. {% extends 'base.html' %} {% block page_content %} {% if user.is_authenticated %} <body> <div class="container"> <div class="row"> <div class="col-12"> <h2> Welcome to the stocktracker </h2> <p>I build this stocktracker app to learn database operations. To get current stock data, I linked this to the free API from Polygon.io. It's only possible to do 5 API calls per minute. You will see an error message whenever the api calls are exceeded. <br><br>Current features are: <ol> <li>Basic CRUD database operation</li> <li>Adding portfolio's linked to user</li> <li>Only show portfolio's linked to user</li> <li>Show general KPI's in portfolio overview</li> <li>KPI's calculated based on positions in portfolio</li> <li>Adding position to portfolio</li> <li>API connection with Polygon.io to get live stock data</li> <li>Chart.js integration for visual representation of portfolio metrics</li> </ol> </p> </div> </div> <div class="row"> <div class="col-8"> <h2>Select your portfolio</h2> … -
How to solve error on using tomtom mapfit?
According to this guide:https://developer.tomtom.com/blog/build-different/adding-tomtom-maps-django-app-building-front-end-map I'm trying to use the tomtom for my django project and everything is working well except the zoom part where the map should zoom according to the accordinates I gave it. The error I get the on explorer consol log is: Uncaught (in promise) Error: `LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, an object {lon: <lng>, lat: <lat>}, or an array of [<lng>, <lat>] The code I tried to run: // create the map tt.setProductInfo('Google Map', '1.0'); let map = tt.map({ key: 'uQInAdnkd8siEnOQdsXUcFi36iHwrgGF', container: 'map' }); // add store markers let bounds = [] let storeLocations = JSON.parse("{{ locations|escapejs }}"); for (let storeLocation of storeLocations) { let coordinates = [storeLocation.longitude, storeLocation.latitude]; bounds.push(coordinates); // create popup to display store information when the marker is clicked let popup = new tt.Popup().setHTML(` <div class="locator-popup"> <h6>Store Name</h6> <p>${storeLocation.name}</p> <h6>Address</h6> <p>${storeLocation.address}</p> </div> `); let marker = new tt.Marker() .setLngLat(coordinates) .setPopup(popup) .addTo(map); } // zoom the map to fit all markers map.on('load', () => { console.log(bounds) map.fitBounds(bounds, { padding: { top: 50, bottom:50, left: 50, right: 50 } }); }) Note: I was thinking that's maybe because of the 'bounds'. So, Checked the output … -
Folders statics not found in server google - Django
Django cannot find the static files on the google server, the python manage.py collectstatic command has already been used with the settings.py configured. To solve this problem I followed several tutorials that showed us how to deploy static files, including the documentation itself. However, none got results. It is worth mentioning that this same code and configuration worked in the homolog version of the system. -
How to add django-crontab in docker container with user django project
Problem ? I am using django-crontab. I can't run it as an authorized user on Docker alpine. I get the following error no crontab for app adding cronjob: (6e4989c275eb1a7f1e4c58d3442c53fe) -> ('*/1 * * * *', 'core.cron.hello') initgroups failed: app Operation not permitted unable to read replacement file /tmp/tmp1ehdmy4i% Docker File FROM python:3.9-alpine3.13 LABEL maintainer="mrfk" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt COPY ./app /app COPY ./scripts /scripts WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache postgresql-client && \ apk add --update --no-cache --virtual .tmp-deps \ build-base postgresql-dev musl-dev linux-headers && \ /py/bin/pip install -r /requirements.txt && \ apk del .tmp-deps && \ apk add --update busybox-suid && \ apk --no-cache add dcron libcap && \ adduser --disabled-password --no-create-home app && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/media && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts && \ chmod 755 /usr/bin/crontab* ENV PATH="/scripts:/py/bin:$PATH" USER app CMD ["run.sh"] Run.SH File #!/bin/sh set -e ls -la /vol/ ls -la /vol/web whoami service cron start python manage.py wait_for_db python manage.py collectstatic --noinput python manage.py migrate uwsgi --socket :9000 --workers 4 …