Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Added ForeignKey object in Custom User Model, when creating users im getting value error
Django Added ForeignKey object in Custom User Model, when creating users im getting value error this is user model(AppUser) having foreignkey in it, the error is as folllowed, ValueError: Cannot assign "1": "AppUser.branch" must be a "Branches" instance. tried with just instance also user = User.objects.create_user(email='admin@fmlk.com',branch=Branches.objects.get(name="Temp_Branch")) class AppUser(AbstractUser): username = None secId = models.CharField(max_length=255,default=sec.token_urlsafe(16)) email = models.EmailField(unique = True, null=False) password = models.CharField(max_length=255) branch = models.ForeignKey(Branches,on_delete=models.SET(tempBranch),null=False) is_verified = models.BooleanField(default = False) USERNAME_FIELD = "email" ` REQUIRED_FIELDS = ['branch'] objects = UserManager() class UserManager(BaseUserManager): def create_user(self, email, branch, password = None,**extra_fields): if not email: raise ValueError("Email is required") if not branch: raise ValueError("Need Branch") email = self.normalize_email(email.lower()) user = self.model(email = email, branch= branch, **extra_fields) user.set_password(password) user.save(using = self.db) return user def create_superuser(self, email,branch, password = None, **extra_fields): extra_fields.setdefault("is_staff",True) extra_fields.setdefault("is_superuser",True) extra_fields.setdefault("is_active",True) return self.create_user(email,branch,password, **extra_fields) >>> user = User.objects.create_user(email='admin@fmlk.com',branch=Branches.objects.get(name="Temp_Branch").id) Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/Varun/Spaces/spaces/core/manager.py", line 9, in create_user email = self.normalize_email(email.lower()) File "/Users/Varun/Spaces/env/lib/python3.10/site-packages/django/db/models/base.py", line 543, in __init__ _setattr(self, field.name, rel_obj) File "/Users/Varun/Spaces/env/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 283, in __set__ raise ValueError( ValueError: Cannot assign "1": "AppUser.branch" must be a "Branches" instance. -
nginx unit + django + docker - wsgi.py cannot import module
Currently containerizing a legacy Django project, and running into an odd error. When pushing the config file to the running server, it fails to apply, and on inspecting the log, I get the following: 2023/12/06 21:36:02 [info] 39#39 discovery started 2023/12/06 21:36:02 [notice] 39#39 module: python 3.11.2 "/usr/lib/unit/modules/python3.11.unit.so" 2023/12/06 21:36:02 [info] 1#1 controller started 2023/12/06 21:36:02 [notice] 1#1 process 39 exited with code 0 2023/12/06 21:36:02 [info] 41#41 router started 2023/12/06 21:36:02 [info] 41#41 OpenSSL 3.0.11 19 Sep 2023, 300000b0 2023/12/06 21:40:22 [info] 49#49 "myapp" prototype started 2023/12/06 21:40:22 [info] 50#50 "myapp" application started 2023/12/06 21:40:22 [alert] 50#50 Python failed to import module "myapp.wsgi" Traceback (most recent call last): File "/app/myapp/wsgi.py", line 5, in <module> from django.core.wsgi import get_wsgi_application # noqa: E402 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ModuleNotFoundError: No module named 'django' 2023/12/06 21:40:22 [notice] 49#49 app process 50 exited with code 1 2023/12/06 21:40:22 [warn] 41#41 failed to start application "myapp" 2023/12/06 21:40:22 [alert] 41#41 failed to apply new conf 2023/12/06 21:40:22 [notice] 1#1 process 49 exited with code 0 My config file is as follows: { "applications": { "myapp": { "type": "python 3.11", "module": "myapp.wsgi", "processes": 150, "environment": { "DJANGO_SETTINGS_MODULE": "myapp.settings.production", } } }, "listeners": { "0.0.0.0:8000": { "pass": "applications/myapp" } } … -
Django php bridge
I have configured my app like this: client -> server(Apache -> php -> [django]) Some requests are handled by the php, and some are "forwarded" to django. I can successfully access the django app via this php proxy. But when I try to upload a file to the server (here django should handle that request), is there any way to directly forward the file content to the django app or I need to temporarily save it in the php server and make a request to the django app for the rest? -
Bootstrap Modal - Deleting a Review using Django
I'm using a simple Boostrap modal and it works fine. I have a delete URL which will delete the review based on the id. My issue is, I don't know how to pass the review.id from the button, through to the modal confirm delete button. If I don't use a modal and just do a simple delete button, it works fine using: How do I pass that review.id through to the final button? {% url 'delete_review' review.id %} HTML: {% if request.user.is_authenticated and user.username == review.name or user.is_superuser %} <div> <a class="btn btn-black rounded-0 text-uppercase mt-2" href="{% url 'edit_review' review.id %}" role="button">Edit</a> | <!-- Button trigger modal --> <a class="btn-delete btn rounded-0 text-uppercase btn-outline-danger mt-2" data-toggle="modal" data-target="#exampleModal" role="button">Delete</a> </div> {% endif %} <hr> </div> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Delete Review</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Are you sure you want to <strong class="text-danger">DELETE</strong> your Review? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-danger" href="{% url 'delete_review' review.id %}">Delete Review</button> </div> </div> </div> </div> -
Django-pipeline collect my statics in dev
I use Django-pipeline on my project. Here are the configurations: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [ BASE_DIR / "static", ] STATIC_ROOT = os.path.join(BASE_DIR, 'zstatics') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_STORAGE = 'pipeline.storage.PipelineManifestStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) PIPELINE = { 'PIPELINE_COLLECTOR_ENABLED': False, 'PIPELINE_ENABLED': False, 'CSS_COMPRESSOR': None, 'JS_COMPRESSOR': None, 'JAVASCRIPT': { 'unauthenticated_main': { 'source_filenames': ( 'website/js/theme.bundle.min.js', 'js/htmx.min.js', 'website/vendors/js/prism.min.js', 'js/copyleft.min.js', 'js/unauthenticated_custom.min.js', 'js/oqb.min.js', ), 'output_filename': 'compressed/unauthmain.min.js', } } } It works quite well but in developpement mode with DEBUG=False it collects my files anyway, and minify them in doucble and I got new files in zstatics, the files declared in the dictionnary. for example I got a 'js/htmx.min.js' file and a 'js/htmx.min..min.js' file which is quite weird. Any idea where I failed in the configuration? -
Connecting to Amazon SQS key (SSE-SQS) Encrypted SQS Queue via Django Celery [sqs]
I am unable to get my Celery working running while connecting to an SQS Encrypted Queue This is my settings.py for my django project SQS_AWS_ACCESS_KEY_ID = 'xxxx' SQS_AWS_SECRET_ACCESS_KEY = 'xxxx' SQS_AWS_QUEUE_NAME = 'sqs.eu-west-2.amazonaws.com/xxxx/xxx-celery-broker' broker_url = f"sqs://{SQS_AWS_ACCESS_KEY_ID}:{SQS_AWS_SECRET_ACCESS_KEY}@{SQS_AWS_QUEUE_NAME}" CELERY_BROKER_URL = broker_url CELERY_RESULT_BACKEND = None CELERY_BROKER_CONNECTION_RETRY_ON_STARTUP = True When i run my worker i get this error, i assume as my Queue Name is not https:// botocore.exceptions.ClientError: An error occurred (InvalidSecurity) when calling the GetQueueAttributes operation: All requests to this queue must use HTTPS and SigV4. when i change it to SQS_AWS_QUEUE_NAME = 'https://sqs.eu-west-2.amazonaws.com/xxxx/xxx-celery-broker' I get this error Cannot connect to sqs://xxx:**@https//sqs.eu-west-2.amazonaws.com/xxx/xxx-celery-broker: Could not connect to the endpoint URL: "http://https/". The Config seems to add a random http onto the url which is why i assume its failing When i connect to a non encrypted queue it works fine as seen as This is my celery.py config os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings") # Create a Celery instance and configure it to use SQS app = Celery("proj") # Load task modules from all registered Django app configs. app.config_from_object("django.conf:settings", namespace="CELERY") # Auto-discover tasks in all installed apps app.autodiscover_tasks(settings.INSTALLED_APPS) app.conf.task_default_queue = 'xxx-celery-broker' I'm at my wits end trying to fix this im assuming there is a small config change … -
Django get a certin value from a dict with a for key value inside of a template
Sorry if my title is a bit crypt, but this is the problem I have a list of dict data = [{"a": 1, "b": 2},{"a": 3, "b": 4} ] and a list with keys = ["a","b"] I want in a template do this: for dat in data: <tr> for k in keys: <th> dat[k]</th> </tr> to get this: <tr> <th>1</th> <th>2</th> </tr> <tr> <th>3</th> <th>4</th> </tr> -
Is there any way to open Google Earth Engine images in Django and render it to leaflet?
I want to open a Google Earth Engine image in Django and display it in a Leaflet. I have used the following codes for this: l8 = ee.ImageCollection("LANDSAT/LC08/C01/T1_SR").mean() geometry = ee.Geometry.Polygon([[[-80.92489760146748, 25.433457120928352], [-80.64474623427998, 25.488013471687964], [-80.57882826552998, 25.710940372707608], [-81.02377455459248, 25.770317250349557], [-80.95236342177998, 25.552457242621447]]]); image = image.filterBounds(geometry) and my template: var map = L.map('map', { zoomControl: false }) now i want to show'image' on leaflet ap. Is there a way to do this? -
Username input and username label are overlapping after refreshing the page, this is happening for both username and password
This is my html code: {% load static %} web Login User Name Password Remember Me Log in And this my css @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap'); *{ margin: 0; padding: 0; font-family: 'poppins',sans-serif; } section{ display: flex; justify-content: center; align-items: center; min-height: 100vh; width: 100%; background: url('background6.jpg')no-repeat; background-position: center; background-size: cover; } .form-box{ position: relative; width: 400px; height: 450px; background: transparent; border: 2px solid rgba(255,255,255,0.5); border-radius: 20px; backdrop-filter: blur(15px); display: flex; justify-content: center; align-items: center; } h2{ font-size: 2em; color: #fff; text-align: center; } .inputbox{ position: relative; margin: 30px 0; width: 310px; border-bottom: 2px solid #fff; } .inputbox label{ position: absolute; top: 50%; left: 5px; transform: translateY(-50%); color: #fff; font-size: 1em; pointer-events: none; transition: .5s; } input:focus ~ label, input:valid ~ label{ top: -5px; } .inputbox input { width: 100%; height: 50px; background: transparent; border: none; outline: none; font-size: 1em; padding:0 35px 0 5px; color: #fff; } .inputbox ion-icon{ position: absolute; right: 8px; color: #fff; font-size: 1.2em; top: 20px; } .forget{ margin: -15px 0 15px ; font-size: .9em; color: #fff; display: flex; justify-content: space-between; } .forget label input{ margin-right: 3px; } .forget label a{ color: #fff; text-decoration: none; } .forget label a:hover{ text-decoration: underline; } button{ width: 100%; height: 40px; border-radius: 40px; … -
Can I create a single endpoint for authorization and registration?
I have an interesting problem that I can't cope with, I wrote an api to register a basic django user to which his profile is attached and which does not have anything special at all, now I need this api to perform 2 functions, that is, the user enters his username , mail and password, and the system should check if there is such a user? If there is no such user in the database, then register him otherwise, authorize and return tokens, here is my code: class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) email = serializers.CharField(write_only=True) is_active = serializers.BooleanField(default=False, read_only=True) refresh_token = serializers.SerializerMethodField() access_token = serializers.SerializerMethodField() class Meta: model = User fields = ('id', 'username', 'password', 'email', 'is_active', 'refresh_token', 'access_token') def create(self, validated_data): password = validated_data.pop('password') email = validated_data.pop('email') is_active = validated_data.pop('is_active', True) username = validated_data.get('username') user = User.objects.create_user(username=username, email=email, password=password, is_active=is_active) profile, created = UserProfile.objects.get_or_create(user=user) return user def get_refresh_token(self, user): refresh = RefreshToken.for_user(user) return str(refresh) def get_access_token(self, user): refresh = RefreshToken.for_user(user) return str(refresh.access_token) maybe someone knows how to add an authorization mechanism to it? -
Displaying static images with Django
Despite having gone through the 6 billion other questions asking the exact same thing, Django still seems to not want to display an image. HTML: <img src="{{ article.article_cover_image }}" alt="img"> Model: def upload_article_image_path(instance, filename): return f'./static/assets/article_media/{instance.id}/{filename}' article_cover_image = models.ImageField(upload_to=upload_article_image_path,help_text='Enter article cover image') settings.py: STATICFILES_DIRS = ( os.path.join(BASE_DIR,'catalog/static'), ) urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('catalog/', include('catalog.urls')), ] urlpatterns += [ path('', RedirectView.as_view(url='catalog/static/', permanent=True)), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) And this is the file structure: -
Django Mixed Block
I have a problem on my website I get a mixed block, the server is written in django and the front is in react + connected ssl certificate + nginx, how can I fix this problemconfig nginx, I have no idea how to go to the Django https server and how to connect a certificate there, whether a certificate is needed separately for the server side and what can be done in general server { listen 3000; listen [::]:3000 ipv6only=on; server_name localhost; listen 443 ssl; ssl_certificate crt.crt; ssl_certificate_key key.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; access_log /var/log/nginx/httpstatus.access.log; error_log /var/log/nginx/httpstatus.error.log; location / { root /data/www; index index.html; try_files $uri $uri/ /; } } I will be very pleased if you tell me where else this problem could arise -
Cannot make ForeignKey optional...?
In my django application, I defined a model: class CourtOrder(models.Model): category = models.ForeignKey(CourtOrderCategory, blank=True, null=True,on_delete=models.PROTECT) institution = models.ForeignKey(Institution, blank=True, null=True, on_delete=models.PROTECT) The class contains a number of other entries, but I'm having trouble with these two. I already read this post: How to make the foreign key field optional in Django model? But did not have any success, the debugger still tells me that my form is invalid if these values are not set. I ran python manage.py makemigrations and python manage.py migrate several times and I also tried to change the on_deletevalue to SET_NULLto see if my mistake was there, but that did not change the outcome. What am I doing wrong? -
Load data to navbar without rendering the django template
Im creating a music streaming webapp and im stuck at a certain section, so as part of the search results a list of music data is displayed and when clicked on a particular item the data about the item should be passed to the navbar without rendering the template. (the navbar is part of the indexpage and the search results are at another page) i tried using ajax but wasn't successfull since im not familiar with it , -
Django query hangs on a model with a ManyToManyField to "self", when adding to prefetch_related
I have an Offer model with a self-referential ManyToManyField: class Offer(models.Model): title = models.CharField(max_length=255) priority = models.PositiveIntegerField(default=100, help_text="The highest priority offers are applied first.") cannot_combine_with = models.ManyToManyField( "self", blank=True, help_text="Never combine this offer with these offers (only the highest priority offer is applied).", ) This query works fine: >>> Offer.objects.all() This also works perfectly fine: >>> Offer.objects.prefetch_related("cannot_combine_with").all() But as soon as I add a model manager, then Offer.objects.all() no longer completes, it just hangs. class OfferManager(models.Manager): def get_queryset(self): return ( super() .get_queryset() .prefetch_related("cannot_combine_with") ) class Offer(models.Model): _base_manager = OfferManager objects = OfferManager() # ... original fields With this manager in place I can't fetch any Offer models anymore as the query just hangs. Why is it that adding prefetch_related to the OfferManager makes the query hang, while manually adding this condition (without using a custom manager) works fine? -
How to pre-populate Username field with Django
I have a ReviewsForm created in forms.py and I have a 'name' model in models.py in my reviews app. I want the name field in this reviewsform to be prepopulated by the full_name from my Profiles app if that's at all possible. I have achieved this in my course project for the Checkout process in a convuluted way. I tried recreating that method and cleaning it up but it's just not working as expected. Somethings to add - I have a Profile Model and this is the model where the saved name is actually pulled from. I have imported this model into my reviews model. My add_review function in views.py: @login_required def add_review(request): """ Add a review to the reviews page """ if not request.user: messages.error(request, 'Sorry, you must login to do that.') return redirect(reverse('reviews')) if request.method == 'POST': form = ReviewsForm(request.POST, request.FILES) if form.is_valid(): form.save() review = form.save() messages.success(request, 'Successfully posted a review, waiting for approval.') return redirect(reverse('reviews')) else: messages.error(request, 'Failed to add review. Please ensure the form is valid.') else: form = ReviewsForm() if request.user.is_authenticated: try: profile = UserProfile.objects.get(user=request.user) review_form = ReviewsForm(initial={ 'name': profile.default_full_name, }) except UserProfile.DoesNotExist: review_form = ReviewsForm() template = 'reviews/add_review.html' context = { 'form': form, … -
Get function in django rest framework does not work even though i explicitly say for permission to allow any
I want to send my product category data to the frontend. this is my view function: class CategoryView(APIView): def get(self,request,format=None): permission_classes=[AllowAny] category=Category.objects.all() serializer=CategorySerializer(category, many=True) return Response(serializer.data) In the frontend i have this: useEffect(()=>{ axios.get('http://localhost:8000/Category/') .then(res=>setCategory(res?.data)) .catch(err=>console.log(err)) .then(res=>console.log('category are'+res?.data)) },[category]) Even though i have stated for permission to allow any, it still says 401 unauthorized error. why is this happening and how do i fix it? -
ALLOWED_HOSTS and CORS_ALLOWED_ORIGINS don't work on VPS
I have project on VPS with front-end (Angular) and back-end (Django, DRF). VPS is running on Ubuntu 22.04 and has nginx. I used docker with compose to build images and run containers. Docker works fine on VPS and if I try to get to ip-address:8081 or <domain_name:8081> I see my Angular page and other links. But if try to get port 8082 (this is where back-end is listening, see the docker-compose below) I see error DisallowedHost at /, Invalid HTTP_HOST header: 'ip-address'. You may need to add 'ip-address' to ALLOWED_HOSTS. I added everything that I found from other topics. For now I have smth like that in settings.py: ALLOWED_HOSTS = ['localhost', 'ip:8082', '127.0.0.1', 'domain_name:8082', '*',] CORS_ALLOWED_ORIGINS = [ 'http://localhost:8081', # This is to allow requests from Angular app ] but it doesn't work even when I try to rebuild images, containers and volumes. I think that's the reason why Angular can't connect to django and daphne (websocket, channels). P.S. it works locally in docker and without. If the problem can be related to CORS_ALLOWED_ORIGINS, write about it too. I don't use nginx as proxy, request filter. docker-compose.yml: version: "3" services: # Back-end django: build: context: ./back-end dockerfile: ./Dockerfile image: django-image … -
Django channels unable to connect(find) websocket after dockerize the project
Before trying to containerize the application with docker, it worked well with: python manage.py runserver with the following settings.py setction for the redis layer: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("0.0.0.0", 6379)], }, }, } and by calling a docker container for the redis layer: docker run -p 6379:6379 -d redis:5 But after trying to containerize the entire application it was unable to find the websocket: Error message in firefox console : Error message docker-compose file: services: redis: container_name: redis image: redis:latest networks: - main ports: - "6379:6379" restart: always wsgiserver: container_name: wsgiserver build: . command: sh -c "python manage.py migrate && python manage.py collectstatic --no-input && python manage.py runserver 0.0.0.0:8000" volumes: - .:/source/ expose: - "8000" networks: - main environment: - EMAIL_HOST_USER=your_email@example.com - EMAIL_HOST_PASSWORD=your_email_password - CHANNEL_LAYERS_HOST=redis depends_on: - redis restart: always asgiserver: container_name: asgiserver build: . command: daphne -b 0.0.0.0 -p 9000 ChatApp.asgi:application volumes: - .:/source/ expose: - "9000" networks: - main depends_on: - redis - wsgiserver restart: always celery_worker: container_name: celery_worker command: "celery -A ChatApp worker -l INFO" depends_on: - redis - wsgiserver - asgiserver build: . environment: - C_FORCE_ROOT="true" - CELERY_BROKER_URL=redis://redis:6379/0 - CELERY_ENABLE_UTC=True - CELERY_RESULT_BACKEND=redis://redis:6379/0 - CELERY_TIMEZONE=Asia/Tehran networks: - main restart: always nginx: … -
Adding the search button and filter button to a single button in Django
Here I am trying to activate two functions with one button. How would it be to write the search button and filter system in a single function, as shown in the examples? I used the django filters framework for the filter. example image This is my views.py file def job_list(request): jobs = Job.objects.all().order_by('-date') locations = Location.objects.all() categories = Category.objects.all() jobtypes = JobType.objects.all() experiences = Experience.objects.all() qualifications = Qualification.objects.all() genders = Gender.objects.all() #filter start my_filter = JobFilter(request.GET, queryset=jobs) jobs = my_filter.qs #filter done context = { 'jobs': jobs, 'categories': categories, 'locations': locations, 'jobtypes': jobtypes, 'experiences': experiences, 'qualifications': qualifications, 'genders': genders, 'my_filter': my_filter, } return render(request, 'jobs.html', context) Here is my filters.py file import django_filters from . models import Job class JobFilter(django_filters.FilterSet): class Meta: model = Job fields = ['location', 'category', 'experience', 'qualification', 'jobtype', 'gender'] this is the search function I also defined a URL to the search function in url.py. def search(request): search_query = '' if request.GET.get('search'): search_query = request.GET.get('search') """aynı şeyleri göstermez... distinct""" jobs = Job.objects.distinct().filter( Q(name__icontains = search_query) | Q(description__icontains = search_query) | Q(category__name__icontains = search_query) ) categories = Category.objects.all() context = { 'jobs': jobs, 'categories': categories, 'search_query': search_query, } return render(request, 'jobs.html', context) I tried many functions but … -
DJANGO template variable not rendering in HTML
I'm working on a Django project, and I'm having trouble getting a variable to render in my HTML template. I have a view that passes a dictionary containing some data to my template, and I want to display a specific value in the HTML. Here's a simplified version of my view: def my_view(request): data = {'user_name': 'John Doe', 'age': 25} return render(request, 'my_template.html', {'data': data}) n my_template.html, I'm trying to display the user's name like this: html <!DOCTYPE html> <html> <head> <title>My Template</title> </head> <body> <h1>Welcome, {{ data.user_name }}!</h1> </body> </html> However, when I load the page, the user's name doesn't render. It just shows "Welcome, !" without the actual name. What am I doing wrong? Any help would be appreciated! yaml --- In this example, the user is facing an issue with rendering a Django template variable (`data.user_name`) in their HTML. They provide relevant code snippets from both the view and the template, explain the problem they are encountering (the variable not rendering), and express a need for assistance. This type of question allows the Stack Overflow community to offer insights and suggestions for resolving the problem. -
need to connect Django project with NGINX, certbot and ngrok
I have a Django project, made a file /etc/nginx/sites-enabled/griphr-backend which include : server { listen 80; server_name 31bb-156-220-68-78.ngrok-free.app; location / { proxy_pass http://localhost:8000; # Django app runs on port 8000 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } used the ngrok to get this domain 31bb-156-220-68-78.ngrok-free.app I run this command: sudo nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful Now when run sudo certbot certonly --nginx -d 31bb-156-220-68-78.ngrok-free.app got this: Saving debug log to /var/log/letsencrypt/letsencrypt.log Which names would you like to activate HTTPS for? 1: 31bb-156-220-68-78.ngrok-free.app Select the appropriate numbers separated by commas and/or spaces, or leave input blank to select all options shown (Enter 'c' to cancel): 1 Requesting a certificate for 31bb-156-220-68-78.ngrok-free.app An unexpected error occurred: There were too many requests of a given type :: Error creating new order :: too many failed authorizations recently: see https://letsencrypt.org/docs/failed-validation-limit/ How make certbot work to generare ssl cert? -
Dynamic StatesGroup on aiogram 3.1.1
Good afternoon everyone. Curf work in a company developing telegram bots for businesses, the main stack is Django / Aiogram 3.1.1. At the moment I am faced with one difficult task and I would like to ask others about the possibility of its implementation. In short, the task is this: The database contains a table with questionnaires (field name, field question) and a table associated with the name of the question: the type of question validation (validation of number, name, mailbox, etc.), as well as a table with the user associated with the answer to the questionnaire. questionnaires and types DBdiagram My task is to create a kind of processor for filling out questions from these questionnaires. The difficulty is that, in fact, I could create a StateGroup and write it like this: class QuestionsStates(StatesGroup): email = State() phone_number = State() full_name = State() # . . .` Next, I would create handlers for each state, and after receiving and validating the data in the last state, the handlers would send the data to the database and that’s all. @router.message(QuestionsStates.last_state) async def send_data_to_backend(message: Message, state: FSMContext): user_answers = await state.get_data() # user_answer.get('') # send all data with user_id to backend … -
web_1 | Error: dictionary changed size during iteration
I have a Django Project. I have dockerized this project to run as container. Currently when I run this container using following command it shows following error at the end and exited docker-compose -f docker-compose-stag-prod.yaml up -d Docker Logs Output web_1 | Starting Gunicorn server... web_1 | 2023-12-05 18:20:18 [1] [INFO] Starting gunicorn 0.17.4 web_1 | 2023-12-05 18:20:18 [1] [INFO] Listening at: http://0.0.0.0:8000 (1) web_1 | 2023-12-05 18:20:18 [1] [INFO] Using worker: sync web_1 | /usr/local/lib/python3.10/os.py:1030: RuntimeWarning: line buffering (buffering=1) isn't supported in binary mode, the default buffer size will be used web_1 | return io.open(fd, mode, buffering, encoding, *args, **kwargs) web_1 | 2023-12-05 18:20:18 [6] [INFO] Booting worker with pid: 6 web_1 | 2023-12-05 18:20:18 [7] [INFO] Booting worker with pid: 7 web_1 | 2023-12-05 18:20:18 [8] [INFO] Booting worker with pid: 8 web_1 | 2023-12-05 18:20:18 [9] [INFO] Booting worker with pid: 9 web_1 | web_1 | Error: dictionary changed size during iteration I am not able to identify the line which is causing error. How can I identify the line number or code snippet which is causing issue. Also my application is running inside container using gunicorn exec gunicorn --bind 0.0.0.0:${PORT:-8000} --timeout 300 -w 4 -t 4 … -
Postgresql causing memory problems in django
I recently started getting this error Python(43052,0x7000021e4000) malloc: *** error for object 0x1: pointer being freed was not allocated Python(43052,0x7000021e4000) malloc: *** set a breakpoint in malloc_error_break to debug on launching my local Django server. I know Python has nothing to do with malloc which is a C library, and this kind of leaves me powerless, as I don't really know C... Shouldn't python do all this automatically? I figured that when I disconnect my PostgreSQL database (i.e. just comment out the DATABASES= ... ) in my settings.py the error goes away. It of course doesn't run my project as it relies on the database, but at least the error happens within the app. If I bring back the DATABASES, Django doesn't even start the app, as the error happens right on server startup and is only logged in the console. What's interesting is that the very same version of the program, but deployed to my production server on Azure works perfectly.