Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django gunicorn nginx forward to <domain>/app
I have searched tutorials and SO all over but unfortunately I still don't understand how to forward requests for my domain to a specific app (not the project). this is my project structure django_project || bjsite -- settings.py -- wsgi.py -- ... || bj -- models.py -- views.py -- templates -- ... || manage.py static requirements.txt venv ... in settings.py, this is my WSGI_APPLICATION = 'bjsite.wsgi.application' gunicorn service [Unit] Description=gunicorn daemon Requires=bj.socket After=network.target [Service] User=bj Group=www-data WorkingDirectory=/home/bj/bjsite ExecStart=/home/bj/bjsite/venv/bin/gunicorn \ --access-logfile /home/bj/bjsite_deploy/gunicorn_access.log \ --error-logfile /home/bj/bjsite_deploy/gunicorn_error.log \ --workers 3 \ --bind unix:/run/bj.sock \ bjsite.wsgi:application [Install] WantedBy=multi-user.target and my nginx cong in sites-available server { listen 80; server_name domain.de www.domain.de; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; proxy_pass http://unix:/run/bj.sock; } location /static/ { root /home/bj/bjsite_deploy; } location /media/ { root /home/bj/bjsite_deploy; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/domain.de/fullchain.pem; # managed by Certb> ssl_certificate_key /etc/letsencrypt/live/domain.de/privkey.pem; # managed by Cer> include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.domain.de) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = domain.de) { return 301 https://$host$request_uri; } # managed by Certbot server_name domain.de www.domain.de; listen … -
IntegrityError at /accounts/verify/ UNIQUE constraint failed: accounts_user.mobile_number
when i try login this error is appear.first i make otp and sent to client then i login him/her. this is login view: class UserLoginView(LoginRequiredMixin, View): form_class = LoginForm def get(self, request): form = self.form_class() return render(request, 'accounts/login.html', {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): cd = form.cleaned_data rcode = random.randint(1000, 9999) send_otp_code(cd['phone'], rcode) OtpCode.objects.create(mobile_number=cd['phone'], code=rcode) request.session['login_info'] = { 'email': cd['email'], 'mobile_number': cd['phone'], 'password': cd['password'] } messages.success(request, 'we sent you a code', 'success') return redirect('accounts:verify_code') return render(request, 'accounts/login.html', {'form': form}) class UserLoginVerify(View): form_class = VerifyCodeForm def setup(self, request, *args, **kwargs): self.next = request.GET.get('next') return super().setup(request, *args, **kwargs) def get(self, request): form = self.form_class() return render(request, 'accounts/verify_code.html', {'form': form}) def post(self, request): user_session = request.session['login_info'] code_instance = OtpCode.objects.get(mobile_number=user_session['mobile_number']) form = self.form_class(request.POST) if form.is_valid(): cd = form.cleaned_data if cd['code'] == code_instance.code: user = authenticate(email=user_session['email'], mobile_number=user_session['phone'], password=user_session['password']) if user is not None: login(request, user) messages.success(request, 'you login successfully', 'success') return redirect('home:home') else: messages.error(request, 'your password or email is wrong', 'danger') return render(request, 'accounts/login.html', {'form': form}) this is my error in browser. The error shown is in the registration section, but I am logging in -
how to use simple jwt withour user class abstraction in django
"how can use simple jwt token generation and validation without using user class abstraction i wanna make something like text to generate api and have limitation for time and count of token request i have model named domain its gonna send request to a server under my server and i have a service model that have that server details to send request now i want to make it with token validation cause i want to have limit for it " -
Django form is rendering via AJAX but with no data inside fields
I'm trying to render a Django form with AJAX : Here are my files : Models.py class models_projects(models.Model): id = models.CharField(primary_key=True, max_length=50) reference = models.CharField(max_length=50) model = models.CharField(max_length=50) class Meta: db_table = 'table_projects' Forms.py class forms_projects(forms.ModelForm): id = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={"placeholder":"id", "class":"form-control"}), label="id") reference = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={"placeholder":"reference", "class":"form-control"}), label="reference") model = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={"placeholder":"model", "class":"form-control"}), label="model") class Meta: model = models_projects exclude = ("user",) View.py def update_project_mobile(request): project_id = request.POST.get('project_num') if request.user.is_authenticated: record = models_projects.objects.get(id = project_id) projects_form = forms_projects(request.POST or None, instance=record) if projects_form.is_valid(): projects_form.save() return render(request, 'projects_mobile.html', {'projects_form':projects_form}) else: messages.success(request, "You Must Be Logged In...") return redirect('home') template.html <select name="project_num" id="project_num"> <option value="2"> "2" </option> </select> <div id="projects_container" ></div> <!-- This is where projects_mobile.html is rendered --> <script> function load_projects (){ $.ajaxSetup( { data: {project_num: $('#project_num').val(), csrfmiddlewaretoken: '{{ csrf_token }}' }, }); $.ajax({ type: "POST", url: "../update_project_mobile/", //dataType: 'json', success: function (data) { $("#projects_container").html(data); } }); } </script> urls.py ... path('update_project_mobile/', views.update_project_mobile,name='update_project_mobile'), ... projects_mobile.html <body> {{ projects_form }} </body> The form is rendering well as the content of projects_mobile.html displays well inside the <div id="projects_container" ></div> but there is no data inside the form's fields, only the placeholders are displayed. The Database is very easy and there is an entry … -
Can Django be utilized in a Python chat app based on sockets
i am new in python. i have created a chat app using kivy and socket(not socket-io and not web-socket). it works well but i want to use Django in server side. "Can Django be utilized in a Python chat app based on sockets, incorporating its features for user authentication, database management, and static content handling alongside real-time communication?" -
Django form wizard can't return to the first step after last summarized page
I use SessionWizardView for gain initial data from user via wizard. I have four required steps and one optional (customed). After last step I forward to summarized page. If press refresh browser's button at this point I will expect redirect to the first page of my wizard. But in fact I redirected to second page, for some reason. Could anyone help me to undestand this behavior? This is my templates: TEMPLATES = { 'select_type': "poneraapp/select_type.html", 'select_features': "poneraapp/select_features.html", 'select_model': "poneraapp/select_model.html", 'set_objects_number': "poneraapp/set_objects_count.html", 'select_support': "poneraapp/select_support.html" } My form list: form_list = [ ('select_type', FormStepOne), ('select_features', FormCustomStep), ('select_model', FormStepTwo), ('set_objects_number', FormStepThree), ('select_support', FormStepFour) ] done function: def done(self, form_list, **kwargs): self.storage.reset() return render(self.request, 'done.html', { 'form_data': [form for form in form_list], }) -
How to apply Bootstrap style to RichTextUploadingField?
I attached CKeditor to my site. When I load a high-resolution image, all Bootstrap responsiveness breaks. This can be corrected - you need to manually assign the style and CSS class to the picture. It’s inconvenient to do this manually every time, and the styles for other elements will also have to be written manually, and this takes a long time. How can I apply Bootstrap style to all elements of this field? Maybe there is some kind of Bootstrap settings preset that needs to be written somewhere in settings.py? I tried to manually set the image style in the ckeditor editor. I want the Bootstrap style to be automatically applied to all elements (such as , , , etc.) -
Django Sending Email: sending activation use django sendgrip
I want to send the email activation using django registration. Below is my production settings.py EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'apikey' # EMAIL_HOST_PASSWORD = get_secret('SENDGRID_API_KEY') EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' DEFAULT_FROM_EMAIL = 'noreply@uralholidays.com' # EMAIL_BACKEND = "sendgrid_backend.SendgridBackend" The project is running fine on my local server. but when I pushed it to the production (beta version)- it did not have any SSL. I need the settings to work for both production (beta version) and (the main version -having SSL). I am getting the below issue. SMTPServerDisconnected at /accounts/signup/ Connection unexpectedly closed Request Method:POSTRequest URL:http://beta-uralholidays.com/accounts/signup/Django Version:3.2.20Exception Type:SMTPServerDisconnectedException Value:Connection unexpectedly closedException Location:/usr/lib/python3.10/smtplib.py, line 405, in getreplyPython Executable:/usr/bin/python3Python Version:3.10.12Python Path:['/home/booking_app-beta-20230928-130136/booking_app/booking_app', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages']Server time:Thu, 28 Sep 2023 14:05:55 +0000 I am trying to make it work in both my local server the production beta version (not having SSL) and the production main version (having SSL). Please suggest to me the exact changes I need to do. The hosting web server is digital ocean -
Django forms(comments) issue
Why is it that when editing a comment, no matter which comment I try to edit, the last one added always changes? This is my update view: class CommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = BlogComment form_class = CommentUpdateForm template_name = 'talesoflnk/blog_comment_update_form.html' def get_context_data(self, **kwargs): context = super(CommentUpdateView, self).get_context_data(**kwargs) context['blog'] = get_object_or_404(Blog, pk = self.kwargs['pk']) return context def form_valid(self, form): blog = get_object_or_404(Blog, pk=self.kwargs['pk']) form.instance.author = self.request.user form.instance.blog = blog return super(CommentUpdateView, self).form_valid(form) def get_success_url(self): return reverse('blog-detail', kwargs={'pk': self.kwargs['pk'],}) def test_func(self): comment = self.get_object() if self.request.user == comment.author: return True return False Path: path('blog/<int:pk>/comment/update', views.CommentUpdateView.as_view(), name='update_comment') And the form itself: {% extends 'base.html' %} {% block content %} <p>Post your comment for: <a href="{% url 'blog-detail' blog.pk %}">{{blog.name}}</a></p> <div class="comment-form"> <form action="" method="post"> {% csrf_token %} <table> {{form.as_table}} </table> <input type="submit", value="Save changes"> </form> </div> {% endblock content %} I've no idea what to do to be honest. I was trying to add <int:comment_pk> to my route path. But it doesn't work. -
Prepopulate ModelForm in FormView with data of another form sent to the by POST method -Django
I'm trying to prepopulate a django FormView fields with data of another form (prepatory for a meeting minute creator). I made an project simplifiying and reproducing the error for better comprehension and easier solving... You see that the body field is present in the ModelForm, but not in the preparoty form. It is that, so I can dinamically create the minute with the data entered by the user in the preparatory form. So, basically, I must fill the "body" field with initial data, that will be dynamically created after using the info the user has just posted. I can do the dynamic thing, but I can't find a way to fill the field. The president and secretary fields are automatically filled by django FormView (class based view), but the body I cannot, even overriding the initial method as above.. By the way, if I print the "initial" in the get_initial method, it is empty, although the fields are filled up... Anyone has any idea on how to solve it? I tried to override the get_initial() method, but it didn't work out. The initial form (preparatory): from django import forms from core.models import MinuteModel class MyForm(forms.Form): president = forms.CharField(widget=forms.TextInput()) secretary = … -
Django how to store data as global table
I am new to Django and got a question. So I currently use pandas.read_sql_query to query data from the database (MSSQL), I don't create the model because it's the company's database and I don't think I can do this. Please correct me if I am wrong, I may don't fully understand what model does. The table I need requires multiple query and do some data cleaning/table merge with pandas which cost over 10mins. Most of the time spend on query the data from the database. (1) Is there a way to query the data and then store it in Django somewhere as a global table? So it will save a lot of time and the table can be reused. (2) If yes, can I setting sometime to update the global data table as specific frequerncy? Thank you so much and any help is really apprecaited! -
Javascript code is not working completely
I am trying to add items to my cart thus using javascript to indicates the product and fetch api to obtain data of item. But my javascript file is somehow get stuck and not running completely . I wrote a code in my js file and if i open server inspect tab to get src code , the code is not the same . -
filter queryset with filterset for anonymous. How install exception 401 UNAuthorized
I am a beginner developer django. I do site foodgram. Here you can publish recipes, subscribe to authors, add recipes to your shopping list. I try install filtering requests for users using bu shopping_cart and favorite as filterset. But I cant to install exception for anonymous.For request /api/recipes/?is_in_shopping_cart appear all recipes. But must be error 401 Unautorized My code filter class CustomFilters(filters.FilterSet): tags = filters.ModelMultipleChoiceFilter(field_name='tags__slug', to_field_name='slug', queryset=Tag.objects.all()) author = filters.NumberFilter(field_name='author') is_favorited = filters.BooleanFilter(field_name='is_favorited', method='get_is_favorited') is_in_shopping_cart = filters.BooleanFilter( field_name='is_in_shopping_cart', method='get_is_in_shopping_cart' ) def get_is_favorited(self, queryset, name, value): user = self.request.user if (user.is_authenticated and value is True and name == 'is_favorited'): return queryset.filter(recipes_favorite_recipes__user=user) return Response(status=status.HTTP_401_UNAUTHORIZED) def get_is_in_shopping_cart(self, queryset, name, value): user = self.request.user if ( user.is_authenticated and value is True and name == 'is_in_shopping_cart' ): return queryset.filter(recipes_shopping_cart_recipes__user=user) return Response(status=status.HTTP_401_UNAUTHORIZED) class Meta: model = Recipes fields = ['tags', 'author', "is_in_shopping_cart", "is_favorited"] if I I remove the method condition in the filter and leave only Response(status=status.HTTP_401_Unauthorized) with an anonymous request, recipes still appear and an error appears on the site. I will glad any advice -
Wrong display on pythonanywhere
I am running a django app on pythonanywhere. I tested it in local and everything was working just fine without any error. However, on pythonanywhere, there is a problem on one of my pages. On it I have a button that changes the style of a part of the page (basically changing a rectangle from portrait to landscape). Everything else on that page works well, but when I click that button, nothing changes. I dig and looked at the template I'm rendering before and after clicking, the template is correctly changed, but nothing changes on the screen. I tried to reload the site from pythonanywhere and then refresh the page, the pages changes well. I'have looked at the access log, the Error log and the Server log, none shows anything indicating any error. I don't understand where the problem is. -
Django database connection with postgis automatically shutdown after serval time
My database automatically shuts down after a few hours. I'm using PostgreSQL 14 with Django 4.2.4,In django i am getting connection refused error ,When i amdcheckfor postgress status it and here's my database configuration in settings.py and PostgreSQL logs, I see the following logs: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'fight-db', 'USER': 'postgres', 'PASSWORD': 'gsdgfwtdtfw', 'HOST': '192.**********', 'PORT': '5432', } } In the PostgreSQL logs, I see the following logs: 2023-09-21 21:48:11.208 UTC [15283] LOG: received fast shutdown request 2023-09-21 21:48:11.222 UTC [15283] LOG: aborting any active transactions 2023-09-21 21:48:11.264 UTC [15283] LOG: background worker "logical replication launcher" (PID 15290) exited -
Mostly Basic Django Site on Google Cloud
I have a basic "mostly informational-only" corporate website in WordPress 6.3 and I plan on migrating it to Django 4.2 since the only one who would be editing the content would be the developer himself. Looking at these options - https://cloud.google.com/python/django - what's the best way to go about with this ? May or may not have a database - if so, it would be of low consumption like max 1GB storage for MySQL. -
Initial Value in modelForm through init
It could be that I'm trying to solve this issue the wrong way. But if someone has a good idea of how to solve this I'm all ears for it. What I want to achieve. I have a model with a Charfield, that I populate with data from a field in another model. For different reasons a ForeignField is not an option for me. So instead I define the data so select from the Init process of my model form. It works well to establish a list to pick from. I have tried to simplify the code below. class myModel(model.Models) troop = models.CharField(......) stuff = models.CharField(......) camp = models.SlugField(......) def __str__(self): return self.troop class mySecondModel(model.Models) name = models.CharField(......) other_stuff = models.CharField(......) slug = models.SlugField(......) camp = models.SlugField(......) def __str__(self): return self.slug class View_Troop(UpdateView): template_name = 'troop.html' model = myModel form_class = myModel_form def get_form_kwargs(self): id_ = self.kwargs.get('id') #//'id' = troop # obj= myModel.objects.filter(troop=id_) kwargs = super(View_Troop, self).get_form_kwargs() kwargs.update({'troop': obj.troop}) kwargs.update({'camp': obj.camp}) return kwargs class myModel_form(forms.ModelForm) stuff = ModelChoiceField(queryset= mySecondModel.objects.all()) class Meta: model = myModel fields = '__all__' def __init__(self, *args, **kwargs): troop = kwargs.pop('troop') camp = kwargs.pop('camp') variable_1= .... function based on troop value super(myModel_form, self).__init__(*args, **kwargs) self.fields['stuff'].queryset=mySecondModel.objects.filter(other_stuff__contains= variable_1, camp=camp) … -
Gateway timeout Django
Have a Django website running on a virtual machine. When I run the site locally on a virtual machine via runserver, everything works as it should. But if I run with the condition runserver 0.0.0.0:8000 (to connect from another machine in the local corporate network), then when I run heavy queries on the site (with a runtime of more than a minute with access to the Postgres database), I get a Gateway Timeout error. But the request itself is not interrupted and continues its execution. I don't understand the reason. I tried to adjust the SETTINGS by adding a TIMEOUT, and I started it from under IIS with an indication of a long TIMEOUT - the result is the same. -
Docker/Django reflects changes only once
Whenever I make a change in a template, it will be reflected on the page. Every subsequent change is ignored. When I refresh page, it "shuffles" between original and first change. I am not a pro, but it looks like something with cacheing? I am not aware of caching anything though. version: '3.7' services: web: container_name: web build: . restart: always command: ["/wait-for-it.sh", "db:5432", "--", "gunicorn", "--bind", "0.0.0.0:8000", "--workers", "3", "mysite.wsgi:application"] volumes: - .:/app - static_files:/app/staticfiles - media_files:/app/media expose: - 8000 env_file: .env depends_on: - db nginx: container_name: nginx restart: always image: nginx:stable-perl volumes: - static_files:/app/staticfiles - media_files:/app/media - ./nginx/user_conf.d/:/etc/nginx/conf.d/ ports: - "80:80" depends_on: - web - db db: container_name: db image: postgres:13 restart: always volumes: - postgres_data:/var/lib/postgresql/data/ - ./db_backup:/app/db_backup/ env_file: .env pgadmin: container_name: pgadmin4_container image: dpage/pgadmin4 restart: always environment: PGADMIN_DEFAULT_EMAIL: mail PGADMIN_DEFAULT_PASSWORD: pw ports: - "5050:80" depends_on: - db volumes: - pgadmin:/var/lib/pgadmin volumes: postgres_data: static_files: media_files: pgadmin: db_backup: -
How to give a result to a html page in python
I have a Django project setup and an HTML page in this project that is asking for a password, and a Python code that is checking that password to validate it, the two are connected, and the password is sent with the GET method and my question is how to respond to the password, after it was checked with valid or invalid depending on the case and how to integrate that response in my page -
ValueError: Field 'id'
When I POST new email i send this request, sender and receiver should represent registered users... i get this error ValueError: Field 'id' expected a number but got '<django.db.models.query_utils.DeferredAttribute object at 0x10291f410>'. I try to delete the migrations and the db.sqlite3 file several times, and run makemigrations & migrate commend but it didn't work. I'm new to Django...So so sorry if i'm not in the right direction at all. I would appreciate any help, thanks { "sender": "test1@gmail.com", "receiver": "test2@gmail.com", "subject": "Hello", "message": "bbaa aaafff jjjj fslskjf adjfjfj dkdklfwl lfewjro fjklsfjl dddkkc "unread": true } models.py class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): email = self.normalize_email(email) user = self.model( email=email, **extra_fields ) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) # is_staff -> controls whether the user is allowed to log in to the admin interface. if extra_fields.get("is_staff") is not True: raise ValueError("Superuser has to have is_staff attribute set to True.") # is_superuser -> have access to create, edit, and delete any object (models). if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser has to have is_superuser attribute set to True.") return self.create_user(email=email, password=password, **extra_fields) class User(AbstractUser): email = models.EmailField(max_length=80, unique=True) username = models.CharField(max_length=50) objects = CustomUserManager() … -
Django framework - makemigrations - no changes detect
In my Django project, when I am running the makemigrations command, it shows no changes detected. I have also updated my settings.py file. It is still facing the same issue, and I tried writing , but it still isn't working. I'm attaching some screenshots here.enter image description here I'm attaching an another ss i want that output. -
Django how to update price of an item if that item existed or save that item to database if not
My models: class Product(models.Model): name = models.CharField(max_length=200) current_price = models.CharField(max_length=50) place = models.CharField(max_length=50) url = models.CharField(max_length=50) img = models.CharField(max_length=50) date_add = models.DateTimeField(default=timezone.now) def __str__(self): return self.name My codes: def cellphones(query): lists = [] search = query.replace(' ', '%20') url = f"https://cellphones.com.vn/catalogsearch/result?q={search}" driver.get(url) content = driver.find_element( By.CSS_SELECTOR, "div[id*='search-catalog-page']") items = content.find_elements( By.CSS_SELECTOR, "div[class*='product-info']") for _ in items: item = Item( url=_.find_element(By.CSS_SELECTOR, "a").get_attribute('href'), name=_.find_element(By.CSS_SELECTOR, "h3").text, current_price=_.find_element(By.CSS_SELECTOR, "p[class*='product__price--show']").text, place="Cellphones", img=_.find_element(By.CSS_SELECTOR, "img").get_attribute('src'), date_add=datetime.datetime.now() ) if Product.objects.filter(name=item.name, place=item.place).first(): t = Product.objects.get(name=item.name, place=item.place) t.current_price = item.current_price t.img = item.img t.date_add = item.date_add t.save() else: save_to_db(item) lists.append(item) return lists save_to_db: def save_to_db(item): conn = sqlite3.connect('../db.sqlite3') c = conn.cursor() c.execute("CREATE TABLE IF NOT EXISTS products (url TEXT, name TEXT, current_price TEXT, place TEXT, img TEXT, date_add TEXT)") c.execute("INSERT INTO products VALUES (?, ?, ?, ?, ?, ?)", (item.url, item.name, item.current_price, item.place, item.img, item.date_add)) conn.commit() conn.close() I want to update the price, date add of an item if that item already exists in the database. If that item not existed, i want to add it to the database. But the item will always save to the database. I think it the same problem i have here Django objects.all() return empty queryset where Product object return empty queryset. How do … -
How to Sort a Nested List in Django Rest Framework Serializer by a Field?
This is the data I am receiving in the frontend. { id: 1, tenant_id: 73, product_channel: 2, revision_status: "Effective", cou_charges_detail_row: [ { biller_category_ref_id: 23, rate_flag: false, rate_percentage: "0.75", min_value: 1, max_value: 5000, }, { biller_category_ref_id: 18, rate_flag: false, rate_percentage: "0.30", min_value: 1, max_value: 10000, }, { .... 31 rows more }, ], } I want to send the cou_charges_detail_row sorted by biller_category_ref_id in ascending order from the backend. { id: 1, tenant_id: 73, product_channel: 2, revision_status: "Effective", cou_charges_detail_row: [ { biller_category_ref_id: 18, rate_flag: false, rate_percentage: "0.30", min_value: 1, max_value: 10000, }, { biller_category_ref_id: 23, rate_flag: false, rate_percentage: "0.75", min_value: 1, max_value: 5000, }, { .... 31 rows more }, ], } Here are relevant code snippets from my models, serializers, and views for reference. I'm seeking guidance to correctly sort the cou_charges_detail_row list. views.py class COUChargesViewSet(viewsets.ModelViewSet): queryset = CustomerOUCharges.objects.filter(is_deleted=False, is_active=True).order_by('-id') serializer_class = COUChargesSerializer def list(self, request): tenant_id = LoginSerializer.get(request.user).values_list("tenant_id", flat=True) if 'id' in self.request.GET: charges_obj = CustomerOUCharges.objects.filter(is_deleted=False,id = request.GET["id"]).exclude(revision_status='History').order_by('-id') serializer = self.get_serializer(charges_obj, many=True) return Response(serializer.data) else: charges_obj = CustomerOUCharges.objects.filter(tenant_id__in =tenant_id, is_deleted=False, is_active=True).exclude(revision_status='History').order_by('-id') serializer = COUChargesSerializer(charges_obj, many=True) return Response(serializer.data) serializers.py class COUChargesSerializer(serializers.ModelSerializer): tenant_name = serializers.CharField(source=varible_class.tenant_id_tenant_name, read_only=True) cou_charges_detail_row = COUChargesDetailsSerializer(many=True) class Meta: model = CustomerOUCharges fields = ('__all__') class COUChargesDetailsSerializer(serializers.ModelSerializer): id = … -
Delete Duplicate Rows in a huge Django DB with condition
There are several questions similar to mine but none are satisfactory. I would like to be able to remove duplicates from a DB having more than 26 million lines, therefore in the most efficient way with the condition that I want to keep the row which has the most recent update date (update_date is a field). Is it possible to use the Django ORM or do we have to use SQL in that case? Thank you in avance for your help.