Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Advanced search in django rest framework
I have a database containing lots of posts with a number of fields(title, content, tags). I want to build a search system to look for posts. It seemed really easy first but it turns out it is not. For instance, when I type 'how to' I want my system show posts containing at least one of the word('how' or 'to' or 'how to' is the best scenario) but the problem is when I type 'how to' my system searches for only posts containing 'how to' not 'how' or 'to'. Please help me to build the system. class PostsSearch(APIView): def get(self, request, format=None): search = request.GET.get('search') query = SearchQuery(search) vector = SearchVector('title') + SearchVector('tags__name') posts = Post.objects.prefetch_related('tags').annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.0001).order_by('-rank') serializer = PostsSerializer(posts, many=True) return Response(serializer.data) I tried the code I provided above but it does not work at all -
django email activation feature failing
the view def activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): raise Http404("Invalid activation link") if generate_token.check_token(user, token): user.is_active = True user.save() login(request, user) messages.success(request, "Your account has been activated!") return redirect(reverse('index')) else: raise ValidationError("Invalid activation link") the url path('activate/<uidb64>/<token>/',views.activate,name='activate'), the token.py file from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.pk) + text_type(timestamp)) generate_token = TokenGenerator() the confirmation email is indeed being sent but whenever i click on that link i get this error ! -
trying to call Post.objects.filter(category=cats) in my view
im trying to call this method in my view: def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats) return render(request, 'categories.html', {'cats': cats, 'category-posts': category_posts}) and i have the category defined in my model, but for some reason the error is creating a field in my Model called objects -
Javascript: Input value on fields and show value on popup
I have a registration form. After filling up the forms, the reference number will display in popup. A reminder for the user to use for logging in the system. register.html <div>Reference No.<input type="text" name="refno" value="{{ refno }}" readonly></div> <div>Name<input type="text" name="name"></div> ... <button type="submit" id="getInputValue()" class="btn">Submit</button> this is my script function getInputValue() { let textElement = document.getElementById('refno').value; alert(textElement); views.py if request.method == 'GET': random_chars = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8)) refno = f"{random_chars}" return render(request, 'registration_form.html', {"refno": refno}) if request.method == 'POST': refno = request.POST.get('refno') name = request.POST.get('name') ... Applicant.objects.create(refno=refno, name=name, ...) return redirect(/user_login/) So after the button was clicked, the msg should display the reference number before it proceed to the login form. So I'm a bit confused on how to show the popup first before login. If I write return render(request, 'registration_form.html'), it will just return to the form. With this code I have, it doesn't even show a pop up. Thank you in advance. -
I am trying to set up django channels for a chat feature in my web app but i am getting DLL import error
File "C:\Users\user.virtualenvs\cinemahub-_4auLGIo\lib\site-packages\cryptography\exceptions.py", line 9, in from cryptography.hazmat.bindings._rust import exceptions as rust_exceptions ImportError: DLL load failed while importing _rust: The specified procedure could not be found. I uninstalled channels 3.0.5 and run python manage.py, the error disappeared. but the Asgi server wasnt showing on terminal. I installed channels 4.0.0 and Daphne but daphne causes the same error however when i remove daphne, the error disappears. I want the asgi server to show on the terminal. I aslo installed and uninstalled cryptography numerous times yet error still appears -
AWSApprunner not able to send email from django
When I try to send and email from django running on AWSAppRunner instance, the screen stays loading for a while and then it turns all white. If I open my debugger, I see a 502 network error: Origin checking failed {My DOMAIN APPEARED HERE } does not match any trusted origins. I Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: Origin checking failed does not match any trusted origins and I added these credentials mentioned in that stack page (CSRF_TRUSTED_ORIGINS,CORS_ORIGIN_WHITELIST, CORS_ALLOWED_ORIGINS, SECURE_PROXY_SSL_HEADER) and then got this error. Origin checking failed - null does not match any trusted origins. I do have the CSFR token on my html {% csrf_token %}. I know its the email because I comment that send_email function and everything works as expected. I verified the identities (from email and to email) in AWS SES. I installed SES with pip and added : EMAIL_BACKEND = 'django_ses.SESBackend' AWS_SES_REGION_NAME = 'us-east-2' AWS_SES_REGION_ENDPOINT = 'email.us-east-2.amazonaws.com' I also have my access key, I was able to send the email using my localhost (My own computer running python manage.py runserver). I allowed all trafic in and out on the security group. What else can I try ? def nuevaorden_view(request): … -
Django unable to connect to PostgreSQL Docker container using hostname (WSL)
I'm facing an issue where my Django application, running on Windows Subsystem for Linux (WSL), can't connect to a PostgreSQL database running in a Docker container. The error I'm getting in Django is: django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known I'm starting the PostgreSQL container using the following Docker command: docker run --name postgres -p 5432:5432 -e POSTGRES_PASSWORD=postgres -d postgres And this is my environment varaible in django: DATABASE_URL=postgres://postgres:postgres@postgres:5432/postgres How can I fix this? -
Django can't connect to Redis Server using Docker
I'm getting started with Docker. Trying to dockerize django application I am facing the problem with the connection to redis-server i ran from docker Here is the error it throws: Error 111 connecting to 127.0.0.1:6379. Connection refused. Docker-compose.yml: version: '3.8' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - '8000:8000' depends_on: - db - redis-server db: restart: always image: postgres ports: - '5432:5432' environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: Legal # volumes: # - pgdata:/var/lib/postgresql/data redis-server: image: "redis:alpine" command: redis-server networks: - djangonetwork volumes: prometheus_data: {} grafana_data: {} django_data: {} settings.py: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://redis-server:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } CACHE_TTL = 60 * 30 -
Django channels - Not Found: /ws/stock/track/
I'm following this video, but I don't get the same console output as in the video. My console output: [20/Feb/2024 19:09:12] "GET /stocktracker/?stockpicker=AAPL&stockpicker=AMGN HTTP/1.1" 200 6449 Not Found: /ws/stock/track/ [20/Feb/2024 19:09:12] "GET /ws/stock/track/?stockpicker=AAPL&stockpicker=AMGN HTTP/1.1" 404 2613 Console output on local site (using py manage.py runserver): stockpicker=AAPL&stockpicker=AMGN stocktracker/?stockpicker=AAPL&stockpicker=AMGN:176 WebSocket connection to 'ws://127.0.0.1:8000/ws/stock/track/?stockpicker=AAPL&stockpicker=AMGN' failed: (anonymous) @ stocktracker/?stockpicker=AAPL&stockpicker=AMGN:176 asgi.py: """ ASGI config for backend project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/ """ import os from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from Tradingapp.routing import websocket_urlpatterns os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') # Initialize Django ASGI application early to ensure the AppRegistry # is populated before importing code that may import ORM models. django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": django_asgi_app, # Just HTTP for now. (We can add other protocols later.) "websocket": AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ) }) routing.py: from django.urls import re_path from . import consumers websocket_urlpatterns = [ # Celery data is sent to a "group" and this group has multiple users #to listen for the same thing via websockets re_path(r'ws/stock/(?P<room_name>\w+)/$', consumers.StockConsumer.as_asgi()), ] JS connection: const roomName = JSON.parse(document.getElementById('room-name').textContent) var queryString = window.location.search queryString = queryString.substring(1) … -
Web server with NGINX, Gunicorn (with workers > 1), and Djagno fails to save JWT in a cookie at server side
I have a WSGI Django application, with Gunicorn before it and Nginx as a web server. The Django Application is a Stateless DRF API. Django Related Configs REST_AUTH = { 'USE_JWT': True, 'JWT_AUTH_COOKIE': 'wird-jwt-auth', 'JWT_AUTH_REFRESH_COOKIE': 'wird-jwt-refresh', 'JWT_AUTH_RETURN_EXPIRATION': True, 'JWT_AUTH_HTTPONLY': False, "SESSION_LOGIN": False, "USER_DETAILS_SERIALIZER": "core.serializers.PersonSerializer", "PASSWORD_RESET_SERIALIZER": "core.util_classes.PasswordResetSerializer" } SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") SECURE_HSTS_SECONDS = 2_592_000 SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin" # Application definition SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True X_FRAME_OPTIONS = 'DENY' PERMISSIONS_POLICY = {"fullscreen": "*", } INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', "django.contrib.postgres", 'member_panel.apps.StudentConfig', 'admin_panel.apps.AdminPanelConfig', 'core.apps.CoreConfig', 'rest_framework', "rest_framework.authtoken", 'django.contrib.sites', 'allauth', 'allauth.account', 'dj_rest_auth.registration', 'django_filters', 'corsheaders', 'polymorphic', 'drf_yasg', "cachalot", ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "django_permissions_policy.PermissionsPolicyMiddleware", 'django.middleware.locale.LocaleMiddleware', 'allauth.account.middleware.AccountMiddleware', ] Nginx Configs upstream app { server localhost:8200; } server { server_name .; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://app; 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; proxy_redirect off; } location /static/ { alias .; try_files $uri $uri/ =404; } location /media/ { alias .; try_files $uri $uri/ =404; } listen 443 ssl; # managed by Certbot # ssl files } When Gunicorn's workers are >1 the JWT Token I save at Client side disappear after the first refresh. When workers=1 … -
MacOS Django Less Issue
I used Django to use Less on my Windows computer without any issues, but when I switched to MacOS, the system reported an error enter image description here StaticCompilationError at /friendLink node:fs:1336 handleErrorFromBinding(ctx); ^ Error: ENOENT: no such file or directory, mkdir '/static/styles/less/global' at Object.mkdirSync (node:fs:1336:3) at module.exports.sync (/Users/taro/.nvm/versions/node/v16.14.0/lib/node_modules/less/node_modules/make-dir/index.js:97:6) at ensureDirectory (/Users/taro/.nvm/versions/node/v16.14.0/lib/node_modules/less/bin/lessc:172:7) at writeOutput (/Users/taro/.nvm/versions/node/v16.14.0/lib/node_modules/less/bin/lessc:230:7) at /Users/taro/.nvm/versions/node/v16.14.0/lib/node_modules/less/bin/lessc:311:9 { errno: -2, syscall: 'mkdir', code: 'ENOENT', path: '/static/styles/less/global' } Step: pip install django-static-precompiler npm install less -g Django setting.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '/static/') STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_PRECOMPILER_OUTPUT_DIR = '' Django templates: {% load compile_static %} {% load static %} ... <link rel="stylesheet" href="{% static "styles/less/global/components.less"|compile %}"/> I am certain that the Django project has this folder/static/styles/less/global enter image description here I thought it was a permission issue $ where lessc /Users/taro/.nvm/versions/node/v16.14.0/bin/lessc sudo chmod +x /Users/taro/.nvm/versions/node/v16.14.0/bin/lessc But it's useless I also tried PyCharm's File Watcher settings But it shouldn't be a problem. When I write a less file and save it, CSS will still appear Is it a problem with NVM, django static precompiler configuration, or macos? I'm not sure -
django if any of many to many has filed with value of False
Say I have a model of a library and I want to hide some books if either the book is marked as hidden or any of authors is marked as hidden or any of categories is marked as hidden. class Category(CustomModel): name = models.CharField(max_length=32, unique=True, null=False, blank=False) ... is_hidden = models.BooleanField(default=False) class Person(CustomModel): first_name = models.CharField(max_length=64, null=False, blank=False) ... is_hidden = models.BooleanField(default=False) class Book(CustomModel): title = models.CharField(max_length=128, null=False, blank=False) authors = models.ManyToManyField(Person, null=False, blank=False) translators = models.ManyToManyField(Person, null=True, blank=True) ... categories = models.ManyToManyField(Category, null=False, blank=False) ... is_hidden = models.BooleanField(default=False) Now I tried these queries to exclude all books with either, is_hidden=True, authors__is_hidden=True, translators__is_hidden=True, or categories__is_hidden=True: as this: books = Book.objects.filter( is_hidden=False, authors__is_hidden=False, translators__is_hidden=False, categories__is_hidden=False).distinct() and this: books = Book.objects.filter( is_hidden=False, authors__is_hidden__in=[False], translators__is_hidden__in=[False], categories__is_hidden__in=[False]).distinct() but I cannot find a way to achieve it. I wish to achieve my goal without a loop since the number of entries can get as high as 80K. How to make the query? -
Problems with implementing logout functionallity
i am trying to implement logout but everytime it throw [21/Feb/2024 00:11:58] "GET /logout/ HTTP/1.1" 405 0 if i try to logout trough drf view by clicking on admin -> logout it has the same error [21/Feb/2024 00:11:58] "GET /logout/ HTTP/1.1" 405 0 questionTime/urls.py from django.conf import settings from django.contrib import admin from django.contrib.auth import views as auth_views from django.contrib.auth.views import LogoutView from django.urls import include, path, re_path from django_registration.backends.one_step.views import RegistrationView from core.views import IndexTemplateView from users import views as ws from users.forms import CustomUserForm urlpatterns = [ path('admin/', admin.site.urls), path( "accounts/register/", RegistrationView.as_view(form_class=CustomUserForm, success_url="/",), name="django_registration_register",), path("api-auth/logout/", auth_views.LogoutView.as_view(), name="rest_logout"), path('logout/', LogoutView.as_view(next_page=settings.LOGOUT_REDIRECT_URL), name='logout'), path("accounts/", include("django.contrib.auth.urls")), path("api-auth/", include("rest_framework.urls")), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.authtoken')), path("api/v1/", include("questions.api.urls")), path("api-auth/logout/", LogoutView.as_view(), name="rest_logout"), re_path(r"^.*$", IndexTemplateView.as_view(), name="entry-point"), ] settings.py LOGOUT_URL = '/logout/' LOGOUT_REDIRECT_URL = "/" it should log out user -
(WAGTAIL) Read_only for Non-superusers in Wagtail Admin
In my Wagtail admin panel, I want to make ModelA read-only for all users who are not superusers. Currently, the 'read_only' parameter is only available for FieldPanel. Is there another way to achieve this for InlinePanel? class ModelA(models.Model): panels = [ InlinePanel("model_b", classname="collapsed") ] class ModelB(models.Model): model_a = ParentalKey(ModelA, related_name="model_b", ....) foo = models.ForeignKey(ModelC, on_delete=models.CASCADE, ...) bar = models.CharField(max_length=100, ...) -
Why does the get request not reach the view?
I take the redirect request from the hidden input get tag, but it does not reach, I sat in the debug for an hour and looked at the code, tried to fix something, but everything seems to be correct, please help! def login(request): if request.method == 'POST': form = UserLoginForm(data=request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user: auth.login(request, user) messages.success(request, f"{username}, Вы вошли в аккаунт") if request.data.get('next', None): return HttpResponseRedirect(request.data.get('next')) return HttpResponseRedirect(reverse('main:index')) else: form = UserLoginForm() <form action="{% url "users:profile" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {% if request.GET.next %} <input type="hidden" name="next" value={{ request.GET.next }}> {% endif %} <div class="row"> <div class="col-md-12 mb-3 text-center"> {% if user.image %} <img src="{{ user.image.url }}" alt="Аватар пользователя" class="img-fluid rounded-circle" style="max-width: 200px;"> {% else %} <img src="{% static "deps/images/baseavatar.jpg" %}" alt="Аватар пользователя" class="img-fluid rounded-circle" style="max-width: 150px;"> {% endif %} <input type="file" class="form-control mt-3" id="id_image" name="image" accept="image/*"> {% if form.image.errors %} <div class="alert alert-danger alert-dismissible fade show">{{ form.image.errors }}</div> {% endif %} form request <WSGIRequest: POST '/user/login/'> user <User: wicki> username 'wicki' Here is a link with a get request that should redirect to the profile after sending the post request http://127.0.0.1:8000/user/login/?next=/user/profile/ -
Why does the authenticate fails even if the email and password are correct in django?
class login(APIView): def post(self,request): email=request.data.get('email') password=request.data.get('password') user=get_user_model() print("user model",user) print(email,password) user = User.objects.get(email=email) if str(password) == str(user.password): print("authenticated") # return Response({'status':200}) user = authenticate(request,email=email,password=password) if user is not None: # User is authenticated, you can proceed with further logic return Response({'status':200,'msg': 'Login successful'}) else: return Response({'status':401,'error': 'Invalid credentials'}) I have made a custom user model with email and password and i am making post request via postman and sending data in JSON format .I have used a simple password check and the password matched as expected but the authenticate function is not giving correct results . What can be the possible cause for this behavior and how to solve it? -
Infinite Load Page Phenomenon in Django Virtual Environments
I'm using MAC, and I had a problem developing django using virtual environments. My development environment uses vscode to access the aws server, open the django virtual environment with 127.0.0.1:8000, and test the page using local(Mac) chrome. I didn't have any particular issues before, but recently, page loading has suddenly slowed down and the page loading bar is running at infinity. I changed the operating system to Windows and tried again, but there was no problem. The issue only happens on my MacBook. What should I do? I emptied my MacBook's Chrome cache and reinstalled Chrome, but nothing improved. I was wondering if it was a vscode problem, but my development environment is being developed using aws server, so it means that it is not a vscode problem to operate smoothly in Windows environment. -
Celery Beat cannot connect to Rabbitmq container
My celery beat docker container has (from what i believe) problems connecting the message broker. I have a RabbitMQ container running: .... rabbitmq: image: rabbitmq:3.11.13-management-alpine container_name: 'rabbitmq' ports: - 5672:5672 - 15672:15672 env_file: - .env volumes: - ./data:/var/lib/rabbitmq/mnesia networks: - rabbitmq_go_net .... And a Python container running a Django application with Celery (there are multiple more containers running the backend itself, celery workers, celery beat and celery flower, which all utilize the same backend files but handle different tasks): .... celery-beat: build: context: . dockerfile: ./compose/local/django/Dockerfile container_name: 'beat' image: beat command: ["./wait-for-it.sh", "0.0.0.0:1337", "--", "/start-celerybeat"] volumes: - .:/app env_file: - .env depends_on: - rabbitmq - backend restart: always .... Starting script for celery beat start.sh (executed by /start-celerybeat): #!/bin/bash set -o errexit set -o nounset rm -f './celerybeat.pid' celery -A app beat -l INFO app/celery.py: from __future__ import absolute_import import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') app = Celery('app') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks()#(lambda: settings.INSTALLED_APPS) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): .... app/settings.py INSTALLED_APPS = [ .... 'django_celery_results', 'django_celery_beat', .... ] CELERY_BROKER_URL = CONFIG.get('CELERY_BROKER_URL') CELERY_RESULT_BACKEND = CONFIG.get('CELERY_RESULT_BACKEND') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler" .env RABBITMQ_USER=user RABBITMQ_PASSWORD=password RABBITMQ_PORT=5672 RABBITMQ_HOST=rabbitmq CELERY_BROKER_URL=amqp://${RABBITMQ_USER}:${RABBITMQ_PASSWORD}@localhost:${RABBITMQ_PORT}/${RABBITMQ_HOST} CELERY_RESULT_BACKEND=amqp:// I receive the … -
Problem in creating folder and file after upload in Django
I'm creating a source code evaluater platform using React and Django. Basically an user is going to upload a source file of his choice, my frontend sends the file to backend, which is working fine, and my backend has to create a copy of the file in a specific folder structure, because the code evaluater (different application) is set to access this structure searching for new files. The folder structure is basically like this: I've a first folder name Delivereds, inside it I've many folders named by the user id, inside each of these folders I've many folders named by the submission id. To simplify this problem solving, let's deal with this ignoring user id, let's just focus on folder adress like this: "/Delivereds/Question1/code.c++". My problem is that when I try to create a folder, it doesn't work. I'm pretty much a beginner in Django, so I don't really know if I need to set some configs in the main settings file. The solutions that I found in my searches are really simple and didn't work in my case. My current code is like this: elif request.method == 'POST': if request.FILES.get('file'): file = request.FILES['file'] parent_dir = '..\Delivereds\Question1' path = os.path.join(parent_dir, … -
Better way to connect django model with django cms page/placeholder
I'm making a website, and one of the features - News. I have a model News with some fields, to have a better user experience i thought that i need some more information for every News - html snippet and for good administrating that additional content for News, i decided that i need to use django csm. So on every page i have an information from News model and in the end of that - html snippet made with cms. And there is a problem - i don't know the better way to make my wishes. Important bit: i want to make all connections with model slug. I read docs about apphooks - but maybe it's not a good approach in my case? Couse apphooks make application embedding to django cms, but i need only the piece of creation and connecting of html template made by this cms. Additionally i tried just take a Page made by cms and put it in my html, but it was something wrong there, maybe it is not possible? Maybe i can see pages only on cms urls? page = Page.objects.all()[0] # for example in views I tried to make the model placeholder, but … -
Django- admin installation error - Failed building wheel for screen
I published my project on Windows server, but domain.com/admin is not working. As a result of research on the internet, I wanted to install Django-admin, but I am getting an error. I didn't have such a problem on my computer. Creating library build\temp.win-amd64-cpython-312\Release\source\str_util.cp312-win_amd64.lib and object build\temp.win-amd64-cpython-312\Release\source\str_util.cp312-win_amd64.exp str_util.obj : error LNK2001: unresolved external symbol PyUnicode_AS_UNICODE build\lib.win-amd64-cpython-312\screen\str_util.cp312-win_amd64.pyd : fatal error LNK1120: 1 unresolved externals error: command 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.38.33130\\bin\\HostX86\\x64\\link.exe' failed with exit code 1120 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for screen Failed to build screen ERROR: Could not build wheels for screen, which is required to install pyproject.toml- based projects C:\inetpub\vhosts\domain.com.tr\httpdocs> Urls.py from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
why do i get this error "cannot unpack non-iterable bool object"
i get this error "cannot unpack non-iterable bool object" as i try to get user input from a form in django which in this case is an email def send_email(request): recepient_list=[] if request.method == "POST": email = request.POST['pwd_email'] print(email) if User.objects.filter(email == email).exists: recepient_list.append(email) send_mail("PASSWORD RESET", f"Your password resetkey is {random_no} \n Do not share this key with anyone", "eliaakjtrnq@gmail.com",recepient_list,fail_silently=False,) recepient_list.clear() -
Converting Flask or Django Web App to Desktop App for Secure Distribution
I have developed a web application using Flask/Django, and now I'm interested in converting it into a desktop application. I want users to be able to run the application directly from their desktop without needing a web browser, and I'm particularly interested in distributing it securely without exposing the source code. Can someone guide me on how to achieve this conversion? Are there any tools or frameworks available that can help in this process? I'm aiming to preserve the functionality and user experience of my web application while making it suitable for desktop usage and secure distribution. Additionally, I would appreciate any insights or best practices from those who have successfully converted web apps to desktop apps before and managed to distribute them securely without exposing the source code. Thank you in advance for your help! -
JWT refresh token is in httponly cookie, How to use DRF simple-jwt to regen the token
I have a front and backend app, front is react and backend is python Django (DRF), so my problem is I store the refresh token inside an HttpOnly cookie and send it in every request, but the DRF endpoint for refresh token (rest_framework_simplejwt.views.TokenRefreshView) will read the token itself from request.data which is the body of the Http request, is there a better way to handle this view other than rewriting a custom view? -
Django/ Office 365 : 535, b"5.7.139 Authentication unsuccessful, user is locked by your organization's security defaults policy
Running into the following error when trying to send email with Django: 535, b"5.7.139 Authentication unsuccessful, user is locked by your organization's security defaults policy. Here is my current config: #Emailing Settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_FROM = 'email@email.com' EMAIL_HOST_USER = 'email@email.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 EMAIL_USE_TLS= True This error was raised here: https://learn.microsoft.com/en-us/answers/questions/1469524/error-when-testing-smtp-for-django-website The irony of the answer provided by Microsoft is to suggest to disable the security default and also adding "not recommend". It seems the error is specific to Microsoft and comes from the use of SMTP, which MS's security doesnt like and encourage the use of OAuth. Can someone suggest an approach that worked for them? Did you disable the security defaults (for the specific email): is it risky? Did you implement OAuth and if so what steps did you take?