Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to modify the nginx.conf file during AWS Elastic Beanstalk deployment
I have developed a Django application and deployed it in an Elastic Beanstalk environment (with nginx as proxy server). The Linux platform should be the first version because if I run the command: cat /etc/os-release in the terminal of the EC2 instance managed by EB I get these information: Also I double confirm that it's Linux 1 and NOT Linux 2 by going to the EC2 console: Now, after having clarified which Linux platform I'm using in the EC2 instance, let's go ahead with the problem. When I access the EC2 instance and I go the file etc/nginx/nginx.conf, what I see is this: Now, what I want to do is to increase the timeout settings under the "server" section of the nginx.conf file. I also would like to increase the client_max_body_size somehow. I read from some documentation online the I have to create a .ebextensions folder in the root of my Django project with inside some .config files and also a buildspec.yml file in the root folder of the project. So this is where I have located my files: my_project |- .ebextensions | |- django.config | |- instances.config | |- nginx.config |- buildspec.yml |- manage.py |... Here the content of … -
Django - Checkbox onchange event only work if I click the label
On a Django template I have a checkbox named "test' from a Form Forms.py test = forms.MultipleChoiceField(required=False,widget=forms.widgets.CheckboxSelectMultiple(), label="test") When I try to make something happend with the onchange event, it's only working if I'm clicking the label of the checkbox. If I check or uncheck the box nothing happens. Template $(function(){ $('#id_test_0').on("change", function() { window.alert("change")}) }); What am I missing here ? Thanks -
convert python to exe for windowsXP sp3
i want to create django project and convert it to exe file for windowsXP sp3 and i cant pip install the versions that works for windowsXP sp3 i tried search many websites an always get this Collecting Pyinstaller Could not find a version that satisfies the requirement Pyinstaller (from versions: ) No matching distribution found for Pyinstaller -
Bootstrap 5.3 Accordion ignoring data-bs-parent
I'm trying to create an accordion where the headers are in a left-side column and when expanded the content appears in a right-side column. This works perfectly except I'm having to click on a header again to close it as per the "Always Open" example on https://getbootstrap.com/docs/5.3/components/accordion/ despite having data-bs-parent populated. <div class="row justify-content-center"> <!-- BEGIN LEFT SIDE --> <div class="col-4"> <div class="accordion accordion-flush" id="catAccordion"> {% for topic in topic_list %} <div class="accordion-item"> <h2 class="accordion-header" style="display:flex;"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse_t{{ topic.id }}" aria-expanded="false" aria-controls="collapse_t{{ topic.id }}"><h5>{{ topic.title }}</h5></button></h2> </div> {% endfor %} </div> </div> <!-- END LEFT SIDE --> <!-- BEGIN RIGHT SIDE --> <div class="col-6"> {% for topic in topic_list %} <div id="collapse_t{{ topic.id }}" class="accordion-collapse collapse" data-bs-parent="#catAccordion" aria-labelledby="head_t{{ topic.id }}"> <div class="accordion-body">{{ topic.id }} - {{ topic.title }}</div> </div> {% endfor %} </div> <!-- END RIGHT SIDE --> </div> -
django and react deployment on premise server?
I am working on an erp project which will going to be deployed on a on premise server , i want to know how i can deploy django with gunicorn and nginx and react with nginx , where i can just go to get to know how i can achieve this i have completed the necessary steps to run django with gunicorn , but having some trouble with nginx setup with gunicorn , and i have done react with nginx , i want to know how i can connect both now where i can learn complete knowledge regarding this? -
How to change a django model text-field to become a django-cms placeholder field
I have included a simple app to a django-cms 4.1.1 installation and connected it with an apphook following the tutorials. model.py: class Meeting(models.Model): # some fields above... body = models.TextField(_('body'), default='', blank=True ) placeholders = PlaceholderRelationField() @cached_property def placeholder_test(self): return get_placeholder_from_slot(self.placeholders, "body") def get_absolute_url(self): return reverse('meetings:detail', kwargs={'slug': self.slug}) def __str__(self) -> str: return f'{self.start_date:%d.%m.%Y} - {self.location}: {self.title}' I want to change the body field to become a Placeholder-Field. In django-cms < 4 this was done with body = PlaceholderField('body') but if I understand right this is obsolete in Version 4. admin.py from cms.admin.placeholderadmin import FrontendEditableAdminMixin from django.contrib import admin from .models import Meeting class MeetingAdmin(FrontendEditableAdminMixin, admin.ModelAdmin): pass admin.site.register(Meeting, MeetingAdmin) meeting_detail.html {% block content %} {% render_placeholder meeting.placeholder_test %} {% endblock content %} But no placeholder appears in the frontend to be filled with plugins. How is this possible? -
How to save django db data in the middle of a playwright test?
I'm having trouble figuring out how to call the "sync" create_user(). Error message: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. However, when I use sync_to_async, it cannot be awaited because this is not an async function... from functools import wraps from django.test import TestCase from playwright.sync_api import sync_playwright def playwright_test(func): @wraps(func) def wrapper(self, *args, **kwargs): with sync_playwright() as self.p: self.browser = self.p.chromium.launch() self.page = self.browser.new_page() try: result = func(self, *args, **kwargs) finally: self.browser.close() return result return wrapper class TC(TestCase): @playwright_test def test_login(self): self.page.goto(self.host) self.page.fill('input[type="email"]', 'my@email.com') self.page.fill('input[type="password"]', 'TestLogin') self.page.click('text="Login"') # expect "Incorrect Credentials" message (no user created yet) assert "Incorrect Credentials" in self.page.content() User = get_user_model() User.objects.create_user('my@email.com', password='TestLogin') # Login again, this time successfully self.page.fill('input[type="email"]', 'my@email.com') self.page.fill('input[type="password"]', 'TestLogin') self.page.click('text="Login"') assert "Login successful. Welcome back!" in self.page.content() If you have a suggestion, please let me know, my hair starts to fall out. 🙏 -
LDAP Authentication with Paperless NGX in Docker
I recently installed Paperless NGX in Docker and set up user authentication via LDAP. The server is reachable, and authentication starts correctly, but the connection keeps dropping. I can't figure out why. Does anyone have any idea what I could check? Here are my logs: [2024/06/19 13:25:23.609239, 3] ../../lib/ldb-samba/ldb_wrap.c:332(ldb_wrap_connect) ldb_wrap open of secrets.ldb [2024/06/19 13:25:23.613473, 3] ../../source4/samba/service_stream.c:67(stream_terminate_connection) stream_terminate_connection: Terminating connection - 'ldapsrv_accept_tls_loop: tstream_tls_accept_recv() - 32:Broken pipe' [2024/06/19 13:25:23.617901, 3] ../../lib/ldb-samba/ldb_wrap.c:332(ldb_wrap_connect) ldb_wrap open of secrets.ldb [2024/06/19 13:25:23.715563, 3] ../../source4/auth/ntlm/auth.c:204(auth_check_password_send) auth_check_password_send: Checking password for unmapped user [firma.DE]\[matthias]@[SAMBA] auth_check_password_send: user is: [firma.DE]\[matthias]@[SAMBA] [2024/06/19 13:25:23.727758, 3] ../../auth/auth_log.c:647(log_authentication_event_human_readable) Auth: [LDAP,simple bind/TLS] user [firma.DE]\[matthias@samba.firma.de] at [Wed, 19 Jun 2024 13:25:23.727738 CEST] with [Plaintext] status [NT_STATUS_OK] workstation [SAMBA] remote host [ipv4:10.100.100.17:43693] became [firma.DE]\[matthias] [S-1-5-21-1856347220-1719576316-2154358202-1529]. local host [ipv4:192.168.100.22:636] {"timestamp": "2024-06-19T13:25:23.727829+0200", "type": "Authentication", "Authentication": {"version": {"major": 1, "minor": 2}, "eventId": 4624, "logonId": "0", "logonType": 8, "status": "NT_STATUS_OK", "localAddress": "ipv4:192.168.100.22:636", "remoteAddress": "ipv4:10.100.100.17:43693", "serviceDescription": "LDAP", "authDescription": "simple bind/TLS", "clientDomain": "firma.DE", "clientAccount": "matthias@samba.firma.de", "workstation": "SAMBA", "becameAccount": "matthias", "becameDomain": "firma.DE", "becameSid": "S-1-5-21-1036045820-1750975616-2752359902-1319", "mappedAccount": "matthias", "mappedDomain": "firma.DE", "netlogonComputer": null, "netlogonTrustAccount": null, "netlogonNegotiateFlags": "0x00000000", "netlogonSecureChannelType": 0, "netlogonTrustAccountSid": null, "passwordType": "Plaintext", "duration": 14075}} [2024/06/19 13:25:23.741307, 3] ../../lib/ldb-samba/ldb_wrap.c:332(ldb_wrap_connect) ldb_wrap open of privilege.ldb [2024/06/19 13:25:23.756797, 3] ../../source4/auth/ntlm/auth.c:204(auth_check_password_send) auth_check_password_send: Checking password for unmapped user [firma.DE]\[Administrator]@[SAMBA] auth_check_password_send: user is: [firma.DE]\[Administrator]@[SAMBA] … -
Snowflake custom OAuth not working with invalid_client error
First it was working, and it showed scope not available error, but now it is showing this error, I created the integration using the snowflake_oauth_docs and this is my query: CREATE SECURITY INTEGRATION my_app_oauth TYPE = OAUTH ENABLED = TRUE OAUTH_CLIENT = CUSTOM OAUTH_CLIENT_TYPE = 'CONFIDENTIAL' OAUTH_REDIRECT_URI = 'https://b54rmx30-8000.inc1.devtunnels.ms/callback/snowflake/' OAUTH_ISSUE_REFRESH_TOKENS = TRUE OAUTH_REFRESH_TOKEN_VALIDITY = 7776000; and then I did this DESC SECURITY INTEGRATION my_app_oauth; and this SELECT SYSTEM$SHOW_OAUTH_CLIENT_SECRETS('DATAOPSLY_OAUTH'); and I collected the client_id and client_secret and I'm using django for my oauth, so this is my callback and login view: def snowflake_login(request): # Snowflake OAuth configuration snowflake_client_id = 'my_client_id' snowflake_client_secret = 'my_secret' authorization_url = 'https://<my_account>.snowflakecomputing.com/oauth/authorize' token_url = 'https://<my_account>.snowflakecomputing.com/oauth/token' redirect_uri = 'https://b54rmx30-8000.inc1.devtunnels.ms/callback/snowflake/' # Update with your Django callback URL scopes = 'openid email profile' # Adjust scopes as needed # Redirect user to Snowflake OAuth authorization URL auth_params = { 'response_type': 'code', 'client_id': snowflake_client_id, 'redirect_uri': redirect_uri, 'scope': scopes, } redirect_url = f"{authorization_url}?{'&'.join([f'{k}={v}' for k, v in auth_params.items()])}" return redirect(redirect_url) def snowflake_callback(request): # Handle callback from Snowflake OAuth snowflake_client_id = 'my_client_id' snowflake_client_secret = 'my_secret' token_url = 'https://<my_account>.snowflakecomputing.com/oauth/token' redirect_uri = 'https://b54rmx30-8000.inc1.devtunnels.ms/callback/snowflake/' # Update with your Django callback URL # Get authorization code from callback request code = request.GET.get('code') # Exchange authorization code for … -
Django asynchronous channels blocking websocket
I have an issue with my django channels which I couldn't resolve. Basically, I have a turn-based combat system where messages are received from the client, to signal e.g. the enemy's turn. This happens via a consumer: async def receive(self, text_data): data = json.loads(text_data) message_type = data.get('type') if message_type == 'enemy_combat_turn': await self.handle_end_of_turn(data) async def handle_end_of_turn(self, data): npc_name = data.get('npc_name') debuff = data.get('debuff') combat_message = data.get('combat_message') print(f"Handling end of combat turn for player. Initiating enemy turn next.") # Check for active traps first response = await trigger_trap(game_id=self.game_id, npc_name=npc_name) # Then, trigger enemy combat action response = await sync_to_async(enemy_combat_action) (self.game_id, npc_name, debuff, combat_message) async def send_unified_message(self, event): # Send message to WebSocket await self.send(text_data=json.dumps(event)) print(f"Sending message for event {event}") The consumer awaits several asynchronous functions, e.g. the result of handle_end_of_turn, which is composed of two other asynchronous functions, trigger_trap and enemy_combat_action. Now, in trigger_trap and in enemy_combat_action, we dispatch messages back to the client e.g.: # Send trap message async_to_sync(channel_layer.group_send)( f'character_{game_id}', { 'type': 'send_unified_message', 'message_type': 'new_assistant_messages', 'messages': trap_message, } ) Since the functions are defined asynchronously the expectation is that the messages are sent immediately but instead they seem to be queued up and sent all at the same time once … -
How to dynamically generate buttons and dropdowns from the database to perfom some action ? (django)
I have data in different bootstrap accordion, in some accordion i want to have buttons and dropdowns, the accordion is divided into two columns. # Create your models here. class CaseStudy_List(models.Model): CaseStudy_id = models.IntegerField(primary_key=True) title = models.CharField(max_length=255) def __str__(self): return self.title class CaseStudy_Parts(models.Model): #accordians case_study = models.ForeignKey(CaseStudy_List, on_delete=models.CASCADE) CaseStudy_part_id = models.AutoField(primary_key=True) CaseStudy_order = models.IntegerField(default="") CaseStudy_title_accordian = models.CharField(max_length=255) def __str__(self): return self.CaseStudy_title_accordian class CaseStudy_Content(models.Model): #column 1 - text area case_study_part = models.ForeignKey(CaseStudy_Parts, on_delete=models.CASCADE, null=True) content_title = models.CharField(max_length=255, default="") content_text = models.TextField(blank=True) content_link = models.TextField(blank=True) def __str__(self): return self.content_title class CaseStudy_Media(models.Model): #column 2 - Media Area case_study_part = models.ForeignKey(CaseStudy_Parts, on_delete=models.CASCADE, null=True) # case_study = models.ForeignKey(CaseStudy_List, on_delete=models.CASCADE) content_img = models.ImageField(upload_to='casestudy/images', default="") This is my model <div class="page-layout"> <div class="accordion" id="accordionPanelsStayOpenExample"> {% for part_data in parts_data %} <div class="accordion-item"> <h6 class="accordion-header" id="heading{{ part_data.part.CaseStudy_part_id }}"> <button class="accordion-button {% if not forloop.first %}collapsed{% endif %}" type="button" data-bs-toggle="collapse" data-bs-target="#collapse{{ part_data.part.CaseStudy_part_id }}" aria-expanded="{% if forloop.first %}true{% else %}false{% endif %}" aria-controls="collapse{{ part_data.part.CaseStudy_part_id }}"> {{ part_data.part.CaseStudy_title_accordian }} </button> </h6> <!-- <div id="panelsStayOpen-{{ part_data.part.CaseStudy_part_id }}" class="accordion-collapse collapse show"> --> <div id="collapse{{ part_data.part.CaseStudy_part_id }}" class="accordion-collapse collapse {% if forloop.first %}show{% endif %}" aria-labelledby="heading{{ part_data.part.CaseStudy_part_id }}"> <div class="accordion-body"> <div class="container-area"> <div class="col-content"> <div class='introduction-content'> <!-- <h3>CASESTUDY ID - {{casestudy_object.CaseStudy_id}} </h3><br> <h3>TITLE - … -
problem in a django app to use rabbitmqp as broker ansd celery for running simpel task
Hello i am tring to learn how to set up a django app for suing celery iam running rabbitmq on docker desktop on a windows machine with this command : docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq then i run celery with this command and monitoring it with flower : celery -A a_shop worker -l Info celery -A a_shop flower in main init file of django app i have this : from .celery import app as celery_app __all__ = ('celery_app',) and for celery setting in setting.py file i have this settings : CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//' CELERY_RESULT_BACKEND = 'rpc://' CELERY_TASK_ACKS_LATE = True CELERY_WORKER_PREFETCH_MULTIPLIER = 1 CELERY_TASK_SOFT_TIME_LIMIT = 600 # 10 minutes CELERY_TASK_TIME_LIMIT = 1200 CELERY_IMPORTS = ('orders.task',) CELERY_TASK_DEFAULT_QUEUE = 'celery' i created a file name celery.py in main app with this codes : from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'a_shop.settings') app = Celery('a_shop') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {self.request!r}') i create a simpel task to test : import logging from celery import shared_task from .models import Order logger = logging.getLogger(__name__) @shared_task def order_created(order_id): logger.info(f"Task order_created started with order_id: {order_id}") try: order = Order.objects.get(id=order_id) logger.info(f"Processing … -
How to change type of existing model objects?
I had a model Topic with date_added field type set to TimeField class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.TimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): """Return a string representation of the model""" return self.text But later I realized that I need to change the type to DateTimeField. I changed it in the model definition and migrated class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): """Return a string representation of the model""" return self.text But the type of existing Topic objects are still TimeField which I figured out by running these commands in the Django shell: >>> field = Topic._meta.get_field('date_added') >>> print(isinstance(field, DateTimeField)) False >>> type(field) <class 'django.db.models.fields.TimeField'> I tried searching it up online but didn't find anything. Chat GPT advised to manually change migration files which seems like a bad idea to me. How to achieve what I want? -
Multiple docker services with their own databases for Django seem to be cross-connecting
We have multiple services, and when run locally each fires up their own docker container for postgres. Fine. There's also an "admin services" repo with a docker compose file for things like pgAdmin that will connect to any running services for ease of use. We have external port mappings assigned for each service so we can run different services at the same time locally. The problem is that for the admin services repo to work we've added a "common" network to the services that it needs to reach. It's fine for pgAdmin there as it connects to "db_service1", "db_service2" etc, which is the container_name value. However, django DATABASES["default"]["HOST"] setting does not seem to like having "db_service1" as a value, and instead requires the actual service ID from the compose file, which is "db" on all the services. And since docker doesn't use external IP addresses, but the internal ones, and the internal ones are all 5432 (postgres default), when I start up eg. service2, then service1 starts erroring with relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se... The only explanation I have for this is that it is now suddenly trying to connect to the service2 database, … -
Add song to Playlist not working Django music App
I'm making a music streaming website (it's my first project on Django). I'm making the view to add a song to a specific playlist, but it is not working (I always get the error "failed to add song to playlist"), and the songs are not added to playlists. How can I fix it? HTML: {% if my_playlists %} <p style="">Add This Song To Your Playlist</p> {% for playlist in my_playlists %} <a class="left-panel-btn" id="D_{{playlist.playlist_id}}" onclick="sendPostRequestPlaylistSong(this)">{{playlist.playlist_name}}</a><br> {% endfor %} {% else %} <p style="">You don't have any Playlist.</p> <a class="create-p" onclick="$('#divId').css({display: 'none'}); document.getElementById('modal-wrapper-playlist').style.display='block'"><i class="fas fa-plus"></i> Create Playlist</a> {% endif %} javascript function: function sendPostRequestPlaylistSong(el) { // alert("Song ID: "+song_id_for_playlist+" | Playlist ID: "+el.id); var data = song_id_for_playlist + "|" + el.id; $.ajax({ "url": "{% url 'music:addSongToPlaylist' %}", "type": "POST", "data": { 'data': data, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, success: function(response) { alert("Song added to your playlist"); location.reload();}, error: function(xhr, status, error) { alert("Failed to add song to playlist.");} }); var div = $("#divId"); div.css({ transition: "0.3s", display: "none" }); } views.py: def addSongToPlaylist(request): user = request.user if request.method == "POST" and user.is_authenticated: data = request.POST['data'] if data: song_id, playlist_id = data.split("|") song_id = song_id[0][2:] playlist_id = playlist_id[1][2:] currPlaylist = Playlist.objects.filter(playlist_id=playlist_id, user=request.user).first() … -
Django+Heroku testing: how to connect to a test database? ('permission denied to create database')
I have been doing my first deployment with django (ever), and I am using Heroku CLI. I get this message when trying to run tests: "Got an error creating the test database: permission denied to create database" I tried first just by running tests. Then I tried to specify the current database as a test option (giving same parameters). I also tried to specify Sqlite as a test database. I am expecting to have a temporal database for testing, or to use the current database for it. I have found an option that creates a custom connection to a postgress database made for only testing purposes. It seems too complicated to be a common problem. I also saw something in heroku pages called dynos database (a temporal one for testing in Ruby), but could not find it in the add ons on the page, nor when trying to do it from the command line (it says its only for command line deployment). Implementing something like what pasted bellow would be ideal as it makes a database temporaly only for testing (found in Ruby section): https://devcenter.heroku.com/articles/heroku-ci-parallel-test-runs { "addons": [ "heroku-postgresql:in-dyno", "heroku-redis:in-dyno" ] } There is an option in NOD.js that looks … -
Complex Django query related to Prefetch, Subquery and OuterRef
I have this queryset below. queryset = Contract.objects.select_related( "company", "user", "user__profile", "user__profile__address", "user__profile__address__living_country", "compensation__currency", "job", "benefit", "payment_details", "working_country", "work_permit", ).prefetch_related( Prefetch( "partner_fee__partner__partner_countries", queryset=CountryPartner.objects.annotate(contract_id=OuterRef("id")).all() ) ) I have to annotate that contract_id to filter that CountryPartner. But it is not possible to use OuterRef there. It always needs Subquery of django.models. Ideally, I want to do this sql query in Django ORM: select cc.id, cc.email, cc.residency_type, dc.country_id from core_contract cc inner join public.core_partnerfee cp on cc.id = cp.contract_id inner join public.core_partnerprofile c on cp.partner_id = c.id inner join public.dicts_countrypartner dc on c.id = dc.partner_profile_id where dc.country_id=cc.working_country_id and dc.residency_type=cc.residency_type and dc.partner_profile_id=c.id order by cc.id; If I use Subquery inside CountryPartner filter it is going to take CountryPartnerId, not Contract ID. See below pls. Prefetch( "partner_fee__partner__partner_countries", queryset=CountryPartner.objects.annotate(contract_id=SubQuery(Contract.objects.filter(id=OuterRef("id")))) ) So, how to be? Django ORM is not able to do this? -
Django reatApi Request user is Anonymous when using jwt cookies
I'm building a new django restApi app within my users app I'm using jwt authentication currently I'm able to register, login , store cookies and send get request after logging in with a valid credentials. My issue is when I'm getting an authinticated get request I'm not able to see request's user it shown as AnonymousUser. I'm attachinf my login post request and an endpoint restApi get request code. from django.shortcuts import render from rest_framework.exceptions import AuthenticationFailed # Create your views here. from rest_framework.views import APIView from .models import User from .serializers import UserSerializer from rest_framework.response import Response import jwt,datetime class RegisterView(APIView): def post(self, request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) class LoginView(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User not found') if not user.check_password(password): raise AuthenticationFailed('Incorrect password') payload={'id':user.id,'exp':datetime.datetime.utcnow()+datetime.timedelta(minutes=60), 'iat':datetime.datetime.utcnow()} token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.set_cookie(key='jwt',value=token,httponly=True) response.data={'jwt':token} return response class UserView(APIView): def get(self, request): token = request.COOKIES.get('jwt') if token is None: raise AuthenticationFailed('Unauthenticatedddd') try: payload=jwt.decode(token,'secret',algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated') user = User.objects.filter(id=payload['id']).first() serializer = UserSerializer(user) return Response(serializer.data) class UsserLogoutView(APIView): def post(self, request): response = Response() response.delete_cookie('jwt') response.data = {'message': 'You have been logged out'} return … -
Can't get route to redirect to login page if user isn't authenticated in React/Django app
I’m using React for my frontend and Django for the backend, both are new to me and I've been spending a ton of time on this issue without solving it, so I'm really hoping someone might know the answer. When I visit my site at http://localhost:4000/ without being logged in, I see a black screen with the text "Loading…” (refer to protected_route code below), instead of being redirected to the login page. This happens when I navigate to any protected routes while not logged in. Currently my only routes that are not protected are the login and register pages, which if I manually go to those they work correctly. After I login, the JWT tokens are correctly stored to the httpOnly cookies, but I do see the “Loading…” page until I manually refresh the page, then I see my protected routes. I was thinking maybe the authentication check is firing too quickly and the state isn't ready yet and it gets stuck on the "Loading..." screen? But I'm unsure how to fix that if it's the case... I'll post the relevant code below, but I'll also share the github repo here. Here’s the browser/server consoles when going to a page … -
What is a better way to push updates to a .exe file on Client Machine? (Exe created by pyinstaller)
Context For a bit of a context I am a self taught developer who is currently working as a freelancer on Fiverr. I work using the Django and the React Framework. I develop different kinds of Automation Softwares for my clients, most of Initially, I used to deliver source code to my clients and they used to install Python and than the libraries to get the program working on their side and as you all can guess this method was very inefficient. So, I learned a trick to convert my django code into .exe format using Pyinstaller. So, now all the clients have to do is to doouble click the exe file which launches the web app in their browser. Problem But now I am facing another problem. As, I am now dealing with some repeating clients who are often contacting me to add features. But now the problem is that every time I update their web apps to add new features they all have to manually install the new version and than shift all the data manually to the newer version which is a big problem ofcourse. So, some of them are asking me to do something so that … -
Django 5.x: directory /workspace/staticfiles does not exist
I am trying to deploy an application in DO App platform and everything worked as expected. As a more stable media and static files handling I am trying to implement DO spaces to store static and media files. Here is how my settings look like for that: MEDIA_ROOT = BASE_DIR / 'media' AWS_S3_CUSTOM_DOMAIN = os.environ.get('AWS_S3_CUSTOM_DOMAIN', 'your_access_key_id') AWS_S3_FILE_OVERWRITE = False AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID', 'your_access_key_id') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY', 'your_secret_access_key') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME', 'bucket_name') AWS_REGION = os.environ.get('AWS_REGION', 'region') AWS_S3_ENDPOINT_URL = AWS_S3_CUSTOM_DOMAIN STORAGES = { "default": { "BACKEND": "storages.backends.s3.S3Storage", "OPTIONS": { "bucket_name": AWS_STORAGE_BUCKET_NAME, "access_key": AWS_ACCESS_KEY_ID, "secret_key": AWS_SECRET_ACCESS_KEY, "endpoint_url": AWS_S3_ENDPOINT_URL, "region_name": AWS_REGION, "default_acl": 'public-read', "querystring_auth": False, }, }, "staticfiles": { "BACKEND": "storages.backends.s3.S3StaticStorage", "OPTIONS": { "bucket_name": AWS_STORAGE_BUCKET_NAME, "access_key": AWS_ACCESS_KEY_ID, "secret_key": AWS_SECRET_ACCESS_KEY, "endpoint_url": AWS_S3_ENDPOINT_URL, "region_name": AWS_REGION, }, }, } STATIC_URL = f'https://{AWS_STORAGE_BUCKET_NAME}.{AWS_REGION}.digitaloceanspaces.com/static/' MEDIA_URL = f'https://{AWS_STORAGE_BUCKET_NAME}.{AWS_REGION}.digitaloceanspaces.com/media/' STATIC_ROOT = BASE_DIR / 'static' But When I deploy it I keep getting: directory /workspace/staticfiles does not exist How do I solve it? Thanks I went to digital oceans deployment guides and also searched through stackoverflow and reddit but no luck. -
Python Django Annotations over multiple relationships
I have a question On Django annotations. Here is my model: class Asset(models.Model): security = models.ForeignKey(Security, on_delete=models.CASCADE, blank=False) class Batch(models.Model): fk_asset = models.ForeignKey(Asset, on_delete=models.CASCADE, blank=False) class BatchPosition(models.Model): fk_batch = models.ForeignKey(Batch, on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=14, decimal_places=2, blank=False) In my view I would like to annotate the total Sum of Batchposition->quantity to the Asset I tried things like Asset.objects.annotate(Sum("batch")).annotate(Sum("batchposition__quantity")) ...but can't get it to work. What am I doing wrong here? Is it finally possible to achieve this? -
How to fetch different data in a single template ? (django)
Scenario of my project - There are different casestudies, each casestudies has different parts which will appear in accordions, now i have designed the database and its generating dynamic accordions with respect to the number of my data entries. Each part (accordion) has two column , first ccolumn for text data second column is for media data. Each part has different format of data, how to fetch the data into this single template ? MODELS # Create your models here. class CaseStudy_List(models.Model): CaseStudy_id = models.IntegerField(primary_key=True) title = models.CharField(max_length=255) def __str__(self): return self.title class CaseStudy_Parts(models.Model): #accordians case_study = models.ForeignKey(CaseStudy_List, on_delete=models.CASCADE) CaseStudy_part_id = models.AutoField(primary_key=True) CaseStudy_order = models.IntegerField(default="") CaseStudy_title_accordian = models.CharField(max_length=255) def __str__(self): return self.CaseStudy_title_accordian class CaseStudy_Content(models.Model): #column 1 - text area case_study_part = models.ForeignKey(CaseStudy_Parts, on_delete=models.CASCADE, null=True) content_title = models.CharField(max_length=255, default="") content_text = models.TextField(blank=True) content_link = models.TextField(blank=True) def __str__(self): return self.content_title class CaseStudy_Media(models.Model): #column 2 - Media Area case_study_part = models.ForeignKey(CaseStudy_Parts, on_delete=models.CASCADE, null=True) # case_study = models.ForeignKey(CaseStudy_List, on_delete=models.CASCADE) content_img = models.ImageField(upload_to='casestudy/images', default="") class CaseStudy_Buttons(models.Model): content = models.ForeignKey(CaseStudy_Content, on_delete=models.CASCADE) button_id = models.CharField(max_length=255) button_label = models.CharField(max_length=255) VIEWS def casestudy(request, CaseStudy_id ): casestudy_object = get_object_or_404(CaseStudy_List, CaseStudy_id = CaseStudy_id) #for list casestudy_parts_obj = CaseStudy_Parts.objects.filter(case_study=casestudy_object).order_by('CaseStudy_order').distinct() #for accordians parts_data = [] #storing in a singlist to avoid duplicacy for … -
Django errors NoReverseMatch at /comment/4
The error occurred When I tested a wrong email format.When I enter the correct email format, it runs normally and the data is stored in the background. The error details as follows: NoReverseMatch at /comment/4 Reverse for 'comment' with arguments '('',)' not found. 1 pattern(s) tried: ['comment/(?P<post_pk>[0-9]+)$'] There are my codes: models.py from django.db import models from django.utils import timezone # Create your models here. class Comment(models.Model): name = models.CharField('名字', max_length=50) email = models.EmailField('邮箱') url = models.URLField('网址', blank=True) text = models.TextField('内容') created_time = models.DateTimeField('创建时间', default=timezone.now) post = models.ForeignKey('blog.Post', verbose_name='comments', on_delete=models.CASCADE) class Meta: verbose_name = '评论' verbose_name_plural = verbose_name def __str__(self): return '{}: {}'.format(self.name, self.text[:20]) views.py from blog.models import Post from django.shortcuts import get_object_or_404, redirect, render from django.views.decorators.http import require_POST from .forms import CommentForm @require_POST def comment(request, post_pk): post = get_object_or_404(Post, pk=post_pk) form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect(post) context = { 'post': post, 'form': form, } return render(request, 'comments/preview.html', context=context) urls.py from django.urls import path from . import views app_name = 'comments' urlpatterns = [ path('comment/<int:post_pk>', views.comment, name='comment'), ] _form.html <form action="{% url 'comments:comment' post.pk %}" method="post" class="comment-form"> {% csrf_token %} <div class="row"> <div class="col-md-4"> <label for="{{ form.name.id_for_label }}">{{ form.name.label }}:</label> {{ form.name … -
1 out of many calls to overridden django `Model.save()` generates a pylint `unexpected-keyword-arg` error - how do I satisfy it?
I implemented and have been using this model (super)class I created for years, and it is completely stable on an active site. I just made a small minor tweak to some completely unrelated portion of its code, and checked my work (on my machine) with the latest superlinter. Our CI tests on github currently use an old superlinter and it has never complained, so I was surprised to see a linting error on code I haven't touched in years. My model class has an overridden save() method, which adds a few extra arguments that it pops off kwargs before calling super().save(). I have a number of calls to save inside the class, and the linter is fine with thos extra arguments everywhere else, except in 1 spot (an override of from_db): @classmethod def from_db(cls, *args, **kwargs): # Instantiate the model object rec = super().from_db(*args, **kwargs) # If autoupdates are not enabled (i.e. we're not in "lazy" mode) if not cls.get_coordinator().are_lazy_updates_enabled(): return rec # Get the field names queryset_fields = set(args[1]) # field_names # Intersect the queryset fields with the maintained fields common_fields = set(cls.get_my_update_fields()).intersection(queryset_fields) # Look for maintained field values that are None lazy_update_fields = [fld for fld in common_fields …