Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pip not installing any package
I have been trying to install django on my virtual environment using pip to learn creating websites, but whenever i try to install django using the command pip install django the terminal out put is the following: WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/1d/23/02f3795a71196019bcfec4c67890a6369e43b023474154fa0b2b7060346d/Django-5.0.6-py3-none-any.whl.metadataWARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/1d/23/02f3795a71196019bcfec4c67890a6369e43b023474154fa0b2b7060346d/Django-5.0.6-py3-none-any.whl.metadataWARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/1d/23/02f3795a71196019bcfec4c67890a6369e43b023474154fa0b2b7060346d/Django-5.0.6-py3-none-any.whl.metadataWARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/1d/23/02f3795a71196019bcfec4c67890a6369e43b023474154fa0b2b7060346d/Django-5.0.6-py3-none-any.whl.metadataWARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/1d/23/02f3795a71196019bcfec4c67890a6369e43b023474154fa0b2b7060346d/Django-5.0.6-py3-none-any.whl.metadataERROR: Could not install packages due to an OSError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Max retries exceeded with url: /packages/1d/23/02f3795a71196019bcfec4c67890a6369e43b023474154fa0b2b7060346d/Django-5.0.6-py3-none-any.whl.metadata (Caused by ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")) The result is an OSError. however I thought it would be better to show all the output. I reinstalled python. I tried to install it out of a virtual environment. I tried to install it other packages to see if its django's fault. I tried running the … -
Django Manifest with Elastic Beanstalk Docker Platform
I have my application running on Elastic Beanstalk with Docker Platform and I am using my own nginx container. Recently for serving static files I used Manifest django tool which is successfully running but after deploying this tool I am getting this on my web I wanna tell you that the staticfiles.json is perfectly being created in my staticfiles folder and the new versions of my static files are perfectly being generated. Here is my settings.py And here is my urls.py I even tried not in if statement cuz my app holds DEBUG-False on elastic beanstalk. The logs are saying nothing - Please HELP!!! -
Trouble running django app in vs code on macos, I'm on the correct directory I believe
So I am trying to run my django project in my vs code terminal but I get the following error message below. I'm in the right directory, that is User/coreyvigil/remotifyIO. But I do run this command `python manage.py runserver'. PS I would like to add that I am currently using a virtual environment for Python .venv. I eve tried looking at my settings for Python. Anything would help me, here is my Git URL if you need it. https://github.com/remoteconn-7891 (.venv) coreyvigil@Coreys-Air remotifyIO % python manage.py runserver /Library/Frameworks/Python.framework/Versions/3.12/Resources/Python.app/Contents/MacOS/Python: can't open file '/Users/coreyvigil/remotifyIO/manage.py': [Errno 2] No such file or directory -
Issue with creating new pigeon and his parent records in a Django form
I am new to programming and currently learning Django. I am working on a web application where users can register new pigeons into a database. The registration form includes fields for the pigeon's name and a long dropdown menu with all the existing records for the father and the mother, which becomes quite tedious with many pigeons. Is there a strategy to solve this? Something like search fields to allow the user to search and select the father and the mother? And if parents do not exist, to add functionality to register them from there, similar to the admin form? If the father or mother doesn't exist in the database, the user should be able to create a new parent record directly from the main registration form without leaving the page. I have implemented the following model for the Pigeon: `python from django.db import models class Pigeon(models.Model): GENDER_CHOICES = ( ('male', 'Male'), ('female', 'Female'), ) name = models.CharField(max_length=100) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) father = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='children_set') mother = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='children_set') def __str__(self): return self.name ` I'm facing an issue where I can't seem to create new parent records from the main registration form. Could … -
Getting ConnectionError while running elastic search using docker in django project
I am recently learning docker. I want to run elasticsearch using docker. It works fine when I only add code to run elastic search in docker file. But I am getting Connection error caused by: ConnectionError(Connection error caused by: NewConnectionError when I update docker-compose.yml file to start server, postgresql db and elastic search. Below is the code for dockerfile and docker-compose.yml file. Dockerfile FROM python:3.8-slim-buster ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt COPY . /code/ docker-compose.yml `version: '3' services: db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data environment: POSTGRES_DB: myproject POSTGRES_USER: myprojectuser POSTGRES_PASSWORD: password web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db - es environment: - DATABASE_URL=postgres://myprojectuser:password@db:5432/myproject es: image: docker.elastic.co/elasticsearch/elasticsearch:7.14.0 environment: - discovery.type=single-node ports: - "9200:9200" volumes: - es_data:/usr/share/elasticsearch/data volumes: postgres_data: es_data: ` Can anyone help me to fix this error please? I tried to run only elastic search container, it works fine. But when I update docker-compose.yml file to start django server, pg db and elastic search I am getting issue. -
Python Admin Issue
This is my admin.py code; from django.contrib import admin from userauths.models import User class UserAdmin(admin.ModelAdmin): list_display=['username', 'email', 'bio'] admin.site.register(User, UserAdmin) I want my admin page to display a list of users in a table but unfortunately bringing the below error; File "/home/daniel/newproject/my_env/lib/python3.12/site-packages/django/core/management/commands/runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "/home/daniel/newproject/my_env/lib/python3.12/site-packages/django/core/management/base.py", line 485, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "/home/daniel/newproject/my_env/lib/python3.12/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/daniel/newproject/my_env/lib/python3.12/site-packages/django/contrib/admin/checks.py", line 51, in check_admin_app errors.extend(site.check(app_configs)) ^^^^^^^^^^^^^^^^^^^^^^^ File "/home/daniel/newproject/my_env/lib/python3.12/site-packages/django/contrib/admin/sites.py", line 96, in check if modeladmin.model._meta.app_config in app_configs: ^^^^^^^^^^^^^^^^ AttributeError: 'User' object has no attribute 'model' -
After pushing log out button the app is forwarding me to empty page
After pushing log out button the app is forwarding me to https://it-company-task-manager-uzrc.onrender.com/accounts/login/ But there is an empty page and after log out I'm still logged in and can do things (create task etc) I tried to solve it in different ways, but nothing changes. You can check it by yourself: https://it-company-task-manager-uzrc.onrender.com sidebar.html: <li class=""> <a href="{% url 'login' %}" class="icon"> <i class="fa-solid fa-right-from-bracket"></i> <span class="ml-4">Log out</span> </a> </li> login.html: {% extends "base.html" %} {% load static %} {% block login %} <section class="login-content"> <div class="container"> <div class="row align-items-center justify-content-center height-self-center"> <div class="col-lg-8"> <div class="card auth-card"> <div class="card-body p-0"> <div class="d-flex align-items-center auth-content"> <div class="col-lg-6 bg-primary content-left"> <div class="p-3"> <h2 class="mb-2 text-white">Sign In</h2> <p>Login to stay connected.</p> {% if form.non_field_errors %} {{ form.non_field_errors }} {% endif %} <form action="{% url 'login' %}" method="post"> {% csrf_token %} <div class="row"> <div class="col-lg-12"> <div class="floating-label form-group"> {% if form.username.errors %} {{ form.username.errors }} {% endif %} <input class="floating-input form-control" type="text" name="username" placeholder="Username"> </div> </div> <div class="col-lg-12"> <div class="floating-label form-group"> {% if form.password.errors %} {{ form.password.errors }} {% endif %} <input class="floating-input form-control" type="password" name="password" placeholder="Password"> </div> </div> </div> <input type="hidden" name="next" value="{{next}}" /> <button type="submit" class="btn btn-white">Sign In</button> </form> </div> </div> <div class="col-lg-6 content-right"> … -
Resolving Celery Timeout Issues on Heroku: 504 Errors for Long-Running Asynchronous Tasks
I have a Django v5.0.6 application (Python v3.12) in which I integrated Celery v5.4 to run asynchronous tasks, such as generating images via the OpenAI API, which takes about 2 minutes. The entire setup is deployed on Heroku. Here is the content of my Procfile: web: gunicorn mngrs_backend.wsgi --timeout 600 worker: celery -A mngrs_backend worker -l info --time-limit=7200 However, after 30 seconds, I get the following error in the logs: I am looking to increase the delay to avoid a timeout. Here are the attempts I made without success: Added --timeout 600 in the gunicorn command in the Procfile Added --time-limit=7200 in the celery command in the Procfile Added a timeout to the API request: requests.post(url, json=payload, headers=headers, timeout=600) Modified the configuration in celery.py app = Celery("mngrs_backend") app.conf.update( task_soft_time_limit=60 * 10, task_time_limit=60 * 12, ) Added in the project settings: CELERY_BROKER_TRANSPORT_OPTIONS = { "visibility_timeout": 60 * 60 * 2, # 2 hours } Locally with Celery, I do not have any timeout issues. I contacted Heroku support, but they told me the problem is with my Celery configuration. Does anyone have a solution? -
How to output the name of the current tag to the template? (The one we are in)
I'm trying to display the name of the current tag, i.e. the one we are in. Does not work. How to write correctly to display a tag in a template? #Models from django.db import models from taggit.managers import TaggableManager class Blog(models.Model): title = models.CharField(max_length=150) created_at = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=550) tags = TaggableManager() def __str__(self): return self.title #Views from django.shortcuts import render from django.views.generic import ListView from .models import * from taggit.models import Tag class TagMixin(object): def get_context_data(self, **kwargs): context = super(TagMixin, self).get_context_data(**kwargs) context['tags'] = Tag.objects.all() return context class PostIndexView(TagMixin,ListView): model = Blog template_name = 'blog.html' queryset=Blog.objects.all() context_object_name = 'posts' class TagIndexView(TagMixin,ListView): model = Blog template_name = 'blog.html' context_object_name = 'posts' def get_queryset(self): return Blog.objects.filter(tags__slug=self.kwargs.get('tag_slug')) #Templates {% if tag %} <h3>Posts by tag: {{ tag }}</h3> <!-- Does not display tag name --> {% endif %} P.s. The site asks for more description, but what else can be described here? The problem with the output is described -
Django Best practices: migration & contenarization
I am working on a Django API and I'd like to add a bit of CI/CD to it. It dockerize my app with FROM python:3.12 WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 ENV DJANGO_SETTINGS_MODULE=vocab_dictionnary.settings CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] I then add a docker-compose.yml services: db: image: postgres:14 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_USER=" - "POSTGRES_PASSWORD=" - "POSTGRES_DB=" ports: - 5438:5432 healthcheck: test: pg_isready -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-${POSTGRES_USER:-postgres}} interval: 5s timeout: 5s retries: 120 start_period: 30s web: build: . command: python3 /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: db: condition: service_healthy environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: The end of my main.yml file for github actions looks like this - name: Run Database Migrations uses: appleboy/ssh-action@master with: host: ${{ secrets.SERVER_HOST }} username: ${{ secrets.SERVER_USERNAME }} password: ${{ secrets.SERVER_PASSWORD }} script: | cd /${{ secrets.SERVER_USERNAME }}/api/vocab_dictionnary/ docker compose exec web python manage.py migrate Finally, to simplify my local dev workflow, I added this in a Makefile: restart: docker compose down docker compose build docker compose up -d docker compose run web python3 manage.py makemigrations docker compose run web python3 manage.py migrate My first problem is that my migrations doen't apply … -
How to serialize snake_case model fields to camelCase in django rest framework
I'm adding REST API endpoints to my existing Django application. I'm using DRF ModelSerializer. My model classes follow the pep8 naming convention and use snake_case for field names, but I need the JSON response to be in camelCase. How can I achieve that in a cross-cutting way without defining proxy fields on each of my serializers? -
How to solve Django error 'django.db.utils.IntegrityError: NOT NULL constraint failed: myapi_article.author_id’
I am attempting to build a dummy news site to learn django. I am running into the stated error when performing a POST request to create a new article which is linked to a signed in user via the author ForeignKey. Users are handled using JWT on the front end. I have been stuck on this for a few days and am out of places to look for answers. Here are the serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password', 'email'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) return user class ArticleSerializer(serializers.ModelSerializer): author= UserSerializer(read_only=True) class Meta: model = Article fields = '__all__' #read_only_fields = ['author'] Here is the relevant view: class ArticleCreateView(generics.ListCreateAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer permission_classes = (IsAuthenticated,) def perform_create(self, serializer): serializer.save(author=self.request.user) and here is the relevant model: class Article(models.Model): headline = models.CharField(max_length=200) subtitle = models.CharField(max_length=300) section = models.CharField(max_length=200, blank=True, null=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='articles') body = models.TextField() #pub_date = models.DateTimeField(auto_now_add=True, blank=True, null=True) endorsements = models.IntegerField(default=0, blank=True, null=True) def __str__(self): return self.headline I am aware that I could set the author field to accept null/blank values and silence the error, but this would not really solve the … -
500 Internal Server Error Exception inside application. Daphne
ValueError: No application configured for scope type 'http' in my django terminal message It's my first time using Stack Overflow, so it's hard. Please understand if I'm not good at asking questions import os from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import chat.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hyean.settings') application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) this is my asgi.py code help me! thank you guys settings.py ASGI_APPLICATION = 'hyean.asgi.application' -
ajax not passing data to view in Django
I am trying to send ajax request but request QueryDict is empty index.html var coin = Number(localStorage.getItem("coin")) if (coin!=0) { debugger $.ajax({ url:"/", method:"POST", headers:{"X-CSRFToken":$("input[name=csrfmiddlewaretoken]").val()}, data:{"coin":coin}, contentType:"application/json", success:function(data){ console.log(data) localStorage.setItem("coin",0) }, error:function(errMsg){ console.log(errMsg) localStorage.setItem("coin",0) } }) } views.py elif request.method == "POST": print(request.POST) response = JsonResponse({"a":"b"},status=200) return response cmd <QueryDict: {}> [09/Jun/2024 09:36:49] "POST / HTTP/1.1" 200 10 web console web console image output i expect in cmd <QueryDict: {"coin":anynumber }> [09/Jun/2024 09:36:49] "POST / HTTP/1.1" 200 10 -
Django SMTPServerDisconnected at /reset_password/ Connection unexpectedly closed
So I am trying to send a password reset link to users but I keep getting this error. My views.py: def password_reset_request_view(request): if request.method == 'POST': email = request.POST.get('email') if email: try: user = CustomUser.objects.get(email=email) subject = "Password Reset Requested" email_template_name = "users/password_reset_email.html" c = { "email": user.email, "domain": request.get_host(), "site_name": "Your Site", "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, "token": default_token_generator.make_token(user), "protocol": 'http', } email_content = render_to_string(email_template_name, c) logger.debug(f"Sending email to {user.email}") logger.debug(f"Email content: {email_content}") # Create an SMTP connection with debug level set to 1 connection = get_connection() connection.open() connection.connection.set_debuglevel(1) send_mail( subject, email_content, settings.DEFAULT_FROM_EMAIL, [user.email], fail_silently=False, connection=connection ) messages.success(request, 'A message with reset password instructions has been sent to your inbox.') logger.debug("Email sent successfully") return redirect('password_reset_done') except CustomUser.DoesNotExist: messages.error(request, 'No account found with this email address.') logger.error("No account found with this email address") return redirect('reset_password') return render(request, 'users/password_reset.html') My settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.mail.yahoo.com' # Your email service SMTP server EMAIL_PORT = 587 # The port your SMTP server uses (e.g., 587 for TLS) EMAIL_USE_TLS = True # Use TLS for security EMAIL_HOST_USER = 'abrarshahriar360@yahoo.com' # Your email address EMAIL_HOST_PASSWORD = 'password' # Your email password DEFAULT_FROM_EMAIL = 'abrarshahriar360@yahoo.com' # Default from email address I feel like my code … -
How can I build the Backend for a reminding feature like in Google Calendar using django and python?
I need to implement a feature that has a recurring nature to it. A user will be able to set a reminder and that reminder will have a frequency to it. The types of frequency are as follows: Daily Weekly Biweekly Monthly Bimonthly Quarterly Half Yearly Yearly Biyearly And to top it off I also need to allow the user to add a "remind me {x} hours before {the scheduled reminder}" Please HELP! Can somebody explain to me the technologies I'll need to use to build a feature like this? To be more precise—to build the backend for it. I did some research and found out about Celery & Redis as the way to go besides a Cron job. And then upon finding out about Celery-Beat I gave up. Why? Because it's all so very confusing and complex. I'm not sure if this is the right way, or not. It seems to me like this could be made inefficiently very easily, if done by brute-force, or very complex, if done efficiently. -
Intermittent Process Stoppage with Requests Library in Django App on Google Compute Engine When Using Gemini API
I am developing a web application with Django. The environment is n2-standard-2(debian) on Google Compute Engine. I am using the requests library to make a request to use gemini-1.5-flash using the API as shown in the following [script]. Normally, [1] is followed by a DEBUG log for [2], but once in 4 times, the process stops working with [1] (no [2] or later is generated and the process stops working as is). It works fine in the local environment (windows), but it always occurs in the GCE environment. Please tell me why does it happen and how to collect it. [1]DEBUG: urllib3.connectionpool:starting new HTTPS connection (1): generativelanguage.googleapis.com: 443 [2]DEBUG: urllib3.connectionpool:https://generativelanguage.googleapis.com:443 “POST /v1/models/gemini-1.5-flash:generateContent?key= hogehoge HTTP/1.1” 200 None [Script] response = session.post(url, headers=headers, json=data, timeout=20) I tried to force a timeout using signal.signal(signal.SIGALRM, timeout_handler) and signal.alarm(20), but no luck -
authenticate() returns none in django
In django i have created a custom user and custom user manager as below: this is my models.py codes: class CustomUserManager(BaseUserManager): def create_user(self, phone_number, password=None): if not phone_number: raise ValueError('وارد کردن تلفن همراه ضروری میباشد.') user = self.model(phone_number=phone_number) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone_number, password): user = self.model(phone_number=phone_number) user.set_password(password) user.is_active = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser, PermissionsMixin): username = None name = models.CharField(max_length=30, blank=True, null=True) phone_regex = RegexValidator(regex=r'^09\d{9}$', message="شماره تلفن را به صورت ۰۹********* وارد کنید.") phone_number = models.CharField(max_length=11, validators=[phone_regex], unique=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'phone_number' objects = CustomUserManager() def __str__(self): return self.phone_number this is my forms.py codes: class UserSignupForm(forms.Form): def __init__(self, *args, **kwargs): super(UserSignupForm, self).__init__(*args, **kwargs) self.fields['phone_number'].label = "شماره تلفن" self.fields['phone_number'].widget.attrs['class'] = 'form-control input-bg-white l-field' self.fields['password'].label = "رمز عبور" self.fields['password'].widget.attrs['class'] = 'form-control input-bg-white l-field' self.fields['password'].widget.attrs['id'] = 'login-signup-pass' def clean_phone_number(self): phone_number = self.cleaned_data['phone_number'] if CustomUser.objects.filter(phone_number=phone_number).exists(): raise forms.ValidationError("این شماره تلفن قبلا در سایت ثبت شده است.", code="already-exist") return phone_number phone_number = forms.CharField( widget=forms.TextInput(attrs={'placeholder': "09123456789"}), validators=[RegexValidator(r'^09\d{9}$', message="شماره تلفن وارد شده معتبر نمیباشد.")] ) password = forms.CharField(widget=forms.PasswordInput) class Meta: model = CustomUser fields = ['phone_number', 'password'] and this is my views.py codes: if request.method == 'POST': user_signup_form = UserSignupForm(request.POST) repairman_signup_form = RepairmanSignupForm(request.POST) if user_signup_form.is_valid() … -
How to handle permissions of media files uploaded in django?
Need urgent help Hi guys, need a help about a project. How can I handle media files securely in django and Django rest framework? Basically the files should be private. For example, suppose this is a digital product website, where the buyer will only get access to the file if he/she purchases the digital product. Otherwise, the product file should be private. I can handle the permissions of drf and django views. But usually the media files are not private, the media files can be access via url easily. If one buyer purchases and share the file link with others everyone can download even without creating an account. So how can I handle this? Also how can I handle video files, that needs to be streamed to the frontend. Thanks -
Is it possible to implement different colours for the various components, such as minimum, maximum, quartiles and median in box and whisker plot?
I am searching for a library or html and javascript code to implement box and whisker plot and each component such as minimum, maximum, quartiles and median should be represented in different colours. Is it possible to implement such box and whisker plot? -
How to start celery beat on azure app service
I want my django app run celery beat automatically without start. I have deployed my django api on azure app service. How can i start celery beat on startup and make it always run without manual start. I Have setup celery with azure cache redis. -
elastic search index is not creating
I tried to create search index in elastic search using document and manually both gives error: curl -X PUT "localhost:9200/elastic_book" -H 'Content-Type: application/json' -d' { "mappings": { "properties": { "title": { "type": "text" }, "description": { "type": "text" }, "author": { "type": "text" } } } } ' {"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"Root mapping definition has unsupported parameters: [author : {type=text}] [description : {type=text}] [title : {type=text}]"}],"type":"mapper_parsing_exception","reason":"Failed to parse mapping [properties]: Root mapping definition has unsupported parameters: [author : {type=text}] [description : {type=text}] [title : {type=text}]","caused_by":{"type":"mapper_parsing_exception","reason":"Root mapping definition has unsupported parameters: [author : {type=text}] [description : {type=text}] [title : {type=text}]"}},"status":400} PUBLISHER_INDEX = Index('elastic_book') PUBLISHER_INDEX.settings( number_of_shards=1, number_of_replicas=1 ) @PUBLISHER_INDEX.doc_type class BookDocument(Document): title = fields.TextField() description = fields.TextField() author = fields.TextField() class Django: model = Book when i run the python manage.py search_index --rebuild command it gives : raise HTTP_EXCEPTIONS.get(status_code, TransportError)( elasticsearch.exceptions.RequestError: RequestError(400, 'mapper_parsing_exception', 'Root mapping definition has unsupported parameters: [author : {type=text}] [description : {type=text}] [title : {type=text}]') -
Celery: attach custom logger to default celery handler (logfile)
I would like to have a logger that can be used both in django and in celery. When used by django it should print to console, while when used from a celery task, I would like it to output using the default celery handler (in my case, it dumps to a file specified by the --logfile cmd line argument). This is especially useful for helper functions that are used by both the django server and celery tasks. This is what I have in my settings.py file: LOGLEVEL = os.environ.get("LOGLEVEL", "info").upper() LOGGING = { "version": 1, # the dictConfig format version "disable_existing_loggers": False, # retain the default loggers "handlers": { # console logs to stderr "console": { "class": "logging.StreamHandler", "formatter": "verbose", }, "django.server": DEFAULT_LOGGING["handlers"]["django.server"], }, "formatters": { "verbose": { "format": "[{asctime}]|{levelname}| {message}", "style": "{", }, "django.server": { # "()": "django.utils.log.ServerFormatter", "format": "[{asctime}]|{levelname}| {message}", "style": "{", }, }, "loggers": { # default for all undefined Python modules "": { "level": "WARNING", "handlers": ["console"], }, # Our application code "app": { "level": LOGLEVEL, "handlers": ["console"], # Avoid double logging because of root logger "propagate": False, }, # Default runserver request logging "django.server": DEFAULT_LOGGING["loggers"]["django.server"], "django.channels.server": DEFAULT_LOGGING["loggers"]["django.server"], }, } In my "app" logger, I have … -
how to Implement non-blocking, sequential AI moves in a multiplayer chess game in django channels?
I'm developing a website to play a special with kind of chess with React and Django. It pretty much requires two games to be played at the same time. The website allows to add AI players, so the common scenario is to have board 1 (human vs AI) and board 2 (AI vs AI). I want the computer players to behave in a manner that they play a move, wait a second, then let another one play, not blocking other games. The problem is that the following code makes the entire AI vs AI game play in a blink of an eye and makes it impossible to send and receive any event (even the game.start event does not get sent). This is my code that triggers the computers playing against each other: for game in started_games: await self.channel_layer.group_send( self.room_group_name, {'type': 'game.start'}) if self.is_ai_turn_in_game(game): if game.gamemode == GameMode.CLASSICAL.value: board = chess.Board(fen=game.fen) else: board = chess.variant.CrazyhouseBoard(fen=game.fen) print(self.is_ai_turn_in_game(game)) while self.is_ai_turn_in_game(game): await self.handle_ai_turn(game, board) await self.send_move_to_clients(game) self.send_move_to_clients processes some data, then calls await self.channel_layer.group_send( self.room_group_name, {'type': 'game.move', 'message': response_data} ) which executes the following code: async def game_move(self, event): move = event['message'] await self.send(json.dumps(move)) await asyncio.sleep(1) I am wondering if I should use a … -
Is there an option to use nginx instead of traefik?
The "Select a front-end web server/proxy to use" option seems to be gone. I'm using cookiecutter-django's docker compose setup. I'd rather use nginx (a more familiar technology without the excessive abstractions of traefik).