Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django payment, user balance [closed]
for example, I have a simple website where there is a list of posts, they are of two types: paid and free, paid ones can be purchased by authorized users and then they can read it, free ones can be read by anyone, after registration, all authorized users will have their own balance, there will be a payment system, and each authorized user can deposit at least 5$, after payment, so that the amount he deposited will be credited to his account, how can I implement this and what technologies do I need to use and what should I pay attention to? -
Initializing a Bokeh AjaxDataSource: source callback not receiving parameters on initialization
I have a Bokeh vbar plot in a figure which gets its data from an AjaxDataSource via a JavaScript callback. It works OK after resizing, but initializing the plot fails with a MultiValueDictKeyError, apparently because my callback function is being called without any of the necessary GET parameters being passed to it. (The error is in the line Amin = float(request.GET["Amin"] of the function ajax_data). How do I configure the plot so that it is initialized correctly on first loading? Here is my (anonymised) code: def plot(request): partnerID = int(request.GET['partnerID']) Amin, Amax, Bmax = 0, 50, 0.01 bokeh_html = get_bokeh_html(Amin, Amax, Bmax) c = {"bokeh_html": bokeh_html} c["bokeh_js"] = (f'<script src="https://cdn.bokeh.org/bokeh/' f'release/bokeh-{settings.BOKEH_VERSION}.min.js"' f' type="text/javascript"></script>') return render(request, 'myapp/plot.html', c) def get_bokeh_html(Amin, Amax, Bmax): fig = bp.figure( frame_width=1000, frame_height=800, title="PLOT", tools="box_zoom,wheel_zoom,reset", x_axis_label="Abcissa", y_axis_label="Data axis", ) fig.toolbar.logo = None fig.x_range = Range1d(Amin, Amax) fig.y_range = Range1d(0, Bmax) source = AjaxDataSource( method="GET", data_url=reverse("myapp:ajax_data"), name="ajax_plot_data_source", polling_interval=None, ) r = fig.vbar( x="x", top="top", width=f"width", source=source, ) callback = CustomJS( args=dict(xr=fig.x_range), code=""" $.ajax({ url: 'ajax-data', data: { 'Amin': xr.start, 'Amax': xr.end, 'partnerID': 2 }, success: function (data) { var ds = Bokeh.documents[0].get_model_by_name('ajax_plot_data_source'); ds.data = data; } }); """, ) fig.x_range.js_on_change("start", callback) fig.legend.click_policy = "hide" bokeh_script, bokeh_div = components(fig) … -
Remote Video Not Displaying in Django WebSockets Video Call Implementation
I'm trying to build a video call feature for two users (local and remote peers) using Django, WebSockets, HTML, and JavaScript. The local video is working fine, but the remote video is not showing up even though its exists. I'm getting the following error: Error: DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: Called in wrong state: stable The error occurs in this snippet of code: function handleAnswer(answer) { console.log('Handling answer:', answer); if (peerConnection.signalingState !== 'have-local-offer') { console.warn('Unexpected signaling state:', peerConnection.signalingState, 'Answer ignored.'); return; } peerConnection.setRemoteDescription(new RTCSessionDescription(answer)).then(() => { console.log('Remote description set for answer:', answer); }).catch(error => { console.error('Error setting remote description for answer:', error); }); } HTML: <div class="video-root" id="vid-area"> <div class="username-wrapper"><span class="user-name">+11ß</span></div> <video class="video-player" id="consultant" autoplay playsinline></video> <!-- Here where the remote comes in --> <div id="remoteVideoFrame" class="smallFrame" style="display : none;"> <video class="video-player" id="client" autoplay playsinline></video> </div> <div class="controls-wrapper"> <div class="icon-wrapper"> <i class='bx bx-microphone control-icon' id="mic-btn"></i> </div> <div class="icon-wrapper"> <i class='bx bx-camera-home control-icon' id="camera-btn"></i> </div> <div class="icon-wrapper"> <i class='bx bx-screenshot control-icon' id="screen-share"></i> </div> <div class="icon-wrapper"> <i class='bx bx-phone-off control-icon' id="leave-btn"></i> </div> </div> </div> JavaScript: document.addEventListener('DOMContentLoaded', function () { var loc = window.location; var wsStart = loc.protocol === 'https:' ? 'wss://' : 'ws://'; var … -
Django + VueJS multiple user type
I'm having a problem in Vue.js with handling multiple users. Before transitioning to this integration, my previous authentication used mixins to handle privileges for each user. Now, I want to use Vue as the frontend, but I'm unsure how to integrate it. I'm using the following user roles: #models.py class User(AbstractUser): is_secretary = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) contact_number = models.CharField(max_length=20, blank=True, null=True) REQUIRED_FIELDS = [] def user_type(self): if self.is_superuser: return "Superuser" elif self.is_secretary: return "Secretary" elif self.is_staff: return "Staff" else: return "User" def __str__(self): return f"{self.first_name} {self.last_name} ({self.user_type()})" I'm using serializers to manage user data. How should I handle this in Vue.js? Any advice or examples would be appreciated. Depending on each user's role, I want to redirect them to their specific dashboard. -
Best Server Configuration For Django
I am new at programing and I want to deploy my first project with django. I have a VDS server that i want to configure for multiple django projects which i will deploy first one. but I am not sure about which linux os or server to prefer. Thanks for answers. I installed cloudlinux, cpanel and nginx but im having issue with delivering static and media files so i want to configure server once to make it easier to deploy new apps in future. -
Why is everything grouped under "api" in Swagger UI with no division between task and subtask?
I'm working on documenting an API using Swagger UI. However, I've noticed that all endpoints are grouped under a single "api" section. There are no separate divisions for different resources such as "task" and "subtask". This makes the API documentation harder to navigate and understand. settings.py REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'), path('api/docs/', SpectacularSwaggerView.as_view(url_name='api-schema'), name='api-docs'), path('api/users/', include('user.urls')), path('api/tasks/', include('task.urls')), path('api/subtasks/', include('subtask.urls')), ] task\urls.py router = DefaultRouter() router.register('', views.TaskViewSet) app_name = 'task' urlpatterns = [ path('', include(router.urls)), ] -
How to apply ordering based on another model field data in DRF?
I am trying to develop an API to filter JobApplication model data, and facing problem to ordering the response data for a custom field. Here is my JobApplication model. class JobApplication(models.Model): job_post = models.ForeignKey(JobPost, on_delete=models.CASCADE) job_seeker = models.ForeignKey(AppUser, on_delete=models.CASCADE) applied_date = models.DateField(auto_now_add=True) experience = models.PositiveSmallIntegerField(null=True, blank=True) And filter models is: class JobApplicationFilter(django_filters.FilterSet): gender = django_filters.CharFilter(field_name='job_seeker__personaldetails__gender') age = django_filters.NumberFilter(field_name='job_seeker__personaldetails__age', lookup_expr='lte') experience = django_filters.NumberFilter(field_name='experience', lookup_expr='lte') class Meta: model = JobApplication fields = ['gender', 'age', 'experience'] And the views is: class JobApplicantFilterListView(generics.ListAPIView): serializer_class = JobApplicationSerializer filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_class = JobApplicationFilter pagination_class = CustomPageNumberPagination ordering_fields = ['age','experience'] Now I want to add a filed as full_name in JobApplicationFilter class, Where full_name field will generate from first_name and last_name fields from PersonaDetails model. And finally use this full_name field to ordering the response data. -
Django send mail works in localhost but not on server
I recently started to learn Django and I wrote a code to send an email in contact us page and it works fine in my localhost but when I uploaded it onto server it gave this error: SMTPServerDisconnected at /contact Connection unexpectedly closed this is my settings.py code: EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my@gmail.com' EMAIL_HOST_PASSWORD = 'app passwords' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' and this is my views.py send_mail('title', 'message', userEmail, [settings.EMAIL_HOST_USER], fail_silently=False,) I talked to the support group of my host server to check the ports but they said it was okay so I don't know if I'm missing something or not. -
Blocked a frame with origin "http://127.0.0.1:8000" from accessing a cross-origin frame. ((Django cors headers, S3 cors policy))
https://sparta-games.net/games/list/47/ <-- !! Sound Too Loud !! I'm trying to lower the sound of iframe or the whole page. The exact error message: 47/:644 Uncaught DOMException: Failed to read a named property 'AudioContext' from 'Window': Blocked a frame with origin "http://127.0.0.1:8000" from accessing a cross-origin frame. at iframe_element.onload (http://127.0.0.1:8000/games/list/47/:644:58) Iframe is a Unity WebGL game which is coming from S3 bucket. I'm using Django, EC2, mobaXterm, S3, nginx, gunicorn, RDS. (Windows11) My settings Django settings.py: INSTALLED_APPS = [ ..., "corsheaders", ..., ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ..., 'django.middleware.common.CommonMiddleware', ..., ] X_FRAME_OPTIONS = 'SAMEORIGIN' CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:8000", ] S3 CORS policy: { "CORSRules": [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "PUT", "HEAD" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [ "x-amz-server-side-encryption", "x-amz-request-id", "x-amz-id-2" ], "MaxAgeSeconds": 3000 } ] } versions: Django==4.2 django-cors-headers==4.3.1 Sending header through views.py like below didn't help either. def my_view(request): response = JsonResponse({'message': 'Hello, world!'}) response['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8000' response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS' response['Access-Control-Allow-Headers'] = 'Content-Type' return response I can't find the exact case like this. Recursively asked ChatGPT to solve it. django-cors-headers, s3 policy, directly sending headers, cors whitelist,... didn't get the problem. In fact, this also happen when user to modify and submit any … -
0 static files copied to 'C:\Users\Reynald\Desktop\Test\cdo_portal\staticfiles', 2365 unmodified
Hello everyone might someone here know how to fix this i just trying to run the py manage.py collectstatic but when i run the sytsem all of the design was a mess and when i check the collecstatic "0 static files copied to 'C:\Users\Reynald\Desktop\Test\cdo_portal\staticfiles', 2365 unmodified." not sure of that I already tried another way to fix this but still not working -
%20 in my url to static javascript file in django application
I have base template core/layout.html and it contains scripts block in it: <script type="text/javascript" src="{% static "core/js/tinymce/tinymce.min.js" %}"></script> <script src = "{% static "core/js/flowbite.min.js" %}"></script> <!-- <script src = "{% static "core/js/index.js" %}"></script> --> {% block scripts %} {% endblock scripts %} So the problem is in url to javascript file (index.js). If I include it in layout.html (base template) everything works perfect, but when i put it in my child template: {% block scripts %} <script src="{% static 'core/js/index.js' %}"></script> {% endblock scripts %} it throws an error: GET 127.0.0.1:8000/static/%20core/js/index.js net::ERR_ABORTED 404 (Not Found) I even have tried to hard code it, still the same problem. -
Mark a view function as being exempt from the CSRF view protection
(function) def csrf_exempt(view_func: _F@csrf_exempt) -> _F@csrf_exempt Mark a view function as being exempt from the CSRF view protection. Make sure disabling CSRF protection is safe here. sonarlint(python:S4502) How to fix this issue on sonarcloud?. (function) def csrf_exempt(view_func: _F@csrf_exempt) -> _F@csrf_exempt Mark a view function as being exempt from the CSRF view protection. Make sure disabling CSRF protection is safe here. sonarlint(python:S4502) -
why does my SQLlite database in django does not show the same records when I run it on a different machine; (running the server on Local Host)
So I am trying to build a basic Task managing app. The main issue is with the database, me and my friend have the exact same code we pulled from the rep, when he and I run the server on local host and try using the website, like creating account and adding tasks, but when we open the admin panel I can only see my tasks and the accounts in the User Database that were created on my machine, and my friend can see the accounts and tasks created on his machine, though our databases are same, they are not displaying the same records, this wasn't an issue before, if he would add a task and create account I can see it in my admin panel thru my machine and vice versa, I don't exactly know what happened. its like the databases are not synced are being emptied everytime you run the website on a different machine. this is giving us trouble, because we are working on an invite feature when you can enter a users email in a specific task then that user would start seeing the task on his machine, since the databases are not in sync the … -
Django model field "null together or not at all" constraint
I need a way to create either a validator or a constraint at model level to evaluate two or more fields to be able to be null/blank only if all of them are null/blank at the same time. For example, in the next model: from django.db import models class Example(models.Model): A = models.CharField(max_length=16,blank=True) B = models.DateField(null=True,blank=True) C = models.FileField(uploadto='/',null=True) if I try to create a new Example with either B or C values empty it should raise a ValidationError; but if both of them are empty it should be OK. -
SynchronousOnlyOperation Error in Django Class Based Views
I am making a Django app, but I can't use async views, I installed uvicorn and asgi, but I get this error: SynchronousOnlyOperation at /chatbot/chat/ You cannot call this from an async context - use a thread or sync_to_async. @method_decorator(login_required(login_url=settings.LOGIN_URL), name='dispatch') @method_decorator(never_cache, name='dispatch') class ChatView(View): async def get(self, request, *args, **kwargs): """ This method return our chatbot view """ response = await sync_to_async(render)(request, 'chatbot/chat.html') return response -
cv2.error: OpenCV(4.10.0) D:\a\opencv-python\opencv-python\opencv\modules\objdetect\src\qrcode.cpp:32: error: (-215:Assertion failed) !img.empty()
i write a bot to decode qr-codes from user's message and send im data back. now i have an error cv2.error: OpenCV(4.10.0) D:\a\opencv-python\opencv-python\opencv\modules\objdetect\src\qrcode.cpp:32: error: (-215:Assertion failed) !img.empty() in function 'cv::checkQRInputImage' code: @decode_router.message(lambda message: True) async def decode(message: Message): await main.bot.send_message(message.chat.id, "Decoding...") fl = main.bot.download_file(message.photo, f"qrcode{message.from_user.id}.png") fl = FSInputFile(f"qrcode{message.from_user.id}.png", f"qrcode{message.from_user.id}.png") img = cv2.imread(f"qrcode{message.from_user.id}.png") detector = cv2.QRCodeDetector() data, vebb, f = detector.detectAndDecode(img) await message.reply(data) what that error means and what should i do to fix it? -
Google authentication with django-allauth fails due to "OAuth2Error: Invalid id_token"
I am trying to set-up Google authentication for my DRF + Next.js web app. I've been following this guide. I am using django-allauth 0.61.1 and dj-rest-auth 6.0.0. If I try to pass both access and it tokens: ... const SIGN_IN_HANDLERS = { credentials: async (user, account, profile, email, credentials) => { return true; }, google: async (user, account, profile, email, credentials) => { try { const response = await axios({ method: "post", url: process.env.NEXTAUTH_BACKEND_URL + "auth/google/", data: { access_token: account["access_token"], id_token: account["id_token"], }, }); account["meta"] = response.data; return true; } catch (error) { console.error(error); return false; } }, }; const SIGN_IN_PROVIDERS = Object.keys(SIGN_IN_HANDLERS); export const authOptions = { pages: { signIn: "/login", }, secret: process.env.AUTH_SECRET, session: { strategy: "jwt", maxAge: BACKEND_REFRESH_TOKEN_LIFETIME, }, providers: [ CredentialsProvider({ name: "Credentials", credentials: {}, async authorize(credentials, req) { console.log("here"); try { const response = await axios({ url: process.env.NEXTAUTH_BACKEND_URL + "auth/login/", method: "post", data: credentials, }); const data = response.data; if (data) return data; } catch (error) { console.error(error); } return null; }, }), GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, authorization: { params: { prompt: "consent", access_type: "offline", response_type: "code", }, }, }), ], callbacks: { async signIn({ user, account, profile, email, credentials }) { if (!SIGN_IN_PROVIDERS.includes(account.provider)) … -
How to add permissions in django admin panel for user?
I have a django app. And I added in the admin panel of django the following permission: Accounts | account | Can view account And in the code of admin.py of the accounts app. I added this: from django.contrib.auth import get_user_model from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from .models import Account User = get_user_model() user = User.objects.get(email='n@n.nl') content_type = ContentType.objects.get_for_model(Account) permission = Permission.objects.get( codename='view_account', content_type=content_type) user.user_permissions.add(permission) class AccountAdmin(UserAdmin): list_display = ( "email", "first_name", "last_name", "username", "last_login", "date_joined", "is_active", ) list_display_links = ("email", "first_name", "last_name") filter_horizontal = ( 'groups', 'user_permissions', ) readonly_fields = ("last_login", "date_joined") ordering = ("-date_joined",) list_filter = () User = get_user_model() user = User.objects.get(email='n@n.nl') content_type = ContentType.objects.get_for_model(Account) permission = Permission.objects.get( codename='view_account', content_type=content_type) user.user_permissions.add(permission) admin.site.register(Account, AccountAdmin) And when I start the django app. I don't get any errors. But when I login with the account with the user permission. I still see the message: You don’t have permission to view or edit anything. And the permissions: Is active Is staff are selected Question: how to add permissions for users? -
how to force a maximum map extent for geonode docker?
I’m running geonode docker, how do I need to modify the .env file to force a maximum map extent (e.g. Italy)? This is my local installation procedure using the default .env git clone -b 4.0.2 https://github.com/GeoNode/geonode.git cd .\geonode\ docker compose build docker compose up -d I modify the .env and run docker compose down and docker compose up -d (https://docs.geonode.org/en/master/install/basic/index.html#customize-env-to-match-your-needs) ADMIN_PASSWORD=admin4 # works and takes effect DEFAULT_MAP_ZOOM=10 # works and takes effect DEFAULT_MAP_CENTER_X=50 # does not work (if this does not work how can max force extent work) DEFAULT_MAP_CENTER=50 # does not work What are variable names and how to use them to force a maximum map extent ? -
Django random can't connect to mysql
In django I'm getting can't connect to mysql randomly it works fine and just gives it to me and on refresh it works fine, completely random, I can't even reproduce it. any ideas? compose file: networks: my_network: driver: bridge ipam: config: - subnet: 172.16.238.0/24 gateway: 172.16.238.1 services: web: extra_hosts: - "host.docker.internal:host-gateway" networks: my_network: ipv4_address: 172.16.238.6 restart: always depends_on: - db env_file: - ./backend/.env image: project-api build: context: . dockerfile: backend/Dockerfile.dev command: bash -c "python manage.py migrate && python manage.py collectstatic --noinput && gunicorn project.wsgi -b 0.0.0.0:9001" volumes: - ./backend:/code - ./backend/logs:/logs db: image: mysql:8.0 command: mysqld --default-authentication-plugin=mysql_native_password restart: always volumes: - ./backend/data:/var/lib/mysql - ./db/init.sql:/docker-entrypoint-initdb.d/init.sql networks: my_network: ipv4_address: 172.16.238.9 environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: dev_db MYSQL_USER: dev_db_user MYSQL_PASSWORD: root -
io.UnsupportedOperation: fileno
in django i want to receive a file from a form and then pass it to a function, then do some OCR with it. but i get the io.UnsupportedOperation: fileno error. here is part of views.py: @login_required(login_url='/profile/login/') def repairman_profile(request): user = request.user repairman = RepairmanUser.objects.get(user=user) if request.method == 'POST': plate_form = PlateForm(request.POST, request.FILES) if plate_form.is_valid(): plate = recognize_plate(request.FILES["plate_image"]) return HttpResponse(plate) else: plate_form = PlateForm() context = { "repairman": repairman, 'plate_form': plate_form, } return render(request, 'repairman/profile.html', context=context) here is the recognize_plate() function: def recognize_plate(plate): results = {} # load models model = Model.load("hezarai/crnn-fa-64x256-license-plate-recognition") license_plate_detector = YOLO('repairman/plate_recognition/best.pt') # load image # cap = cv2.imread(plate) frame = cv2.imread(plate) the line frame = cv2.imread(plate) is where the error happens. here is django log: Internal Server Error: /profile/ Traceback (most recent call last): File "D:\Tamirauto\WebApp\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "D:\Tamirauto\WebApp\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Tamirauto\WebApp\venv\Lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapper_view return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Tamirauto\WebApp\tamirauto\repairman\views.py", line 94, in repairman_profile plate = recognize_plate(request.FILES["plate_image"]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Tamirauto\WebApp\tamirauto\repairman\plate_recognition\main.py", line 18, in recognize_plate frame = cv2.imread(plate) ^^^^^^^^^^^^^^^^^ File "D:\Tamirauto\WebApp\venv\Lib\site-packages\ultralytics\utils\patches.py", line 26, in imread return cv2.imdecode(np.fromfile(filename, np.uint8), flags) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ io.UnsupportedOperation: fileno -
Did I write data migration for data type change in a correct way?
Say, I have a model TestModel: class TestModel(models.Model): field1 = models.CharField(max_length=255) field2 = models.IntegerField() def __str__(self): return f"{self.field1}" But I need to change the type of field2 to Text now. In order not to lose the data in TestModel model, I need to write a data migration. So I create a new model NewTestModel: class NewTestModel(models.Model): field1 = models.CharField(max_length=255) field2 = models.TextField() def __str__(self): return f"{self.field1}" Run python manage.py makemigrations command In 0006_newtestmodel.py migration file I add copy_data function and run it using migrations.RunPython(copy_data) from django.db import migrations, models def copy_data(apps, database_schema): TestModel = apps.get_model("data_migrations", "TestModel") NewTestModel = apps.get_model("data_migrations", "NewTestModel") for old_object in TestModel.objects.all(): new_object = NewTestModel( field1 = old_object.field1, field2 = old_object.field2 ) new_object.save() class Migration(migrations.Migration): dependencies = [ ('data_migrations', '0005_testmodel'), ] operations = [ migrations.CreateModel( name='NewTestModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('field1', models.CharField(max_length=255)), ('field2', models.TextField()), ], ), migrations.RunPython(copy_data) ] Then I delete TestModel model and run the migration commands. After that I rename NewTestModel to TestModel and once again run the migration commands. Everything worked out as it was supposed to. Did I do it right? -
How to show permissions in django admin project?
I have a django app. And I try in the admin panel of django restrict user permissions with the AUTHENTICATION AND AUTHORIZATION tab. But I noticed that something is missing in my existing django app on the AUTHENTICATION AND AUTHORIZATION tab. Because I installed a clean install from django. And the AUTHENTICATION AND AUTHORIZATION tab looked like: and the AUTHENTICATION AND AUTHORIZATION tab in my existing django app looks like: So as you can see in my existing django app the right part is missing of the user permissions. What I have done? Is checking the versions. And they are the same(clean version and exsting version) I am using django version: 5.0.6. and the libraries I checked the libraries installed with pip freeze of my exisiting version: anyio==4.2.0 asgiref==3.7.2 attrs==23.1.0 azure-common==1.1.28 azure-core==1.29.6 azure-storage-blob==12.19.0 azure-storage-common==2.1.0 certifi==2023.7.22 cffi==1.15.1 charset-normalizer==3.2.0 click==8.1.7 colorama==0.4.6 coreapi==2.3.3 coreschema==0.0.4 cryptography==39.0.0 defusedxml==0.7.1 Django==5.0.6 django-allauth==0.52.0 django-cors-headers==3.10.1 django-dotenv==1.4.2 django-filter==23.2 django-storages==1.14.2 djangorestframework==3.14.0 drf-spectacular==0.26.4 drf-yasg==1.20.0 exceptiongroup==1.2.0 gunicorn==21.2.0 h11==0.14.0 idna==3.4 inflection==0.5.1 isodate==0.6.1 itypes==1.2.0 Jinja2==3.1.2 jsonschema==4.19.0 jsonschema-specifications==2023.7.1 Markdown==3.4.4 MarkupSafe==2.1.3 oauthlib==3.2.2 packaging==23.1 Pillow==10.0.0 psycopg2==2.9.7 pycparser==2.21 PyJWT==2.6.0 pyrsistent==0.19.3 python-dateutil==2.8.2 python3-openid==3.2.0 pytz==2023.3.post1 PyYAML==6.0.1 referencing==0.30.2 requests==2.31.0 requests-oauthlib==1.3.1 rpds-py==0.10.2 ruamel.yaml==0.17.32 ruamel.yaml.clib==0.2.7 six==1.16.0 sniffio==1.3.0 sqlparse==0.4.4 typing_extensions==4.7.1 tzdata==2023.3 uritemplate==4.1.1 urllib3==2.0.4 uvicorn==0.23.2 waitress==2.1.2 And part of settings.py file of the existing app: LOGOUT_REDIRECT_URL … -
Error when displaying contents of a .csv in Django (backend in S3 AWS)
I'm having quite a trouble when displaying in JSON format the contents of a .csv file located in a S3 Bucket. I am able to do the GET method correctly, but I think that I'm doing something wrong when trying to display the contents of the previously mentioned file. It is not that I obtained something weird or an error, the label where the content should be just displays nothing. Current Python code is: def flightlogs(request): # configure boto3, this works csv_files = [] try: response = s3_client.list_objects_v2(Bucket=bucket_name) for obj in response.get('Contents', []): if obj['Key'].endswith('.csv'): csv_files.append(obj['Key']) except Exception as e: print(f"Error al listar archivos en el bucket: {e}") # this is for saving the content of the .csv csv_contents = {} # Itera sobre cada archivo CSV encontrado for file_key in csv_files: try: # Obtiene el objeto (archivo) desde S3 obj = s3_client.get_object(Bucket=bucket_name, Key=file_key) # Lee el contenido del archivo y lo decodifica como UTF-8 content = obj['Body'].read().decode('utf-8') # Lee el contenido CSV y lo convierte en una lista de diccionarios csv_reader = csv.DictReader(StringIO(content)) rows = list(csv_reader) # Convierte la lista de diccionarios a JSON con formato indentado csv_contents[file_key] = json.dumps(rows, indent=4) except Exception as e: # Manejo de errores … -
How to get a joined latest object in django ORM?
I have two tables 1:N related. I want to get only one latest deal model on each real_estate model. class RealEstate(gis_models.Model): class Meta: db_table = "real_estate" id = models.BigAutoField(primary_key=True, auto_created=True) name = models.CharField( help_text="부동산 이름", null=True, blank=True, max_length=30 ) build_year = models.SmallIntegerField( help_text="건축년도", null=False, blank=False ) regional_code = models.CharField( help_text="지역코드", null=False, blank=False, max_length=6, ) lot_number = models.CharField( help_text="지번(구획마다 부여된 땅 번호, 서울특별시 서초구 반포동 1-1)", null=False, blank=False, max_length=50, ) road_name_address = models.CharField( help_text="도로명 주소", null=True, blank=True, max_length=50 ) address = models.CharField( help_text="주소", null=True, blank=True, max_length=50 ) real_estate_type = models.CharField( help_text="부동산 타입", choices=REAL_ESTATE_TYPES, max_length=20, ) latitude = models.CharField( help_text="위도", null=False, blank=False, max_length=20 ) longitude = models.CharField( help_text="경도", null=False, blank=False, max_length=20 ) point = gis_models.PointField(geography=True, null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Deal(models.Model): class Meta: db_table = "deal" id = models.BigAutoField(primary_key=True, auto_created=True) deal_price = models.PositiveIntegerField( help_text="거래금액(전월세 보증금)", null=False, blank=False ) brokerage_type = models.CharField( help_text="중개/직거래(거래유형)", null=True, blank=True, choices=BROKERAGE_TYPES, max_length=10, ) deal_year = models.SmallIntegerField( help_text="계약년도(년)", null=False, blank=False ) land_area = models.CharField( help_text="대지권면적", null=False, blank=False, max_length=10 ) deal_month = models.SmallIntegerField( help_text="계약 월", null=False, blank=False ) deal_day = models.SmallIntegerField( help_text="계약 일", null=False, blank=False ) area_for_exclusive_use = models.CharField( help_text="전용면적(제곱미터)", null=False, blank=False, max_length=10 ) floor = models.CharField( help_text="층", null=False, blank=False, max_length=3 ) is_deal_canceled = models.BooleanField( help_text="해제여부(거래계약이 …