Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to see certificate contents for incoming request in Django?
I am building an Endpoint to receive data inside POST request, And a webserver is going to send that request to my server, and they have SSL Certificate, Now i need to verify inside my API View that the request is coming from them not anyone else, And i will check that by getting their Digital Certificate and check it, Now how can i view their certificate inside the request in Django View? -
KeyError in django when using a textarea
I want to do a very simple operation : 1-taking some info form the form 2-saving the data in the database But i get this error and i don't know the reason of it! can you please help . this is the forms.py : class ContactForm(forms.Form): title = forms.CharField(max_length=500) phone_mail = forms.CharField(max_length=30) body = forms.Textarea() this is the models.py : class Contact(models.Model): title = models.CharField(max_length=500) phone_mail = models.CharField(max_length=30) text = models.TextField() this is the views.py : def contact(request): if request.method == 'POST': form = forms.ContactForm(request.POST) if form.is_valid(): data = form.cleaned_data Contact.objects.create(title = data['title'] , text = data['body'] , phone_mail = data['phone_mail']) return redirect('accounts:profile') else : form = forms.ContactForm() con = {'form' : form} return render(request , 'home/contact.html' , con) And this is the form : <form class="row g-3 p-3" method="post"> {% csrf_token %} <div class="col-md-6"> <label for="title" class="form-label">title</label> <input type="text" class="form-control" id="title" name="title"> </div> <div class="col-md-6"> <label for="phone_mail" class="form-label">phone or email</label> <input type="text" class="form-control" id="phone_mail" name="phone_mail"> </div> <div class="col-12"> <label for="inputtext" class="form-label">text:</label> <textarea type="text" class="form-control" name="body" id="inputtext" minlength="20" maxlength="10000" required></textarea> </div> <div class="col-12"> <button type="submit" class="btn btn-primary">Send</button> </div> </form> And i get this error for them when i use the form to send the data : KeyError at /contact/ 'body' … -
How to mock settings in Django Unit testing
I am new to Django Unit testing and am trying to write unit test for a simple function which is like below: utils.py #some import statements from django.conf import settings if platform.system() == 'Linux': cx_Oracle.init_oracle_client(lib_dir=settings.GAP_DB_LIB_DIR) else: cx_Oracle.init_oracle_client(lib_dir=settings.LOCAL_DB_LIB_DIR) db_password = settings.DB_PASS db_user = settings.DB_USER db_connection_dsn = settings.DB_CONNECTION_DSN def project(repo): pieces = parse.urlsplit(repo) return pieces.path.rstrip('/').split('/')[-1] I am writing unit tests in test.py fie as below from django.test import TestCase from common import utils from utils import project from django.test import override_settings # Create your tests here. class UtilsTest(TestCase): def setUp(self): self.repo = "http://test/testrepo" @override_settings(LOCAL_DB_LIB_DIR="c:/testdir") def test_project(self): response = utils.project(self.repo) self.assertEqual(response,"testrepo") When I run tests am getting below error: AttributeError: 'Settings' object has no attribute 'LOCAL_DB_LIB_DIR' Please help me where I am doing wrong and correct my coding. Thanks in advance. -
In Django with all-auth, how do I pass the authenticated user from the front end to be saved in the database table through a form?
I have been able to get my form to write to the database but I have two issues. One with passing the site_name to the slug field so that the user doesn't have to manually enter a slug and one passing the authenticated user to the "pilot" field automatically. I'd like to address the user issue with this question. When I render all fields of the model as a form I am able to manually select the user from a drop-down list of the possible users (all users) when submitting a form. I would like to take this field away from the form and have it auto-populate with the name of the currently authenticated user. Is there a way to set the default value in 'pilot' field of the model to be the currently authenticated user? I have tried a few different ways but I am running into different errors. I am very new to Django so don't have a great understanding. I have included the previous attempt in the view commented out. Thanks for your help. View def UploadFlyingSite(request): if request.method == "POST": form = SiteUpload(request.POST) if form.is_valid(): site_details = form.save() site_details.pilot = request.user.username site_details.slug = site_details.site_name site_details.save() # … -
Пытаюсь привязать Postgresql с Django.Библиотека psycopg2 установлена.Данные базы данных изменены,но при попытке запустить сервер выходит такая ошибка
Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 282, in ensure_connection self.connect() File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 263, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\postgresql\base.py", line 215, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\psycopg2_init_.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run self.check_migrations() File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 564, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\loader.py", line 58, in init self.build_graph() File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\recorder.py", line 81, in applied_migrations if self.has_table(): File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 323, in cursor return self._cursor() File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 299, in … -
Directional/ guidance related to Django, secured code hosting
I just joined today and this is my first post. I hope everyone is doing well. First, NOT AT ALL am a programmer and therefore there may be some elementary dependency in my posts (note this first). For some reasons, I was tasked to start a web application (small with, but have the potential to be scaled in the future with a proper dev team)... My questions below are very conceptual, I would need your thoughts/expert advice here. NOTE: The application is an analytics tool that is 80% forms, tables, tree charts, dropdowns and popups that interact with the database to extract the data on the front end and manipulate the data in the database based on user input. To develop the application in less time, we use the Django framework. In the YouTube tutorials, I see that the web UI is open on localhost:8000. How can I redirect this address so that it appears in my URL? How secure are the shared domains offered by web hosting companies (like GoDaddy, Hostinger, etc.)? When the time is right, all applications need to be hosted in the cloud, with proper security encryption of the data. Is there a good data management … -
Celery current_task.update_state not working
I'm trying to add a long running async task and make it update it's progress status in intervals. I'm using a Django-rest-framework server, RabbitMQ broker, Celery worker. I'm able to add a task to celery, and even able to successfully retrieve the result upon task completion. However whenever trying to get the state before task completion I get the following: task.result = None, task.state = PENDING, task.info = None When trying to get state post completion: task.result = None, task.state = PENDING, task.info = None DeployML/ manage.py DeployML/ ... settings.py tasks.py dcelery.py views.py urls.py dcelery.py: import os from celery import Celery import sys sys.path.append('.....DeployML') sys.path.append('.....DeployML/DeployML') # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DeployML.settings') app = Celery('DeployML', backend='rpc://', broker='pyamqp://guest@localhost//', worker_state_db = '/tmp/celery_state') app.config_from_object('django.conf:settings') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') tasks.py: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DeployML.settings') from celery import shared_task from celery import current_task from dcelery import app import time @app.task(bind=True) def addShrd(self, x, y): for i in range(4): time.sleep(5) progress_percent = i #NOTE update_state not working yet current_task.update_state(state='PROGRESS', meta={'current': i, 'total': 4}) return x + y views.py: #... #... @api_view(['GET', 'POST']) def ml_celer_view(request): print("authentication: ", request.user, request.auth) if request.method == 'GET': result = addShrd.delay(17,10) return Response({'task_id': str(result.id)}) … -
how can I solve this error on angular app
This error is showing after I keeps running ng serve --disable-host-check and have enable for all origin on python django rest framework Access to XMLHttpRequest at 'localhost:8000/supplier/' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, chrome-untrusted, https, isolated-app. -
I use POST methon in Django, but my request.method == 'POST' said that it's GET methon
I don't know why my create function worked before, but now is not working. I see only "It's not POST, it's GET". I have tried to delete something, for example: from def index(request): email = str(request.GET.get('autorization_email')) and from def create(request) type_values = Type.objects.all() model_values = Model.objects.all() equipment_values = Equipment.objects.all() It didn't helped url.py urlpatterns = [ path('', views.autorization, name='autorization'), path('home/', views.index, name='home'), path('return_equpment/', views.return_equpment, name='return_equpment'), path('create/', views.create, name='create'), ] create.html {% block content %} <form method="post" action="{% url 'create' %}"> {% csrf_token %} ... <button type="submit" class="btn btn-success">Save</button><br> <span>{{ error }}</span><br> </form> {% endblock%} views.py from django.shortcuts import render, redirect from .models import Booking, Type, Model, Equipment from .forms import BookingForm error = '' email = '' def index(request): global email global error email = str(request.GET.get('autorization_email')) context = { 'title': 'Main page', 'error': error, 'index_email': email } return render(request, 'main/index.html', context) def create(request): type_values = Type.objects.all() model_values = Model.objects.all() equipment_values = Equipment.objects.all() form2 = BookingForm() global error global email context = { 'form': form2, 'error': error, 'type_values': type_values, 'model_values': model_values, 'equipment_values': equipment_values, 'create_email': email } if request.method == 'POST': form2 = BookingForm(request.POST) form2.email = email form2.type = request.POST.get('type') form2.model = request.POST.get('model') form2.number = request.POST.get('number') if form2.is_valid(): form2.save() return redirect('autorization') else: … -
socket "/cloudsql/.s.PGSQL.5432" failed: Invalid argument (0x00002726/10022) Is the server running locally and accepting connections on that socket?
I have tested connectivity for cloud SQL instance and started web server in sample Django project. #.\cloud_sql_proxy.exe -instances="instance-name"=tcp:5432 python manage.py runserver It is working fine in sample Django project. But whenever We are trying to execute the above commands by our Django Project, we are facinng the following error when execute the python manage.py runserver. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\KarthikKumar\Documents\GitHub\tnt-deploy\venv\lib\site-packages\psycopg2_init_.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: connection to server on socket "/cloudsql/ajrsd2:us-central1:ajrsd2/.s.PGSQL.5432" failed: Invalid argument (0x00002726/10022) Is the server running locally and accepting connections on that socket. I have checked secrets details in https://console.cloud.google.com/security/secret-manage There are no restrictions in the access permission. Also I have verified steps as per the below reference link. Sir https://cloud.google.com/python/django/appengine#console_3 Please check and let us know the solution. Thanks -
How to handle migrations for 3rd-party django apps in a deployment pipelines?
I'm using a 3rd party dependency modeltranslation-lokalise which requires me to run python manage.py makemigration. This will generate a migration file that sits within the package directory once generated, and therefore are not source controlled. For all other migration files I'm keeping them in source control and would like to do the same for these, as it will allow us to track changes to the database in the environments we use, ensuring they can be easily replicated and that operations are not duplicated on the same database (e.g. by having the same operation exist in differently-named migrations). My question: How are these 3rd party migrations meant to be handled when building and deploying to production (e.g. via a Dockerfile in a build pipeline? My guess would be to find a way to reliably extract the migration files from the package and add it to source control. The alternative would be: run makemigrations within the Dockerfile that builds the deployed image, however that could result in the same migration being run twice on the database should the name of that migration change (e.g. if there's a timestamp in the name). So I'm thinking best to avoid that. Note: this question is … -
django Imagefield accepting all files
In my registration page, I am able to input a file other than an image for example -.txt or .py then save it. Even though my model is an Imagefield it allows files other than images. I have other models with imagefield in them but they are working fine. When I try to save a txt or py file there it raises an error. But in my registration page it directly saves it. I have also added validators still does not work. Note that when I try to edit user from admin page there it raises an error. models.py : from django.contrib.auth.models import User from django.core.validators import validate_image_file_extension from django.db import models from django.utils import timezone from multiselectfield import MultiSelectField # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, help_text=False) profile_pic = models.ImageField(upload_to="profile_pic/",validators=[validate_image_file_extension], null=True , blank=True) def __str__(self): return self.user.username views.py def register(request): accounts = User.objects.all() if request.method == "POST": user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.is_active = False user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() messages.success(request, 'Your account has been created Sucessfully!!!!') messages.success(request, 'You can use your account after it has … -
No Tag matches the given query. on localhost:8000/filter/en
I've been working on a project, where I want to filter a resource on a page by language. But everytime I use that filter, i'm getting redirected to a 404-Page. This is my View: class SomeView(LoggedUserWithOrganizationMixin, ListView): paginate_by = 12 def get_queryset(self): qs = Example.objects.all() selected_language = self.kwargs.get("selected_language",self.request.user.profile.language) return qs.filter(language = selected_language) This is my url in urls.py: path('<str:selected_language>/', views.SomeView.as_view(), name="list-lang-filter"), And this is my HTML-Code for the select where the user can pick the language: <div x-show="dropdownOpen" class="w-full absolute rounded border border-forblueshadow bg-white z-20 font-light text-brightblue pt-1"> {% for language in languages %} <a href="{% url 'list-lang-filter' current_organization.pk language.code %}" class="language_filter_dropdown rounded-t py-2 px-4 block whitespace-no-wrap"> {{ language.name }} </a> {% endfor %} </div> When choosing an option in the filter-menu, i get redirected to a url with the right language code in it, but it just shows a 404. The weird thing is i did the exact same thing on another resource and it worked just fine. Does anybody have an idea? -
Imports using SlugRelated Feilds are Not working
I am Trying To Json Parse the objects passed through the slugrelated Feilds in django serializer class ImportFinanceSaleSerializerField(serializers.JSONField): def to_representation(self, obj): user_serializer = ImportFinanceSaleSerializer(obj, many=False, ) return user_serializer.data class ImportFinanceSaleSerializer(serializers.ModelSerializer): interestpercentage = serializers.SlugRelatedField( required=False, allow_null = True, slug_field="code", queryset=PercentageInterest.objects.filter(status=1,)) guarantor = serializers.SlugRelatedField( required=False, allow_null = True, slug_field='code', queryset=Person.objects.filter(status=1,)) emi_date = serializers.IntegerField(required=False, min_value=1, max_value=30) Error:- It input is taken as PCI00002 <class 'str'> -
Display ckeditor in django without form.py
I am trying to build an application in which I want to add a rich text editor. I have added CKEditor and it is working fine on the admin panel. I want to know if there is any way to display the editor without form.py, just to save data from simple post requests. this is how it is looking but it should be the rich text editor. is there any alternative way except forms.py for adding that editor? Thank You in advance :) models.py from django.db import models from ckeditor.fields import RichTextField # Create your models here. class Profile(models.Model): name = models.CharField(max_length=255) email = models.EmailField(max_length=255) previous_work = RichTextField(max_length=2000) skills = RichTextField(max_length=2000) html <form class="container"> {% csrf_token %} {{ form.media }} <div class="mb-3"> <label class="form-label">Name</label> <input type="text" class="form-control" name="name" id="name"> </div> <div class="mb-3"> <label class="form-label">Email</label> <input type="email" class="form-control" name="email" id="email"> </div> <div class="mb-3"> <label class="form-label">Previous Work</label> <!-- <input type="number" class="form-control" name="summary" id="summary"> --> <textarea name="Previous_work" class="form-control" id="Previous_work" cols="30" rows="10"></textarea> </div> <div class="mb-3"> <label class="form-label">Skills</label> <!-- <input type="number" class="form-control" name="summary" id="summary"> --> <textarea name="skills" class="form-control" id="skills" cols="30" rows="10"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> -
How to use IntegerRange as part of unique constraint in a Django 2.2 model
I understand that Django 2.2 is outdated. I am in the midst of migrating. Having said, that I still need to temporarily add new constraints to prevent invalid data for time being. from django.contrib.postgres.fields.ranges import IntegerRangeField class ProjectStructureWbsIslandGap(): series = models.ForeignKey(ProjectStructureFasSeries, on_delete=models.CASCADE) is_island = models.BooleanField(default=True) # island or gap level_3_range = models.IntegerRangeField(default=(1, 9999)) # 1-9999 line_number_range = models.IntegerRangeField(default=(1, 9999)) # 1-9999 class Meta: constraints = [ models.UniqueConstraint( fields?? conditions?? ), ] so what i want is these two constraint, whenever create new or update existing ProjectStructureWbsIslandGap record, within the same parent series and of the same is_island value, no two records can have overlap in terms of the IntegerRangeField level_3_range. whenever create new or update existing ProjectStructureWbsIslandGap record, within the same parent series and of the same is_island value, no two records can have overlap in terms of the IntegerRangeField line_number_range. so under the unique constraint, how should i fill in fields, and conditions? -
Django - CSS File Not Loading In Production server (Debug: False)
Use : nginx,gunicorn,linode for server Debug=False When I keep debug=False in production the css file don't get loaded.I have also build 404.html page.Suppose some one visit mydomain.com/abcd then he/she will get the 404 page which I have designed.Its good.The issue is css file not loaded. Debug True When I keep debug=True in the production the css file get loaded.Everything goes right.But when someone visited the mydomain.com/abcd then he/she will get the django defaualt error page.If I keep debug=True in the production everything goes right but I have heard that keeping debug=True in production is not recommended and may cause the security issues in the sites Currently what I have in my settings.py and nginx cofig are : settings.py : DEBUG =True ALLOWED_HOSTS = ['ip','mydomain.com','www.mydomain.com'] Nginx config file : server { server_name mydomain.com www.mydomain.com; location = /favicon.ico { access_log off; log_not_found off; } location projectdir/static/ { autoindex on ; root /home/user/projectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } Please help me to solve the issue,since I am struggling from past 1 week. Currently the site is live and css is loaded by keeping debug=True.But I don't want to have any security issue later. -
gunicorn processes wont shut down
I am trying to kill my gunicorn processes on my server. When I run kill {id} they seem to shut down for maybe 1sec and then they start back up. $ ps ax | grep gunicorn 42898 ? S 0:00 /usr/bin/python3 /usr/bin/gunicorn cms_project.wsgi -b 0.0.0.0:8000 -w 1 --timeout 90 42924 ? S 0:00 /usr/bin/python3 /usr/bin/gunicorn cms_project.wsgi -b 0.0.0.0:8000 -w 1 --timeout 90 then I run pkill -f gunicorn the processes go away for maybe 1second and then start back up on session id's 43170 ? S 0:00 /usr/bin/python3 /usr/bin/gunicorn cms_project.wsgi -b 0.0.0.0:8000 -w 1 --timeout 90 43171 ? S 0:00 /usr/bin/python3 /usr/bin/gunicorn cms_project.wsgi -b 0.0.0.0:8000 -w 1 --timeout 90 I have also tried killing them individually using the kill process -
Django StreamingHttpResponse returns only a single yield result from generator to stream
I am trying to stream several large json files to the front end at a time (I need to stream all of them one by one, and can't split it into several requests): def stream_response_generator(response): yield json.dumps({ 'searchedVariants': response['searchedVariants']}) yield json.dumps({ 'genesById': response['genesById']}) yield json.dumps({ 'locusListsByGuid': response['locusListsByGuid']}) yield json.dumps({ 'genesQcData': response['genesQcData']}) @login_required(login_url=API_LOGIN_REQUIRED_URL) @csrf_exempt @log_request(name='query_variants_handler') def query_variants_handler(request, search_hash): ... return StreamingHttpResponse(stream_response_generator(response), content_type='application/octet-stream') Only the very first searchedVariants response is streaming to the front end but other 3 are omitted. I verified it printing out the response on the frontend: fetch(url, { method: 'POST', credentials: 'include', body: JSON.stringify(search), signal: signal, }).then((response) => { const reader = response.body.getReader() let decoder = new TextDecoder('utf8'); let read reader.read().then(read = (result) => { if (result.done) return let chunk = decoder.decode(result.value); console.log(chunk) reader.read().then(read) }) }) In some tutorials, e.g. https://andrewbrookins.com/django/how-does-djangos-streaminghttpresponse-work-exactly/ Its written that we should pass a function generator instead of calling a function like I do, however, when I do that: def stream_response_generator(response): def generator(): yield json.dumps({ 'searchedVariants': response['searchedVariants']}) yield json.dumps({ 'genesById': response['genesById']}) yield json.dumps({ 'locusListsByGuid': response['locusListsByGuid']}) yield json.dumps({ 'genesQcData': response['genesQcData']}) return generator @login_required(login_url=API_LOGIN_REQUIRED_URL) @csrf_exempt @log_request(name='query_variants_handler') def query_variants_handler(request, search_hash): ... return StreamingHttpResponse(stream_response_generator(response), content_type='application/octet-stream') I am getting an error: 2022-10-21 03:34:28,165 ERROR: Traceback (most recent call last): … -
HTTP Error 500.0 - Internal Server Error (Django-Pyodbc,Oracle Database,IIS+FastCGI)
I can python manage.py runserver local but when I run by IIS some of my page can accessible except the page that use data from oracle and pyodbc. All 32bit except IIS. -
Django exhaust all object with specific status before returning other status with pagination
I basically have a todo list that may or may not go up to a thousand and the requirement is to show all "unchecked/uncomplete" before showing those that are completed, that looks easy but the problem is that it is paginated and or on an unlimited scrolling UI. I have this piece of code which works fine for basic usage but is not working for the requirement since it orders it all the time. models.mytodo.objects.order_by("-status") -
When create django table dynamically, how can I set Meta class?
I have a Django abstract model class and want to create it dynamically with meta class. class AccountTransaction(models.Model): class Meta: abstract = True account_num = models.ForeignKey('Account', on_delete=models.CASCADE) tran_amt = models.PositiveBigIntegerField() tran_type = models.CharField() tran_detail = models.CharField() tran_time = models.DateTimeField(auto_now_add=True) for i in range(10): model_name = f'account_transaction_{i:02}' globals()[model_name] = type(model_name, (AccountTransaction, ), {'__module__': AccountTransaction.__module__}) I could create 10 tables with this code when execute makemigrations and migrate Is it possible to set different metaclasses for each tables? For example, account_transaction_01 class Meta: db_table: "table1" account_transaction_02 class Meta: db_table: "table2" -
Django, Is there a way to access additional custom fields to the default user model in the serializer?
I am trying to send current user information through an API endpoint. I am using the Django default user model, and adding additional fields through inline. (Please refer to the code below) I am wondering if there is a way that I can access the newly added fields in the User serializer? I tried a lot of ways to include the newly added data but all failed. (for example, I am trying to pass gender_identity to my serializer so that my frontend could access the information) Here is my serializer.py: from django.contrib.auth.models import User from accounts.models import Account class UserSerializer(serializers.ModelSerializer): # author = serializers.SlugRelatedField(queryset=User.objects.all(), slug_field='username') class Meta: # gender_identity = User.objects.get(username = 'bucky').account.gender_identity model = User fields = ['username', 'email','first_name','last_name'] read_only_fields = ['username', 'email','first_name','last_name'] depth = 3 Here is my Views.py: from rest_framework import viewsets # from .serializers import UserSerializer from .serializers import UserSerializer from django.contrib.auth.models import User from rest_framework.generics import (ListAPIView, ListCreateAPIView, DestroyAPIView, UpdateAPIView) class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer def get_object(self): # print(self.request.user.account.gender_identity) print(type(self.request.user)) return self.request.user def list(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) My models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Account(models.Model): # user = models.ForeignKey(User, on_delete=models.CASCADE) user = … -
Why does Bootstrap cards have cards all shifted to the left?
I am creating a page in which news articles get fetched using Python, and then formatted into cards. I have used pagination to have 12 cards per page, but for some reason, all my cards and pagination bar are shifted to the left, and everything is off-centered. I would like to have them centered and all have the same width and height. How would I do this? {% if not posts %} <p>No articles were found.</p> {% else %} <div class="card-columns"> <!--class="row" style="display: flex; flex-wrap: wrap; gap: 8px; max-width: 916px; width: calc(100% - 20px);"--> {% for result in posts %} <div class="card"> <!--style="height: 260px; width: 300px; border-radius: 10px;"--> <img class="card-img-top img-fluid" src="{{ result.img }}" alt="Article image cap"> <div class="card-body"> <a href="https://{{ result.link }}" target="_blank"><h5 class="card-title">{{ result.title }}</h5></a> <p class="card-text">{{ result.desc }}</p> </div> </div> {% endfor %} </div> {% endif %} {% if posts.has_other_pages %} <ul class="pagination justify-content-center"> {% if posts.has_previous %} <li class="page-item"> <a class="page-link" href="?page= {{ posts.previous_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#!" tabindex="-1" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% endif %} {% for num in posts.paginator.page_range %} {% … -
copyleaks sent pdfReport to endpoint as binary on request.body, not as file
I have django view that gets request and I try to send pdf result of copyleak scan. I get file as request.body and request.FILES is empty. I have checked copyleaks docs to see if I could pass extra argument as we should pass enctype="multipart/form-data" in django form to get files in request.FILES, but I did not see anything related. I can read request body and write it to file, no problem here, but would be great if I directly get pdf file in request FILES. myobj = json.dumps( { "pdfReport": { "verb": "POST", "endpoint": "https://aa67-212-47-137-71.in.ngrok.io/en/tool/copyleaks/download/", }, "completionWebhook": "https://aa67-212-47-137-71.in.ngrok.io/en/tool/copyleaks/complete/", "maxRetries": 3, } ) response = requests.post( "https://api.copyleaks.com/v3/downloads/file4/export/export16", headers=headers, data=myobj, ) I tried to change Content-Type manually and got error django.http.multipartparser.MultiPartParserError: Invalid boundary in multipart: None Bad request (Unable to parse request body): /en/tool/copyleaks/download/