Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change div text from select dataset
I want the selected dataset to appear at the beginning and then the selected ones to appear in the div.I don't know Java. I try someting like this. not work :( <script> $(document).ready(function() { const div = document.getElementById("nitelik3") div.on('change', function() { from_text.html(div.dataset.fiyat); }) }); </script> {{ key|safe }}-{% translate 'Price' %} €<div id='from'></div> <select id='nitelik3' name="nitelik3" class="form-control mb-3"> {% for vl in val %} <option value={{ vl.0 }} data-fiyat='{{ vl.3 }}' style="font-size:15px">{{ vl.1 }} - €{{ vl.3 }}</option> {% endfor %} </select> -
How do I stop CKEditor from stripping out Adsense Ads <ins> tag in my Django admin backend?
I have implemented a standard CKEditor configuration on my Django site's admin backend. The default CKEDITOR_CONFIGS in settings.py is: CKEDITOR_CONFIGS = { 'default': { 'allowedContent': True, }, } In the article model I have: description = RichTextField() The problem I am having is that when I try to insert a Google Adsense Ad unit code in the CKEditor source and save it like so: The CKEditor is stripping the ins tag from the Adsense ad code after saving as seen here: How do I prevent the CKEditor from stripping the tag from the Adsense code? I have tried implementing the solution suggested here by adding the two lines to the CKEditor's config.js file but that doesn't have any effect: How to push a protectedSource in django-ckeditor? /** * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. * For licensing, see https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; config.protectedSource.push( /<ins[\s|\S]+?<\/ins>/g ); config.protectedSource.push( /<ins class=\"adsbygoogle\"\>.*?<\/ins\>/g ); }; This leads to another question: how do I make sure that the CKEditor's config.js file is being applied as it seems its currently not … -
Problem with query optimization in Django admin
I came across the fact that when I try to open the object creation window FriendlyMatch, it takes a lot of time. About 2 minutes. Through the django debug toolbar I found out that there were 4300 SQL queries. Here are my models: class Player(models.Model): """Модель игрока""" user = models.ForeignKey( User, related_name="player", on_delete=models.CASCADE, verbose_name="Игрок" ) created = models.DateTimeField(auto_now_add=True) team = models.ForeignKey( Team, related_name="team_player", null=True, on_delete=models.SET_NULL, verbose_name="Команда", ) class Meta: """Мета класс модели Игрока""" verbose_name = "Игрок" verbose_name_plural = "Игроки" def __str__(self): return f"Игрок {self.user.username}" class FriendlyMatch(models.Model): """Модель Дружеского матча""" date_start = models.DateTimeField( verbose_name="Дата и время начала", null=True, blank=True ) date_end = models.DateTimeField( verbose_name="Дата и время окончания", null=True, blank=True ) duration_macth = models.SmallIntegerField( verbose_name="Длительность дружеского матча", default=3, null=True, blank=True ) creator = models.ForeignKey( User, related_name="creator_friendly_match", null=True, on_delete=models.SET_NULL, verbose_name="Создатель", ) player_1 = models.ForeignKey( Player, related_name="friendly_match_player1", null=True, on_delete=models.SET_NULL, verbose_name="Игрок 1", ) player_2 = models.ForeignKey( Player, related_name="friendly_match_player2", null=True, blank=True, on_delete=models.SET_NULL, verbose_name="Игрок 2", ) first_game_winner = models.ForeignKey( Player, related_name="first_game_winner_friendly_match", null=True, blank=True, on_delete=models.SET_NULL, verbose_name="Победитель первой игры", ) second_game_winner = models.ForeignKey( Player, related_name="second_game_winner_friendly_match", null=True, blank=True, on_delete=models.SET_NULL, verbose_name="Победитель второй игры", ) third_game_winner = models.ForeignKey( Player, related_name="third_game_winner_friendly_match", null=True, blank=True, on_delete=models.SET_NULL, verbose_name="Победитель третьей игры", ) fourth_game_winner = models.ForeignKey( Player, related_name="fourth_game_winner_friendly_match", null=True, blank=True, on_delete=models.SET_NULL, verbose_name="Победитель четвертой игры", ) fifth_game_winner = models.ForeignKey( … -
Handling File Uploads in Django: How Can I Improve Security and User Experience?
`I'm currently working on a Django web application, and I need to implement a file upload feature. While the basic functionality is clear, I want to ensure that the file upload process is both secure and provides a good user experience. What are the best practices for handling file uploads securely in Django? How can I prevent common security vulnerabilities related to file uploads? Are there any Django packages or libraries that enhance the user experience when uploading files? I've done some research, but I'd appreciate insights from the community to ensure I'm on the right track. Any code examples or recommended resources would be greatly appreciated. Thanks! ` Handling file uploads securely in Django is crucial, and there are several best practices you can follow to achieve this. Here's a comprehensive guide to help you improve both security and user experience: Use Django's Built-in File Handling: Django provides a FileField for handling file uploads in models. This field automatically handles file storage, and you can specify the storage backend, such as FileSystemStorage or S3Boto3Storage for Amazon S3. Example model: from django.db import models class MyModel(models.Model): upload = models.FileField(upload_to='uploads/') -
DJANGO, update button is not working in frontend but in admin panel, i can change the status. Help me fix it guys im going crazy
When i click the update button, it should change the remarks/status of the submitted file in submission, however i dont know why it is working in my frontend but it works in my django admin panel. Please help me huhu, and also i dont want to use AJAX cause it's so complicated to use html {% extends "base/room_home.html" %} {% block content %} <div class="container d-flex align-items-center justify-content-center" style="min-height: 100vh;"> <div class="text-center"> <h1>{{ room_bills.title }}</h1> <p>Due: {{ room_bills.due }}</p> <div class="col-3"> <h3>Paid Members: </h3> <ul> {% for submission in submissions %} <li> <a href="proof/{{ submission.user.id }}" target="_blank">{{ submission.user.username }}</a> {% if submission %} <form method="POST" class="update-form" data-room-id="{{ room_bills.room.id }}" data-bills-slug="{{ room_bills.slug }}" data-submission-id="{{ submission.id }}"> {% csrf_token %} <select name="status"> <option value="P" {% if submission.status == 'P' %}selected{% endif %}>Pending</option> <option value="A" {% if submission.status == 'A' %}selected{% endif %}>Accepted</option> <option value="R" {% if submission.status == 'R' %}selected{% endif %}>Rejected</option> </select> <button type="submit" class="btn btn-primary">Update</button> </form> {% endif %} </li> {% endfor %} </ul> </div> <div class="col-3"> <h3>Did not pay members: </h3> <ul> {% for user in did_not_submit %} <li>{{ user.username }}</li> {% endfor %} </ul> </div> </div> </div> <script> function getCookie(name) { const value = `; ${document.cookie}`; const parts … -
Django Compare passwords with Bcrypt
I have a problem with bcrypt... How I compare the String saved in the db with the String from the user input this: >>> import bcrypt >>> salt = bcrypt.gensalt() >>> hashed = bcrypt.hashpw('secret', salt) >>> hashed.find(salt) 0 >>> hashed == bcrypt.hashpw('secret', hashed) True >>> and this doesn't work at least I save my passwords raw in the db -_- Somebody know how to do it? -
How to find duplicate FK entries in Django using query
I have a GeneralLedger that is comprised of JournalLineItems and AccountsPayableLineItems. When either a JournalLineItem or AccountsPayableLineItem gets stored, I save it in the GeneralLedger as a referece. I have an issue to where, while setting everything up I guess, I added 10 duplicate FK entries for either a JournalLineItem or AccountsPayableLineItem. I am trying to determine which they are, but I am having issues figureing out the query to use. For example: print(GeneralLedger.objects.count()) # 2416448 print(JournalLineItem.objects.count()) # 2414902 print(AccountsPayableLineItem.objects.count()) # 1536 Overall the important structure of my model would be: class GeneralLedger(models.Model): journal_line_item = models.ForeignKey('accounting.JournalLineItem', null=True, on_delete=models.CASCADE, related_name='general_ledger', db_index=True) accounts_payable_line_item = models.ForeignKey('accounting.AccountsPayableLineItem', null=True, on_delete=models.CASCADE, related_name='general_ledger', db_index=True) How do I write a query to see which journal_line_item or accounts_payable_line_item has duplicate entries in the GeneralLedger? -
Can I use `JWTStatelessUserAuthentication` instead of `JWTAuthentication` in my Django project, even without multiple applications?
I'm currently working on a Django project, and I'm exploring the use of authentication mechanisms provided by Simple-JWT. In the documentation, I noticed the option of using JWTStatelessUserAuthentication for single sign-on (SSO) between separate Django apps that share the same token secret key. My project doesn't involve multiple applications, but I'm intrigued by the potential benefits of JWTStatelessUserAuthentication, especially in avoiding database queries for user info in each API call, which seems to be a characteristic of JWTAuthentication. I'd appreciate any insights, experiences, or recommendations regarding the use of these authentication methods in a Django project. Thanks! Specific Questions: Is it advisable to use JWTStatelessUserAuthentication in a project without multiple applications? Are there any specific considerations or limitations associated with using JWTStatelessUserAuthentication in a project context like mine? -
Limiting choices in django dynamically (call-back function?)
I am relatively new to Django and this is my first question on Stackoverflow. So pleas bear with me if not ideally formulated. My Problem: I have a Model Animal with two fields that are ForeignKey based (species,breed) . Only those breeds should be shown that are available as per the entered/given species. This reduction of choice options shall take place when a) a new Animal record is created, b) the specie value is changed and the breed options are looked up newly and c) when the breed for a given animal shall be changed. This shall happen both in the Admin UI as well as in the apps UI via Django Forms Originally I thought the the limit_choices_to attribute in conjunction with a Q could do the trick but it did not, neither I was able to got it working callable defined. By reading various posts I have found a way to interfere for method c) which does not work for a) and b) Here are my data: Models.py class Specie(models.Model): specie = models.CharField(primary_key=True, max_length=1, ) specieText = models.CharField( max_length=24,) class Meta: ordering = ['specieText'] def __str__(self): return self.specieText class Breed(models.Model): specie = models.ForeignKey('Specie', on_delete=models.CASCADE,) breed = models.CharField(max_length=2,) breedText … -
Django models troubles in admin
I was trying to build database connections for an online school project. It turned out that I have 2 entities Student and Course, they have a many-to-many relationship. At the same time, if I delete a student from a course, the course will not be deleted and also, when I delete a course, the students will not be deleted. I had an idea to make a related model through which I can assign courses to students and vice versa, but after creating the connection, when I try to disconnect a student from it, I get an error IntegrityError at /admin/student/studentcourse/1/change/ NOT NULL constraint failed: student_studentcourse.student_id Request Method:POSTRequest URL:http://127.0.0.1:8000/admin/student/studentcourse/1/change/Django Version:4.2.7Exception Type:IntegrityErrorException Value:NOT NULL constraint failed: student_studentcourse.student_idException Location:C:\Users\amane\PycharmProjects\StudyHome\.venv\Lib\site-packages\django\db\backends\sqlite3\base.py, line 328, in executeRaised during:django.contrib.admin.options.change_viewPython Executable:C:\Users\amane\PycharmProjects\StudyHome\.venv\Scripts\python.exePython Version:3.11.4Python Path:['C:\\Users\\amane\\PycharmProjects\\StudyHome', 'C:\\Users\\amane\\PycharmProjects\\StudyHome', 'C:\\Program Files\\JetBrains\\PyCharm ' '2022.2\\plugins\\python\\helpers\\pycharm_display', 'C:\\Users\\amane\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip', 'C:\\Users\\amane\\AppData\\Local\\Programs\\Python\\Python311\\DLLs', 'C:\\Users\\amane\\AppData\\Local\\Programs\\Python\\Python311\\Lib', 'C:\\Users\\amane\\AppData\\Local\\Programs\\Python\\Python311', 'C:\\Users\\amane\\PycharmProjects\\StudyHome\\.venv', 'C:\\Users\\amane\\PycharmProjects\\StudyHome\\.venv\\Lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2022.2\\plugins\\python\\helpers\\pycharm_matplotlib_backend']Server time:Mon, 27 Nov 2023 13:10:21 +0000 My project code student/models.py from django.db import models class Student(models.Model): GENDER_CHOICES = [ ('М', 'Мужской'), ('Ж', 'Женский'), ] student_id = models.AutoField(primary_key=True) name = models.CharField(max_length=30, blank=False) surname = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) age = models.IntegerField() gender = models.CharField(max_length=1, choices=GENDER_CHOICES) parents_phone = models.CharField(max_length=100) parents_email = models.EmailField(max_length=100, blank=False) phone = models.CharField(max_length=20) email = models.EmailField(max_length=100, blank=False) description … -
Django channels login connection already closed
I'm trying to login user after registering where my app is using django channels in combination with Strawberry. class RegisterUserMutation(DjangoCreateMutation): def create_user(self, data, password): user = MyUserModel(**data) user.set_password(password) user.save() return user def login_user(self, info, username, password): request = get_request(info) user = auth.authenticate(request, username=username, password=password) print(f"Step 3.1 - authenticate user {user}") if user is None: raise IncorrectUsernamePasswordError() scope = request.consumer.scope print("Step 3.2 - fetched scope") async_to_sync(channels_auth.login)(scope, user) print("Step 3.3 - channels login") # According to channels docs you must save the session scope["session"].save() print("Step 3.4 - scope updated with session") # FIXME: session doesnt actually seem logged in. return user @transaction.atomic def create(self, data: dict[str, Any], *, info: Info): password = data.pop("password") username = data.get('username') validate_password(password) with DjangoOptimizerExtension.disabled(): data = self.set_default_values(data) print("Step 1: Set default values") user = self.create_user(data, password) print("Step 2: Created user") self.login_user(info, username, password) print("Step 3: Logged in user") return user When I try that code, the user "step 3" is never completed with error django.db.utils.InterfaceError: connection already closed. It seems that: The user is correctly created (Step 2) The user authenticated against django correctly (Step 3.1) The scope is fetched (Step 3.2) But the channels_auth.login is never completed: async_to_sync(channels_auth.login)(scope, user) Is where it seems to fail. Any … -
Iterating through form-data with nested keys in Django Rest Framework
I'm working on a project using Django Rest Framework, where I need to create a company by sending relevant documents through form-data. When I print the data received, it looks like this: { "company[company_owner][email]": "rohansheryabraham@gmail.com", "company[company_owner][phone]": "098765439", "company[company_owner][first_name]": "Mike", "company[company_owner][last_name]": "Tyson", "company[company_name]": "Testing", "company[company_email]": "testing@mail.com", "company[company_mobile_phone]": "980765432", "company[company_landline]": "78765421", "company[company_country]": "India", "company[email_otp]": "783143", "company[mobile_otp]": "256310", "company_detail[0][detail_id]": "110", "company_details[0][documents]": [some list of file], } Now unlike JSON I cannot dynamically access documents in form-data like print(company_detail[0]['documents'])can anyone suggest a good way to iterate this? for now, I am just printing data @api_view(['POST']) @permission_classes([AllowAny]) @parser_classes([FormParser, MultiPartParser]) def test(request): print(request.data) #logic to create company return Response() -
Django celery cron job is not calling back the tasks
I'm trying to run celery cron job after every 30 second but its not working. Tried every possible solution, mentioned the beat command in my docker-compose.yaml command field under celery_worker but its not working, don't know what i'm missing. Logs does not show anything unusual. apps/ app1/ tasks.py app2/ project/ __init__.py settings.py celery.py ... manage.py docker-compose.yaml celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") app = Celery("celery_app") app.config_from_object("django.conf:settings", namespace="CELERY") app.conf.beat_schedule = { 'send-event-reminders': { 'task': 'apps.app1.tasks.send_event_reminders', 'schedule': 30, # run after every 30 seconds }, } app.autodiscover_tasks() tasks.py (below method has no errors if i run it manually, but not getting hit from celery @shared_task def send_event_reminders(): logger.info("send_event_reminders task called") print("send msg") ...some code here return this is my celery_worker in my docker-compose.yaml celery_worker: ... build: dockerfile: ./docker/Dockerfile.dev command: celery -A etell_django_app worker -B -l info volumes: - .:/app - static_files:/app/static env_file: .env depends_on: - redis - etell_db -
TypeError at / Insertdetails() missing 1 required positional argument: 'request' - Django
I am getting the following error in a Django project TypeError at / Insertdetails() missing 1 required positional argument: 'request' Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.2.7 Exception Type: TypeError Exception Value: Insertdetails() missing 1 required positional argument: 'request' Exception Location: D:\Works\django\projects\proj1\proj1\views.py, line 9, in Insertdetails Raised during: proj1.views.Insertdetails Python Executable: C:\Users\ankilla\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.6 I am totally new to Django, I need to insert data into mysql from HTML page. I was following a old video https://www.youtube.com/watch?v=d9fx8qrJyCY Views.py from django.shortcuts import render from proj1.models import Insertrecord from django.contrib import messages def Insertdetails(request): if request.method == "POST": saverecord=Insertdetails() saverecord.ID=request.POST.get('ID') saverecord.Name=request.POST.get('Name') saverecord.Email=request.POST.get('Email') saverecord.Address=request.POST.get('Address') saverecord.save() messages.success(request,'Saved') return render(request,'index.html') else: return render(request,'index.html') models.py from django.db import models class Insertrecord(models.Model): ID=models.IntegerField() Name=models.CharField(max_length=100) Email=models.CharField(max_length=100) Address=models.CharField(max_length=100) class Meta: db_table="employee" Index.html <form method="post"> Emp Id : <input type="number" name="ID"> Employee Name : <input type="text" name="Name"> Email : <input type="text" name="Email"> Address : <input type="text" name="Address"> <input type="submit" value="Submit </form> Urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ #path('admin/', admin.site.urls), path('',views.Insertdetails) ] Please help Followed the same as video to insert data into mysql -
Django JSONField filter on complex JSON document with list of object
I work with Django 3.2 and MariaDB. I have an Product Model with an product_settings field (typed as JSONField ). With a queryset I want to retrieve all products with a type of deposit equals to building. Example of truncated product_settings value : { "resources": [ { "resource_config": { "linked_to": { "params": { "deposit": { "type": "building" } } } } } ] } I'm trying with this queryset but it does not return any results : Product.objects.filter(product_settings__resources__resource_config__linked_to__params__deposit__type="oauth2") Do you have any idea ? I've already read this question but mine is quite more complex and need another solution. -
Many-to-many communication of a model in Django with itself
How can I create a customer table in the database using Django models so that the desired customers can be linked together, with the following conditions? The client may not be related to any other client. The customer may have a relationship with one or more other customers. When for customer 1 and customer 2 the connection with customer 4 was registered, and in reading the connections of customer 1 the connection with customer 4 was visible. Conversely, by reading the communications of customer 4, you can find out about customer 1 and customer 2. I have attached a schematic example of what I mean. Schema class CustomUser(AbstractBaseUser, PermissionsMixin): nid = models.CharField(max_length=10, unique=True, db_index=True, primary_key=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) email = models.EmailField(max_length=255) USERNAME_FIELD = "nid" REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.nid friends = models.ManyToManyField("self") -
Django, How to access request data in include template
In my Django project, I have some templates that includes in base template using {% include %} tag. How do I access request data in this included template? How do I access context variables in this included template? I was expecting that request data is accessible in any template. -
How to retry failed tasks in celery chunks or celery starmap
I would like to know how to configure these tasks correctly so that the failed tasks can be retried. One thing I have noted is if one of the tasks in the chunk fails, the whole chunk (I assume executed by celery.starmap) fails @celery_app.task def get_item_asteroids_callback(parent_item_id): pass @celery_app.task( ignore_result=False, autoretry_for=(requests.exceptions.ReadTimeout, TimeoutError, urllib3.exceptions.ReadTimeoutError, InterfaceError), retry_kwargs={'max_retries': 3}, retry_backoff=True ) def get_item_asteroid(work_id): """ Does some stuff that can raise some exceptions. """ raise requests.exceptions.ReadTimeout('Test Exception') @celery_app.task(ignore_result=False) def get_item_asteroids(parent_item_id): item_ids = [1,2,3.......] item_ids = [(item_id,) for item_id in item_ids] chunk_size = min(len(item_ids), 128) tasks = [get_item_asteroid.chunks(item_ids, chunk_size).group()] chord(tasks)(get_item_asteroids_callback.si(parent_item_id)) None of the failed tasks is retried (The Retried count is 0) -
Please tell me how to implement views.py of audio recording app
I want to create a recording app using Django. As a beginner, I'm not sure what kind of processing to write in views.py though I read many information about pyaudio, librosa etc... The desired functions are: Record the user's voice with the smartphone's microphone. put some effect on it.(I think I can handle this myself, so I'm not expecting code example) Save the recorded audio in the database. I would like to see an example code for implementing function1,3. As I said, I've read many information about pyaudio, librosa etc... But have no idea because I could not find how to combine the code to template.(like start recording button). Thank you in advance for your guidance. -
How to pass a sub-directory of a website to uwsgi in nginx?
Suppose I have a website named www.test.com. Now I've written a django server, and I want to access this server via www.test.com/api. So I write the nginx configuration file like this: server { listen 80; server_name www.test.com; root ROOT_FOR_MAIN_SERVER; access_log /var/log/nginx/access.www.test.com; error_log /var/log/nginx/error.www.test.com; location / { index index index.php index.html; try_files $uri $uri/ =404; } location /api { include uwsgi_params; uwsgi_pass unix:ROOT_FOR_DJANGO_SERVER/uwsgi/uwsgi.sock; } location ~ \.php(.*)$ { root ROOT_FOR_MAIN_SERVER; fastcgi_pass unix:/run/php/php8.1-fpm.sock; fastcgi_index index.php; fastcgi_split_path_info ^(.+\.php)(.*)$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; include fastcgi_params; } location ~ /\.ht { deny all; } } But when I access www.topfyf.cn/api, the uri will still contains /api. Can I tell nginx or uwsgi that I want to delete the /api prefix, i.e., if I access /api/abc, the request becomes /abc when I comes to the django server? -
Static files not loading in pythonanywhere
I am going to run my project on the pythonanywhere site and I did all the work, but the static files are not loaded. I'm developing a website with Django. My static files are located in the static_root directory and the static file path is also set correctly in my Django settings. However, when I open the website in the browser, the static files are not loading. For example, when I try to access an image, I get the following error: 404 Not Found: /static/images/my_image.jpg I've checked the following: The static_root directory is accessible. The web server user has read access to the static_root directory. The Django application URL patterns point to the static files correctly. I've cleared the web server cache. I've used the Django debug toolbar and found no problems with the static file paths. Can anyone help me troubleshoot this issue? python version :3.9 django version :4.2.6 Thanks, Elyas -
how can i send my string statement to views.py file in django from another python file
class Decisions: @staticmethod def rpa(OlcumSonuclariLOG: list, dfLimit: pd.Series, test_kodu: int, urun_kodu: str, sonuc1=None, sonuc2=None, sonuc3=None, sonuc4=None,startDate = None,endDate = None,retest1 = None,retest2 = None,retest3 = None) -> None: rpaLog = OlcumSonuclariLOG[1:3] # 1. paletin 2. testi ve 2 paletin 1. testi seçiliyor statistics, sigma3 = Calculaters.spc_calculations(test_kodu, urun_kodu,startDate,endDate) OK_NOK_RPA = [] for i in range(len(rpaLog)): for j, rows in rpaLog[i].iterrows(): if (rows["Test Adı"] == "SS G'@100") and (rows["Deger"] <= LSL_SSG100): output = f"SS G'@100 için değer {rows['Deger']} alt spec {LSL_SSG100} altındadır." how can i pass the output variable to my views.py file ? -
How to login to Django views from React?
Currently I am facing an issue where I can sign in from react accurately but my django session is not updated based on whether I login or logout from react. What I am expecting is that when I sign in through react, my current user view in django will be changed to demonstrate the current user I signed in as from react but at this moment no changes can be seen. Using jwt tokens from react, I am able to access the current user view and get the correct user but this change can only be observed in react and the server side isn't adjusted to have the correct user logged in. The following image demonstrates my problem: problem Please provide any help that you can as I have been stuck on this problem for roughly a week now and have been unable to find a solution. This is how I handle sign ins in react. //Signs In the user through Django const handleSignIn = async ()=> { try { const response = await axios.post('http://127.0.0.1:8000/api/login/', { username, password }); //Store the access token const accessToken = response.data.access; alert("Sign In Success!\nAccess Token: " + accessToken) localStorage.setItem('accessToken', accessToken); //Store the refresh token … -
Store foreign key as eccrypted and fetch be decrypt
I am implementing a user management system using django ORM. It is said to store the Password in different table "user_password" and encrypt the the foreign key "id" of "user_password" table in "User" table. I implemented it by defining no relationship between the two tables. Is their any way to store and fetch the foreign relation object by encryting and decrypting the foreign key field while preserving the foreign key relation in database? -
Getting this Error PermissionError: [Errno 13] Permission denied: '/app/manage.py' in Docker
I am encountering a PermissionError when trying to run the docker compose run command for creating a Django project within a Docker container. The error message is as follows :- docker compose run --rm app sh -c "django-admin startproject myproject ." [+] Building 0.0s (0/0) docker:desktop-linux [+] Building 0.0s (0/0) docker:desktop-linux Traceback (most recent call last): File "/py/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) File "/py/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/py/lib/python3.9/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/py/lib/python3.9/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/py/lib/python3.9/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) File "/py/lib/python3.9/site-packages/django/core/management/commands/startproject.py", line 21, in handle super().handle("project", project_name, target, **options) File "/py/lib/python3.9/site-packages/django/core/management/templates.py", line 205, in handle with open(new_path, "w", encoding="utf-8") as new_file: PermissionError: [Errno 13] Permission denied: '/app/manage.py' . . . And this is my Dockerfile :- FROM python:3.9-slim ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt COPY ./app /app WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /requirements.txt && \ adduser --disabled-password --no-create-home app ENV PATH="/py/bin:$PATH" USER app . . and this is my docker-compose.yml file :- services: app: build: context: . image: my-django-image ports: - 8000:8000 volumes: - ./app:/app command: > i tried …