Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to list by most used foreign keys in django
I have 2 models: Post and Comment as you can see below class Post(models.Model): id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, ) date = models.DateTimeField(default=datetime.now) title = models.CharField(max_length=100,) body = models.CharField(max_length=1000) class Comment(models.Model): id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False) post = models.ForeignKey(Post, on_delete=models.CASCADE, default=None, null=True, blank=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) date = models.DateTimeField(default=datetime.now) body = models.CharField(max_length=1000) I want to get the most commented posts last week so how would I list the Posts with most comments. Thanks! -
How to list product in fixed position?
Hello, I haven't been able to do this for a while. Can someone show me how how to did it? After searching for a product, is it possible for it to appear exactly in this format? this is model. class Product(BaseModel): owner = models.ForeignKey( 'account.Account', on_delete=models.CASCADE, blank=False, null=False, verbose_name=_("Owner"), ) title = models.CharField( max_length=150, help_text=_("User-friendly attribute name"), verbose_name=_("Name"), ) location = models.ForeignKey( 'tag_map.Location', on_delete=models.PROTECT, blank=True, null=True ) rank = models.IntegerField(blank=True, null=True) is_featured = models.BooleanField(default=False, db_index=True) class Tariff(BaseModel): name = models.CharField(max_length=100, verbose_name=_('Tariff Name')) duration_in_days = models.PositiveIntegerField(default=0, verbose_name='Duration in Days') duration_in_hours = models.PositiveIntegerField(default=0, verbose_name="Duration in Hours") price = models.DecimalField(default=0, max_digits=10, decimal_places=2) active = models.BooleanField(default=False) def __str__(self): return f"{self.name} ({self.duration_in_days} days, {self.duration_in_hours} hours) -- {self.price} uzs" def total_duration(self): return timedelta(days=self.duration_in_days, hours=self.duration_in_hours) class FeaturedProduct(BaseModel): product = models.OneToOneField( 'product.Product', on_delete=models.CASCADE, related_name='featureds', verbose_name=_("Product")) tariff = models.ForeignKey( 'product.Tariff', on_delete=models.PROTECT, blank=True, null=True, verbose_name="Tariff" ) start_time = models.DateTimeField(default=now, verbose_name="Start Time") end_time = models.DateTimeField(blank=True, null=True, verbose_name="End Time") def is_active(self): return now() <= self.end_time -
Custom Link on Column
I am working with django-tables2 to display some patient information on a page. I am creating the table like this: class PatientListView(tables.Table): name = tables.Column('Practice') patientid = tables.Column() firstname = tables.Column() lastname = tables.Column() dob = tables.Column() addressline1 = tables.Column() addressline2 = tables.Column() city = tables.Column() state = tables.Column() zipcode = tables.Column() class Meta: template_name = 'django_tables2/bootstrap.html' and then I am populating the table in my view with the result of an sql query like this: table = PatientListView(patients) I would like to ideally make each row of the table clickable so clicking anywhere on the table row would take me to a separate url defined by me. I would also settle for having a specific cell to click that would take me to a separate url. I have seen the linkify option, but from what I've read of the documentation it looks like linkify does redirects to django model pages, but I am not using models for this database as the database is created and managed by another application, and I am just reading and displaying that information. If django-tables2 is not the right solution for this issue I am open to hearing suggestions of other ways I can … -
get list of selected items from html form when we have two from in django app
hello i have two html from for selcting categories one for desktop view and other one for mobile view both of them have get method mt problem is in the mobile view when i select a category its work at start but when i want to select another one its not its html form for mobile view : <form action="{% url 'shop:category' %}" method="get"> {% for cat in categories %} <div class="d-flex align-items-center justify-content-between flex-wrap mb-3"> <div class="form-check"> <label for="category_{{ cat.id }}" class="form-check-label">{{ cat.name }} </label> <!-- Correctly use the same name and ensure it's an array to hold multiple values --> <input type="checkbox" name="categories" id="category_{{ cat.id }}" value="{{ cat.id }}" class="form-check-input" {% if cat.id|stringformat:"s" in selected_categories %}checked{% endif %}> </div> <div> <span class="fw-bold font-14">( {{ cat.product_numbers }} )</span> </div> </div> {% endfor %} <div class="filter-item text-center"> <button type="submit" class="btn-outline-site">اعمال فیلتر</button> </div> and this is for desktop view : <form action="{% url 'shop:category' %}"> {% for cat in categories %} <div class="d-flex align-items-center justify-content-between flex-wrap mb-3"> <div class="form-check"> <label for="colorCheck11" class="form-check-label">{{ cat.name }} </label> <label for="category_{{ cat.id }}"></label><input type="checkbox" name="categories" id="category_{{ cat.id }}" value="{{ cat.id }}" class="form-check-input"> </div> <div> <span class="fw-bold font-14">( {{ cat.product_numbers }} )</span> </div> </div> {% endfor … -
Django DRF - Accessing data from POST request forwarded through ngrok
I'm working on a Django REST framework (DRF) API that receives data forwarded from an external endpoint through ngrok. Here's the relevant view code: Python class MessageReceiver(generics.CreateAPIView): def post(self, request, org_id, channel_name): data = request.data if data: return Response( data={ "data": data }, status=status.HTTP_200_OK ) return Response(data={'message': 'No data received'}, status=status.HTTP_400_BAD_REQUEST) Use code with caution. My question is: since this is a POST request, I'm unable to access the original forwarded data directly. As I understand, POST requests require a payload to be sent along with the request. How can I effectively access and process the data within request.data in this scenario before I have to hit the endpoint again? -
Celery infinite retry pattern issue
I am using celery with AWS SQS for async tasks. @app.task( autoretry_for=(Exception,), max_retries=5, retry_backoff=True, retry_jitter=False, acks_late=True, ) @onfailure_reject(non_traced_exceptions=NON_TRACED_EXCEPTIONS) def send_order_update_event_task(order_id, data): ......... But the retry pattern is getting very much messed up when I use an integer value for the retry_backoff arg. No of tasks spawning up are getting out of control. logs: 2024-12-10 05:16:10 ERROR [1b810665-c0b1-4527-8cd9-c142f67d6605] [53285c923f-79232a3856] tasks.order_request_task - [ send_order_update_event_task] Exception for order: 700711926: Order absent 700711926, retry_count: 10 2024-12-10 05:16:10 ERROR [1b810665-c0b1-4527-8cd9-c142f67d6605] [1052f09663-c19b42589a] tasks.order_request_task - [ send_order_update_event_task] Exception for order: 700711926: Order absent 700711926, retry_count: 10 2024-12-10 05:16:10 ERROR [1b810665-c0b1-4527-8cd9-c142f67d6605] [dd021828dd-4f6b8ae6f8] tasks.order_request_task - [ send_order_update_event_task] Exception for order: 700711926: Order absent 700711926, retry_count: 10 2024-12-10 05:16:10 ERROR [1b810665-c0b1-4527-8cd9-c142f67d6605] [116bef9273-e4dbfb526b] tasks.order_request_task - [ send_order_update_event_task] Exception for order: 700711926: Order absent 700711926, retry_count: 10 2024-12-10 05:16:10 ERROR [1b810665-c0b1-4527-8cd9-c142f67d6605] [913697ae7e-d4f65d45a5] tasks.order_request_task - [ send_order_update_event_task] Exception for order: 700711926: Order absent 700711926, retry_count: 10 2024-12-10 05:16:10 ERROR [1b810665-c0b1-4527-8cd9-c142f67d6605] [d99e889882-a76718b549] tasks.order_request_task - [ send_order_update_event_task] Exception for order: 700711926: Order absent 700711926, retry_count: 10 2024-12-10 05:16:10 ERROR [1b810665-c0b1-4527-8cd9-c142f67d6605] [d99e889882-30bac3e515] tasks.order_request_task - [ send_order_update_event_task] Exception for order: 700711926: Order absent 700711926, retry_count: 10 2024-12-10 05:16:10 ERROR [1b810665-c0b1-4527-8cd9-c142f67d6605] [d7f01e5b4f-edfa22355f] tasks.order_request_task - [ send_order_update_event_task] Exception for order: 700711926: Order absent 700711926, retry_count: 10 2024-12-10 05:16:10 ERROR … -
Serializer raise exception to foreign data
I have complex selection logic for GET request, but serializer raise next exception. Got AttributeError when attempting to get a value for field crossroad_direction on serializer CrossroadDirectionRegulationSerializer. The serializer field might be named incorrectly and not match any attribute or key on the RelatedManager instance. Original exception text was: 'RelatedManager' object has no attribute 'crossroad_direction'. Direction has relationship One to One through models.ForeignKey(unique=True). Selection query create by use select_related('regulation') I added required serializers and models below. Serializers Crossroad class ReadonlyCrossroadFullDataSerializer(serializers.ModelSerializer): time_loads = CrossroadTimeLoadSerializer(many=True) sides = CrossroadSideFullDataSerializer(many=True) directions = CrossroadDirectionFullDataSerializer(many=True) class Meta: model = Crossroad fields = "__all__" CrossrodDirection class CrossroadDirectionFullDataSerializer(serializers.ModelSerializer): time_params = CrossroadDirectionTimeParamsSerializer(many=True) regulation = CrossroadDirectionRegulationSerializer(allow_null=True, default=None) class Meta: model = CrossroadDirection fields = "__all__" Regulation class CrossroadDirectionRegulationSerializer(serializers.ModelSerializer): class Meta: model = CrossroadDirectionRegulation fields = "__all__" Models CrossrodDirection class CrossroadDirection(models.Model): class Meta: constraints = ( models.UniqueConstraint( "input_point", "output_point", name="unique_crossroad_direction__input_output_points", ), ) crossroad = models.ForeignKey( Crossroad, on_delete=models.CASCADE, related_name="directions", ) input_point = models.ForeignKey( CrossroadPoint, on_delete=models.CASCADE, related_name="direction_input_point", ) output_point = models.ForeignKey( CrossroadPoint, on_delete=models.CASCADE, related_name="direction_output_point", ) probability = models.FloatField(default=1) Regulation class CrossroadDirectionRegulation(models.Model): crossroad_direction = models.ForeignKey( CrossroadDirection, on_delete=models.CASCADE, unique=True, related_name="regulation", ) cycle_duration = models.IntegerField(default=180) green_signal_phase = models.IntegerField(default=60) If I change Regulation serializer as below then crossroad serializer work successful - if there is regulation then … -
experiencing intermittent apache error AH01630
We have two different django apps running on a server (Centos7), using django manage.py runmodwsgi (python module mod_wsgi). Both apps are running fine, and have been for a few years. The odd thing we are running into is that every 10-12 days or so, we get a 403 Forbidden message in the browser. When checking the mod_wsgi apache error log (/tmp/mod_wsgi-localhost:8080:1999/error_log), there is nothing except the error below, which is triggered whenever the user unsuccessfully tries to access the app. AH01630: client denied by server configuration: /tmp/mod_wsgi-localhost:8080:1999/htdocs After receiving this error, I can see that the htdocs directory that is referenced in the error doesn't exist. Restarting the web server fixes the issue (and the htdocs directory reappears). Both apps experience this issue. Sometimes at the same time, sometimes not. Both apps otherwise run fine. We would really like to find a solution to this annoying issue. Googling this error just gives me advice on the httpd.conf file content, but I have not been able to find any help on this when the issue is intermittent the way I'm describing it here. I have plotted the date/times of the AH01630 errors, and find that this happens at an oddly regular … -
Django-tenant: Accessing tenant data in public domain
I was working on Django-tenant where I have tenant model called Appointment now I want to get the appointment of a specific tenant from the public domain but I'm having an issue when rendering it in the template class OrganizationAppointmentList(LoginRequiredMixin, TenantMixin, ListView): template_name = 'main/appointments/list_appointment.html' paginate_by = 10 def get_queryset(self): tenant_id = self.kwargs.get('pk') try: tenant = Organization.objects.get(id=tenant_id) self.schema_name = tenant.schema_name with schema_context(self.schema_name): queryset = Appointment.objects.all() return queryset except Organization.DoesNotExist: raise Http404("Tenant not found") except Exception as e: raise Http404(f"Error accessing tenant data: {e}") def paginate_queryset(self, queryset, page_size): with schema_context(self.schema_name): return super().paginate_queryset(queryset, page_size) def get_context_data(self, **kwargs): with schema_context(self.schema_name): context = super().get_context_data(**kwargs) tenant_id = self.kwargs.get('pk') context['tenant_id'] = tenant_id context['appointments'] = Appointment.objects.all() print(context['appointments']) return context In above code the print(context['appointments']) Is giving the exact data but while rendering it in template it shows LINE 1: ...app_appointment"."al_appointment_updated_at" FROM "appointme... and if I left the template empty the error does not show is it something that I'm missing?? I'm trying to get the specific tenant model data in public domain -
How can I programatically authenticate a user in Auth.js?
I have a Django application with authenticated (logged-in) users. I have another (Svelte) application using Auth.js (https://authjs.dev) for authentication, currently set up with github/facebook/linkedin. Now I want to send a user from the Django application to the Svelte application, and automagically (i) create the user in the Svelte application if they don't exist, and (ii) log them in to the Svelte application. I want the end-user experience to be like a regular redirect from one page to the other staying logged-in in both places. I'm stuck at the part where the user arrives in the Svelte application and I need to create a session. Does Auth.js have any way of doing this without going through a "provider"? -
PDF file cannot be opened, when generated with Django and WeasyPrint
I recently began trying generating PDF reports with Django and Weasyprint, but I cannot make it work somehow. I already have file upload, file download (even PDFs, but already generated ones that were uploaded), CSV generation and download, XLSX generation and download in my application, but I'm not able to return PDFs generated with WeasyPrint so far. I want my users to be able to create reports, and they'll be saved for further new download. So I created this basic model : from django.db import models class HelpdeskReport(models.Model): class Meta: app_label = "helpdesk" db_table = "helpdesk_report" verbose_name = "Helpdesk Report" verbose_name_plural = "Helpdesk Reports" default_permissions = ["view", "add", "delete"] permissions = [ ("download_helpdeskreport", "Can download Heldpesk Report"), ] def _report_path(instance, filename) -> str: return f"helpdesk/reports/{instance.id}" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100, unique=True) file = models.FileField(upload_to=_report_path) Since I use service classes, I also did : import uuid from io import BytesIO from django.core.files import File from django.template.loader import render_to_string from weasyprint import HTML class HeldpeskReportService: def create_report(self) -> HelpdeskReport: report_name = f"helpdesk_report_{uuid.uuid4().hex}.pdf" html_source = render_to_string(template_name="reports/global_report.html") html_report = HTML(string=html_source) pdf_report = html_report.write_pdf() # print("check : ", pdf_report[:5]) # It gives proper content beginning (PDF header) pdf_bytes = BytesIO(pdf_report) pdf_file = … -
Forms not displaying properly when using django with tailwind and crispy forms
When using {{ form|crispy}} filter in the index.html file, the form input fields are not shown with borders as they should be when using Crispy Forms. I have followed the BugBytes YouTube video TailwindCSS and Django-Crispy-Forms - Template Pack for Django Forms! I am looking for help with getting the Crispy filter working with a Django form. Here is the html page Here is the html page I am using Django 5.1.4 with crispy-tailwind 1.03 and django-crispy-forms 2.3 using python 3.12.8 The output css files are being built correctly and referenced in the html. This is demonstrated by using tailwind styles in the (template) html files. I am using Pycharm as my IDE. I have created a Django based project with a virtual environment included in the project directory. Node.js has been installed. The following are command line instructions and excerpts are from relevant files (apologies for it being so long ...): Setup commands run from the .venv npm install -D tailwindcss npx tailwindcss init npx tailwindcss -i ./static/css/input.css -o ./static/css/style.css --watch The last command is used to create and update the tailwind stylesheet. package.json "devDependencies": { "tailwindcss": "^3.4.16" } tailwind.config.js (entire file) /** @type {import('tailwindcss').Config} */ module.exports = { … -
How to import stripe? [closed]
I am trying to import stripe library into my Django app but it says << stripe is not accessed >> I installed it correctly, I activated my virtual environment, I use python -m pip install stripe, I use pip install too. I use pip list command and it's in my list. There is no name conflict or anything else but still when I do << import stripe >> I have the problem I mentioned. virtual environment is activated : pip install stripe pip install stripe== version python -m pip install stripe pip list -
I'm developing a web application using django and ajax for checklist. I have total of 140 checklist
I'm developing a web application using django and ajax for checklist. I have total of 140 checklist each checklist have header(meta data about that particular checklist), body of the checklist, and signature footer where certain users can click the ticket box and close the checklist. These 140 checklist are of 28 different types with different structures. Now I stored that each checklist as json data and created different templates and views for each types. Is it good way or is there any other better way to do this.. I'm a new developer and I can't get satisfied with my approach to this solution like there is a better solution. As I'm a new developer. Even though I can get solution to my problems but there is a feeling that is not the best solution until I get the best solution I can't get satisfied with this approach -
Faster table of content generation in Django
I am trying to make a table of content for my queryset in Django like this: def get_toc(self): toc = {} qs = self.get_queryset() idx = set() for q in qs: idx.add(q.title[0]) idx = list(idx) idx.sort() for i in idx: toc[i] = [] for q in qs: if q.title[0] == i: toc[i].append(q) return toc But it has time complexity O(n^2). Is there a better way to do it? -
How to mirror a container directory on the host?
All I want is to be able to read a directory of my container from my host machine. I.e., a symlink from my host machine to the container's directory, and I don't require anything more than read permissions. I have tried many different methods: services: django: volumes: - /tmp/docker-django-packages:/usr/local/lib/python3.12/site-packages Problem: /tmp/docker-django-packages is not created if it doesn't exist, but there is no docker error, however no python packages can be resolved by the container's python process. If I manually make /tmp/docker-django-packages on the host, then I still get the same error. services: django: volumes: - type: bind source: /tmp/docker-django-packages target: /usr/local/lib/python3.11/site-packages bind: create_host_path: true Problem: /tmp/docker-django-packages is not created. If I make it manually, it is not populated. The container behaviour is not affected at all. services: django: volumes: - docker-django-packages:/usr/local/lib/python3.11/site-packages volumes: docker-django-packages: driver: local driver_opts: type: none o: bind device: "/tmp/docker-django-packages" Problem: host directory not created if it doesn't exist, not populated if it already exists, and the container functions as normal services: django: volumes: - type: volume source: docker-django-packages target: /usr/local/lib/python3.11/site-packages volumes: docker-django-packages: driver: local driver_opts: type: none o: bind device: "/tmp/docker-django-packages" Problem: host directory not created, nor populated, container yet again functions as if these lines weren't … -
Why this inner atomic block not rolled back in a viewflow custom view code
I created this custom create process view to add in logged in user's email to the saved object, I also added a transaction block so that when the next step fails (inside self.activation_done() statement) it will roll back the db changes inside form_valid() and then display the error in the start step, so no new process instance is saved. from django.core.exceptions import ValidationError from django.db import transaction from django.http import HttpResponseRedirect from viewflow.flow.views import CreateProcessView, StartFlowMixin class StarterEmailCreateProcessView(CreateProcessView): """ Sets the user email to the process model """ def form_valid(self, form, *args, **kwargs): """If the form is valid, save the associated model and finish the task.""" try: with transaction.atomic(): super(StartFlowMixin, self).form_valid(form, *args, **kwargs) # begin of setting requester email # https://github.com/viewflow/viewflow/issues/314 self.object.requester_email = self.request.user.email self.object.save() # end of setting requester email self.activation_done(form, *args, **kwargs) except Exception as ex: form.add_error(None, ValidationError(str(ex))) return self.form_invalid(form, *args, **kwargs) return HttpResponseRedirect(self.get_success_url()) Based on Django documentation, exception raised inside the transaction is rolled back However, upon form displays the error message, new process instances are still saved, so I suspect the transaction is not rolled back and I don't know why. -
How to authorize a Gmail account with Oauth to send verification emails with django-allauth
So from 2025 less secure apps are going to be disabled and i can't figure out how to integrate gmail account with django-allauth anymore in order to send verification emails. I have OAuth consent screen and credentials, Client_id, Client_secret but i don't understand how can I use this gmail account with django. I know i lack code here, but literally didn't get anywhere other than creating an account in google console and activating OAuth/Credentials. Been searching for any guide online but they are all using less secure apps. Tried something with https://docs.allauth.org/en/dev/socialaccount/providers/google.html but not even sure if this has anything to do with logging in an account into the app and sending emails using that account -
Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at dashboard/:110:27 django python
i am working on a chart that shows data on the dashbord. it's taking the data from the db and trying to make a json from that but in the html code it's not working. showing Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse () this is the view def dashboard(request): mood_data = MentalHealthSurvey.objects.values( 'mood').annotate(count=Count('mood')) stress_data = MentalHealthSurvey.objects.values( 'stress_level').annotate(count=Count('stress_level')) # Serialize data for JavaScript mood_data_json = json.dumps(list(mood_data)) stress_data_json = json.dumps(list(stress_data)) context = { 'mood_data_json': mood_data_json, 'stress_data_json': stress_data_json, } return render(request, 'employees/dashboard.html', {'context': context}) this is the template code. {% extends 'employees/base_generic.html' %} {% block title %} Employee Dashboard {% endblock %} {% block content %} <div class="container"> <h2>Survey Data</h2> <canvas id="moodChart"></canvas> <canvas id="stressChart"></canvas> </div> {% endblock %} {% block scripts %} <script> const moodData = JSON.parse('{{ mood_data_json|safe }}') console.log('moodData:', moodData) const stressData = JSON.parse('{{ stress_data_json|safe }}') const moodLabels = (moodData || []).map((item) => item.mood || 'Unknown') const moodCounts = (moodData || []).map((item) => item.count || 0) const stressLabels = (stressData || []).map((item) => item.stress_level || 'Unknown') const stressCounts = (stressData || []).map((item) => item.count || 0) const moodChart = new Chart(document.getElementById('moodChart'), { type: 'pie', data: { labels: moodLabels, datasets: [ { data: moodCounts, backgroundColor: ['#28a745', '#ffc107', '#dc3545', '#17a2b8', '#6f42c1'] … -
React Flow Edges Not Displaying Correctly in Vite Production Mode with Django Integration
I am developing a Django website and encountered an issue while integrating React Flow UI into one of the apps. The frontend of the site was previously written entirely in pure HTML, CSS, and JavaScript, so I am new to React. I needed to generate a React Flow canvas and pass it to a Django template. Using Vite to bundle the React app, I successfully implemented this, but I encountered a problem: in production mode (after building with npx vite build), the CSS behavior differs from development mode (running with npx vite dev). In development mode, styles render correctly. However, in the production version, styles work only partially — specifically, edges between nodes (react-flow__edge-interaction) are not displayed. Problem In production mode, React Flow edges (react-flow__edge) are not displayed, and their CSS classes only partially work. In development mode, everything functions correctly. Video with an example of the problem: click Project structure Standard files/directories for Django and React apps are omitted for brevity: <app_name>/ ├── templates/ │ └── <app_name>/ │ └── reactflow_canvas.html ├── static/ │ └── reactflow-frontend/ | ├── dist/ (dir with build files (index.css and index.js) │ ├── src/ │ │ ├── App.jsx │ │ ├── App.css │ │ ├── … -
Django : 'empty_form' is not used in polymorphic formsets, use 'empty_forms' instead
I am newbie at Python/Django i have been charged to migrate old project from Python 3.7 / Django 2.2.5 to the Python 3.12 and Django 5.1 but when i did this some functionality didn't work now . For exemple before i have in the Admin interface when i click on "Add watcher" i can create watcher and in the same page choose the realted Trigger, Indicator and other staff. But in my new version when i choose Add Watcher i have this error : RuntimeError at /admin/watchers/watcher/add/ 'empty_form' is not used in polymorphic formsets, use 'empty_forms' instead. I am using the last version of django-polymorphic, nested-admin from polymorphic.admin import PolymorphicParentModelAdmin, PolymorphicChildModelAdmin, PolymorphicInlineSupportMixin import nested_admin from django.db import transaction from watchers.models import * class TriggerInline(nested_admin.NestedStackedPolymorphicInline): model = apps.get_model('triggers', 'Trigger') child_inlines = tuple([type(f'{subclass.__name__}Inline', (nested_admin.NestedStackedPolymorphicInline.Child,), { 'model': subclass, 'inlines': [ TriggerComponentInline] if subclass.__name__ == "CompositeTrigger" else [] }) for subclass in apps.get_model('triggers', 'Trigger').__subclasses__()]) #Same that TriggerInline class IndicatorInline(nested_admin.NestedStackedPolymorphicInline) class WatcherChildAdmin(PolymorphicChildModelAdmin): base_model = Watcher inlines = (IndicatorInline, TriggerInline,) #Other infos #Register subclass for subclass in Watcher.__subclasses__(): admin_class = type(f'{subclass.__name__}Admin', (nested_admin.NestedPolymorphicInlineSupportMixin,WatcherChildAdmin,), { 'base_model': subclass, 'exclude': ['periodicTask', ], }) admin.site.register(subclass, admin_class) @admin.register(Watcher) class WatcherParentAdmin(PolymorphicInlineSupportMixin, PolymorphicParentModelAdmin): base_model = Watcher child_models = tuple(Watcher.__subclasses__()) #Other Functions Both Trigger and … -
How to create a "Bulk Edit" in Django?
I would like to create a bulk edit for my Django app, but the problem is that I don't get the function to work. I got lost at some point while creating it, and don't know what I am doing wrong. I feel sruck at this point, I don't see other options. Here is what I have done so far (I am using airtable as the database): The error is mostly when it tryies to retrieve the products from the tables after being selected with the checkbox (I tried to debug it, and change it but I don't see what else I could do) models.py from django.db import models class RC(models.Model): sku = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) cost = models.DecimalField(max_digits=10, decimal_places=2) weight = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name class Category(models.Model): sku = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=255) category = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name class LB(models.Model): sku = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=255) cost = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name class PM(models.Model): sku = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=255) cost = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators … -
Split queryset into groups without multiple queries
How can I retrieve a ready-made queryset divided into two parts from a single model with just one database hit? For example, I need to fetch is_featured=True separately and is_featured=False separately. I tried filter function of python but I want to do it alone with query itself is that possible. I want to add 2 featured and 8 organic products on one page. In general, is it correct to divide them into two groups, bring them in, and then set the correct position for each? p = Product.objects.all() featured_products = filter(lambda p: p.is_featured, p) list(featured_products) [<Product: Nexia sotiladi | 2024-12-06 | -20241206>, <Product: Nexia sotiladi | 2024-12-06 | -20241206>` these are is_featured=True -
Configuring Celery and its progress bar for a Django-EC2(AWS)-Gunicorn-Nginx production environment
I am trying to implement a Celery progress bar to my Django website, which is now on the Web via AWS EC2, Gunicorn, and Nginx, but I simply cannot get the Celery progress bar to work. The bar is supposed to come on after the visitor clicks the submit button, which triggers a process that is run by Celery and feedback on progress is fed to the frontend via Celery Progress Bar. Celery fires up initially, but then flames out if I hit the submit button on my website, and never restarts until I manually restart it. Below is the report on the Celery failure: × celery.service - Celery Service Loaded: loaded (/etc/systemd/system/celery.service; enabled; preset: enabled) Active: failed (Result: timeout) since Mon 2024-12-09 15:14:14 UTC; 6min ago Process: 68636 ExecStart=/home/ubuntu/venv/bin/celery -A project worker -l info (code=exited, status=0/SUCCESS) CPU: 2min 51.892s celery[68636]: During handling of the above exception, another exception occurred: celery[68636]: Traceback (most recent call last): celery[68636]: File "/home/ubuntu/venv/lib/python3.12/site-packages/billiard/pool.py", line 1265, in mark_as_worker_lost celery[68636]: raise WorkerLostError( celery[68636]: billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 15 (SIGTERM) Job: 0. celery[68636]: """ celery[68636]: [2024-12-09 15:14:13,435: WARNING/MainProcess] Restoring 2 unacknowledged message(s) systemd[1]: celery.service: Failed with result 'timeout'. systemd[1]: Failed to start celery.service - Celery Service. … -
Django cant access variable from form created with ModelForm
I am trying to create a simple form based on ModelForm class in Django. Unfortunately I keep getting UnboundLocalError error. I checked numerous advises on similar issues, however it seems I have all the recommendations implemented. If I run the below code, I get following error: UnboundLocalError: cannot access local variable 'cook_prediction' where it is not associated with a value My models.py: from django.db import models class RecipeModel(models.Model): i_one = models.BigIntegerField(default=0) v_one = models.FloatField(default=0) My forms.py: from django import forms from .models import RecipeModel class RecipeInputForm(forms.ModelForm): class Meta: model = RecipeModel exclude = [] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['i_one'].initial = 0 self.fields['v_one'].initial = 0 My views.py: from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.decorators import login_required from . import forms @login_required def index(request): if request.method == 'POST': recipe_form = forms.RecipeInputForm(request.POST) else: recipe_form = forms.RecipeInputForm() if recipe_form.is_valid(): cook_prediction = recipe_form.cleaned_data if recipe_form.is_valid() == False: print("Recipe form is not valid!") After running the code, except for the above mentioned error message, I also get the Recipe form is not valid! printout from the last line of views.py. How to get rid of this error and successfully get variable from form based on ModelForm?