Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I add Daisy UI plugin to my django project? If yes , Please how do I do it?
I have already installed tailwind CSS to my django project and it works just fine, I tried using the documentation procedure I saw at the daisyui website npm i daisyui and I also added the plugin to my tailwin.config.js file also module.exports = { //... plugins: [require("daisyui")], } -
How to integrate drill-down chart in django using plotly python?
I have some basic knowledge of django python and I am using Django, and how to integrate drill-down charts in Django using Plotly python. I watched many online tutorials but it gives demos of all flasks app. Can you share some tutorials and others links or demo working examples? Thanks in advance. I have tried this demo : Drill through bar chart Dash plotly, but this demo is in flask app. Can you share some useful code or links for how to convert this flask code to django code in python. -
pop method for Django queryset?
I am having a data model where the model contains a members field to relate to objects of the same type. the idea is that each objects can also be a group of objects. Groups can contain groups etc. class MyObject(CommonModel): name = models.CharField(max_length=255, unique=False, null=True, blank=True) members = models.ManyToManyField("self", blank=True, symmetrical=False) For a search with Django-filters I need to perform a recursive search to get all items, but also all parent group items. So I wrote this little helper function that take a query set from a previous search(by name for example) and gives back a queryset that contains all items where one of the items in the querste is in a member. def recursive_objects_member_filter(queryset): """Takes a queryset and retruns a queryset of all parent objects""" query_set_result = [] while queryset: query_item = queryset.pop() query_set_result.append(query_item) members_queryset = MyObject.objects.filter(members=query_item).exclude(id = query_item.id ) for member in members_queryset: queryset.append(member) return query_set_result My problem is that there does not seem to be a function to remove an item from a queryset like pop(). -
Get cumsum from aggregated field with Django orm
In my project, I want to get the sum of an "amount" field which comes form an aggregate. I've read some posts on this but I can't find a way to achieve what I want. Example model: class ScheduledOperation: day = models.dateField() amount = models.DecimalField(...) Example queryset {'day': datetime.date(2023, 2, 7), 'amount': Decimal('-500.00')} # same day each month {'day': datetime.date(2023, 2, 7), 'amount': Decimal('1500.00')} # same day each month {'day': datetime.date(2023, 3, 7), 'amount': Decimal('-500.00')} {'day': datetime.date(2023, 3, 7), 'amount': Decimal('1500.00')} {'day': datetime.date(2023, 4, 7), 'amount': Decimal('-500.00')} {'day': datetime.date(2023, 4, 7), 'amount': Decimal('1500.00')} {'day': datetime.date(2023, 5, 7), 'amount': Decimal('-500.00')} {'day': datetime.date(2023, 5, 7), 'amount': Decimal('1500.00')} {'day': datetime.date(2023, 5, 8), 'amount': Decimal('-4000.00')} # big op here Where I am so far ScheduledOperation.objects.order_by('day').values('day').annotate(day_tot=Sum('amount')) gives me the total amount for each day: {'day': datetime.date(2023, 2, 7), 'day_tot': Decimal('1000')} {'day': datetime.date(2023, 3, 7), 'day_tot': Decimal('1000')} {'day': datetime.date(2023, 4, 7), 'day_tot': Decimal('1000')} {'day': datetime.date(2023, 5, 7), 'day_tot': Decimal('1000')} {'day': datetime.date(2023, 5, 8), 'day_tot': Decimal('-4000')} What I want {'day': datetime.date(2023, 2, 7), 'day_tot': Decimal('1000'), 'cumul_amount':Decimal('1000')} {'day': datetime.date(2023, 3, 7), 'day_tot': Decimal('1000'), 'cumul_amount':Decimal('2000')} {'day': datetime.date(2023, 4, 7), 'day_tot': Decimal('1000'), 'cumul_amount':Decimal('3000')} {'day': datetime.date(2023, 5, 7), 'day_tot': Decimal('1000'), 'cumul_amount':Decimal('4000')} {'day': datetime.date(2023, 5, 8), 'day_tot': Decimal('-4000'), 'cumul_amount':Decimal('0')} What I tried … -
Python script for MySQL DB backup
I'm trying to create a Python script to make a backups for MySQL DB. (I have a Django-REST app with MySQL DB wrapped in Docker compose) The script should make backuos and send in to Disk API. It accept parameters: db name user name user password API parameters for working with Disk API There sholud be a simple function in the script. I think I'll just add it to cron (linux task scheduler) and it will run once a week, for example. The function have to create a DB backup and send it via the API to yandex disk. So, these are my thoughts, but I never made smth like this. I will be very grateful for links or examples of such a script. -
Django Postgres Database Migration
I have an access database with two tables, members and residential areas, I'm using a tool to migrate the tables from access to postgres on railway.app. The problem is, when i run migrations from django, i get a relationship doesn't exist error. (I have a foreign key attribute in members referencing residential areas because each member is linked to a residential area. I understand this is happening because when the data gets to postgres, it doesn't have a unique ID fields(the auto-generated ID from django), I've tried using custom fields as primary keys but nothing seems to work. Anyone with an idea how I can solve this issue? -
How to render an arbitrary set of key->value pairs from a JSONField in a Jinja2 template?
I'm trying to add debug information to a frontend; for reasons that don't need to be gone into at the moment I'm storing the pertinent information in a JSONField. Storing and retrieving the information works correctly, but when I try to render it via J2 to the page it's supposed to be at I'm running into some issues. Here's the segment in question: {% for log in connection.debug_logs.all %} <tr> <td></td> <td>{{ log.log_message }}</td> <td> {% for key in log.log_data %} {{ key }}: {{ log.log_data.key }} <br/> {% endfor %} </td> </tr> {% endfor %} What I'm hoping for is for that to produce a series of lines of key: value. What I'm getting instead is: <td>Login requested by vmx1.internal (11.22.33.44)</td> <td> Framed-Route: <br/> Service-Type: <br/> Framed-IP-Address: <br/> Framed-IPv6-Route: <br/> control:Auth-Type: <br/> Framed-IPv6-Prefix: <br/> Delegated-IPv6-Prefix: <br/> ERX-Egress-Policy-Name: <br/> ERX-Ingress-Policy-Name: <br/> ERX-Virtual-Router-Name: <br/> control:Cleartext-Password: <br/> </td> Using {{ log.log_data | pprint }} does yield the keys and values, but renders them as a plaintext JSON string which gets flattened by the html renderer and isn't terribly useful for debugging purposes. Trying 'log.log_data[key]' instead yields a 'Could not parse the remainder' error. I've tried the suggestions in this question as well … -
How to merge pdf files using python without storing them into the local directory
I have some pdf files which are uploaded on a remote server. I have URL for each file and we can download these PDF files by visiting those URLs. My question is, I want to merge all pdf files into a single file (but, without storing these files into local directory). How can I do that (in python module 'PyPDF2')? -
what Gunicorn worker configuration is required for long running sql queries inside Api to parallely process requests. Currently requests are in queue
I am using gunicorn for our django web app. my api is mostly waiting for response from db as sql query take much time. So api most of api calls generally takes greater that 1 minutes. Due to this other requests/api calls are stuck in queue. What worker class, no. of workers and threads shall I use in gunicorn conf to address this issue. -
AttributeError: 'QuerySet' object has no attribute 'model'
I want to add documentation for the Django app I use rest_framework_mongoengine, rest_framework OpenAPI 3.0, drf-spectacular swagger [that is model : ] (https://i.stack.imgur.com/49ynm.png) [that is serializer :] (https://i.stack.imgur.com/kfgTd.png) [that is views] (https://i.stack.imgur.com/5ehJL.png) I created documentation but when I execute any endpoint in documentation this error happens [documentation] (https://i.stack.imgur.com/PqdeR.png) "AttributeError: 'QuerySet' object has no attribute 'model'" anyone can help me to solve this problem -
How to upload a video in chunks Django
Im using Cloudflare, and it has a POST request limit of 100M and I want to upload larger files, how to bypass this? I was thinking to upload in chunks but i have no idea how. -
Enabling CSRF for Django
I have the following python code in my Django views.py, the code takes in a JSON body and send the extracted DATA to another API endpoint, I have simplified the code here. How do I enable csrf such that it will send the token back to the caller for this method? I am calling this from postman. @csrf_protect def validate_booking(request): if request.method != "POST": return HttpResponseServerError("Invalid HTTP method") body = json.loads(request.body) booking_details = body["booking_details"] DATA = { "name": booking_details["name"], "nric": booking_details["nric"], "booking_id": booking_details["booking_id"] } return HttpResponse(status="200") This site directs to put this piece of code in my method. But what is "a_template.html"? https://docs.djangoproject.com/en/4.1/ref/csrf/ @csrf_protect def my_view(request): c = {} # ... return render(request, "a_template.html", c) -
why web page is not showing in full page while upgrading to bootstrap 4.1.3 and jquery 3.6
I am trying to upgrade the Bootstrap version to 4.1.3 and jQuery to 3.6 . But the page is not showing in full screen, it shows in the middle of the screen or we can say the page is broken. Here the code uses some Django formatting. Html code: {% load static %} <!DOCTYPE html> <html lang="en"> <head> {% block head %} {% block meta %} <link rel="icon" href="{% static '/images/logo.jpg' %}"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!-- Meta, title, CSS, favicons, etc. --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% endblock meta %} <title>Portal {% block title %}{% endblock title %}</title> {% block stylesheets %} <link rel="stylesheet" href='{% static "/login-assets/bower_components/bootstrap/dist/css/bootstrap.min.css" %}'> <!--Bootstrap--> <link rel="stylesheet" href='{% static "/vendors/datatables.net-buttons-bs/css/buttons.bootstrap.min.css" %}'> <!-- Theme style --> <link rel="stylesheet" href='{% static "/login-assets/dist/css/AdminLTE.css" %}'> <!-- Custom Login style --> <link rel="stylesheet" href='{% static "/login-assets/dist/css/custom-login.css" %}'> <!-- Font Awesome --> <link rel="stylesheet" href='{% static "/vendors/font-awesome/css/font-awesome.min.css" %}'> <link rel="stylesheet" href='{% static "/vendors/font-awesome/css/font-awesome-animation.css" %}'> <link href='{% static "/vendors/sweetalert/css/sweetalert2.min.css" %}' rel="stylesheet"> <style> body { width: 100%; min-height: 100%; display: -webkit-box; display: -webkit-flex; display: -moz-box; display: -ms-flexbox; display: flex; flex-wrap: wrap; justify-content: center; align-items: center; padding: 15px; background-image: url("/static/images/login_background.jpg"); background-position: center; background-repeat: no-repeat; background-size: cover; } #particles-js{ width: … -
Proeblem when creating Django app in digitalocean
I'm trying to create django app using github as a repository (all accesses granted) but just after clicking next button it says no component detected please help to solve this issue . p.s. I see someone already asked this question but no one answered properly i hope this time someone will help us.. I tried all possible ways, my settings properly created for deploying to server -
Why does django not hit the database when we try to access queryset object attributes?
Knowing that QuerySets are lazy, and a db query is made only when we try to access the queryset, I noticed that a db query is not made even if we iteratively try to access queryset object attributes (however, a query is made when we try to access the object itself). So a sample example for demonstration purposes. from django.db import connection, reset_queries reset_queries() tests=Test.objects.filter(is_test=True) print(len(connection.queries)) # returns 0 for obj in tests: print(obj.id) print(obj.is_test) print(len(connection.queries)) # returns 0 again The attributes are correctly printed, but how can they if it shows that a no query was made? Again if we do print(obj) instead, a query will be made. Any explanation is appreciated. -
i want to add list of many to many field in api results
searched_data = FormData.objects.filter(organizatio_name__icontains=query,organization_category__category__icontains=organization_category).values('state_of_products__state','country__country_name','organizatio_name','organization_contact_details','organization_email','organization_telephone','organization_address','organization_website','organization_contact_person','organization_contact_person_name','organization_contact_person_email','organization_contact_person_telephone','organization_contact_person_designation','organization_category__category','products_and_services__name','mineral_type__type','capacity','business_size__size','no_of_male','no_of_female','organization_capacity','organization_age__age','business_registration__name','market_localization__name','market_status','market_negotiation') model.py country = models.ForeignKey(Country,on_delete=models.CASCADE) organizatio_name = models.CharField(max_length=50) organization_contact_details = models.CharField(max_length=50) organization_email = models.CharField(max_length=50) organization_telephone = models.CharField(max_length=50) organization_address = models.CharField(max_length=50) organization_website = models.CharField(max_length=50) organization_contact_person = models.CharField(max_length=50) organization_contact_person_name = models.CharField(max_length=50) organization_contact_person_email = models.CharField(max_length=50) organization_contact_person_telephone = models.CharField(max_length=50) # coma seperated string of numbers organization_contact_person_designation = models.CharField(max_length=50) organization_category = models.ForeignKey(OrganizationCategory,on_delete=models.CASCADE ) products_and_services = models.ManyToManyField(ProductAndServices) state_of_products = models.ForeignKey(StateofProducts,on_delete=models.CASCADE) mineral_type = models.ForeignKey(MinaralType,on_delete=models.CASCADE) capacity = models.IntegerField() business_size = models.ForeignKey(BusinessSize,on_delete=models.CASCADE) no_of_male = models.IntegerField() no_of_female = models.IntegerField() organization_capacity = models.FloatField() organization_age = models.ForeignKey( OrganizationAge ,on_delete=models.CASCADE) business_registration = models.ForeignKey( BusinessRegistration ,on_delete=models.CASCADE) market_localization = models.ForeignKey( Marketlocalization ,on_delete=models.CASCADE) market_status = models.CharField(max_length=50) market_negotiation = models.BooleanField() { "state_of_products__state": "state of product", "country__country_name": "india", "organizatio_name": "demo", "organization_contact_details": "123", "organization_email": "demo@gmail.com", "organization_telephone": "123", "organization_address": "demo", "organization_website": "demo", "organization_contact_person": "demoperson", "organization_contact_person_name": "demopersonname", "organization_contact_person_email": "demo@gmaIl.com", "organization_contact_person_telephone": "12325645", "organization_contact_person_designation": "destination", "organization_category__category": "demo", "mineral_type__type": "minral", "capacity": 5, "business_size__size": "100", "no_of_male": 5, "no_of_female": 5, "organization_capacity": 5.0, "organization_age__age": "50", "business_registration__name": "demo", "market_localization__name": "location", "market_status": "5", "market_negotiation": false }, i need list in "organization_category__category -
How to target multiple ids with HTMX hx-target
I have a dynamic form in my Django project which have 3 form fields And i want to clear other form fields when im changing first form field but hx-target working only for one id and i dont rly know how, i was trying hx-swap-oob but nothing changed i suppose to target all ids if i change first form field, using widget_tweaks package as well template.html <div class="mt-3"> {{ form.contractor_counter.label_tag }} {% render_field form.contractor_counter class='form-select mt-2' autocomplete='off' hx-get='/objects/' hx-trigger='change' hx-target='#id_contractor_object' %} </div> <div class="mt-3"> {{ form.contractor_object.label_tag }} {% render_field form.contractor_object class='form-select mt-2' autocomplete='off' hx-get='/sections/' hx-trigger='change' hx-target='#id_contractor_section' %} </div> <div class="mt-3"> {{ form.contractor_section.label_tag }} {% render_field form.contractor_section class='form-select mt-2' autocomplete='off' hx-swap-oob='true' %} </div> -
Run the celery tasks automatically every day at a particular time in python
Here i am using python 3.7 and django 3.0 I want to run a celery task every day at 11:30 Here is my settings.py CELERYBEAT_SCHEDULE = { 'create_auto_capacity': { 'task': 'crm.tasks.create_auto_capacity', 'schedule': crontab(minute='30', hour='11') }, } Here is my crm/tasks.py @celery_app.task() def create_auto_capacity(): production_settings = ProductionSettings.objects.all() client_id = [] for i in production_settings: client_id.append(i.client.id) client = '' for id in client_id: client = Client.objects.get(id=id) process = ProductionProcess.objects.filter(is_deleted=False,client=client) capacity = ProductionCapacity.objects.filter(client=client).last() capacity_last_date = capacity.date for i in production_settings: c_time = [] work_time = WorkTime.objects.filter(client=client,day_type='Weekdays').values_list('total_time',flat=True) for j in work_time: try: t = datetime.datetime.combine(capacity_last_date.min, j) - datetime.datetime.min except: t = datetime.combine(capacity_last_date.min, j) - datetime.min x = isinstance(t, timedelta) y = t.total_seconds() / 60 c_time.append(y) g = sum(c_time) capacity = g * i.num_of_people remaning_time = g * i.num_of_people ProductionCapacity.objects.create(client=client,date=capacity_last_date, production_process=i.production_process,number_of_people=i.num_of_people, capacity=capacity,remaning_time=remaning_time,manual_add=False) I want to run this code(crm/tasks) daily at 11:30 but this is not working -
Python framework will be best for job portal website
Recently we started working on a job portal website as i am not from the technical background please someone guide in what sought of python framework we can use for job portal Moreover it would be really helpful if someone can help me in selecting the whole technology stack. I know Django and Flask are the 2 main options in Django.However, I don't have the clear idea with the whole tech stack for the job posting portal -
How do I fix 'Message' instance needs to have a primary key value before this relationship can be used
When I try to add a Message from the admin pages I get the 'Message' instance needs to have a primary key value before this relationship can be used. Here is my models.py Message class... class Message(models.Model): """ Message as sent through a Submission. """ default_id = time.time() #adding primary key to satisfy error id = models.BigAutoField(primary_key=True, auto_created=True) title = models.CharField(max_length=200, verbose_name=_('title')) slug = models.SlugField(verbose_name=_('slug')) newsletter = models.ForeignKey( Newsletter, verbose_name=_('newsletter'), on_delete=models.CASCADE, default=get_default_newsletter ) date_create = models.DateTimeField( verbose_name=_('created'), auto_now_add=True, editable=False ) date_modify = models.DateTimeField( verbose_name=_('modified'), auto_now=True, editable=False ) class Meta: verbose_name = _('message') verbose_name_plural = _('messages') unique_together = ('slug', 'newsletter') #order_with_respect_to = 'newsletter' def __str__(self): try: return _("%(title)s in %(newsletter)s") % { 'title': self.title, 'newsletter': self.newsletter } except Newsletter.DoesNotExist: logger.warning('No newsletter has been set for this message yet.') return self.title def get_next_article_sortorder(self): """ Get next available sortorder for Article. """ next_order = self.articles.aggregate( models.Max('sortorder') )['sortorder__max'] if next_order: return next_order + 10 else: return 10 @cached_property def _templates(self): """Return a (subject_template, text_template, html_template) tuple.""" return self.newsletter.get_templates('message') @property def subject_template(self): return self._templates[0] @property def text_template(self): return self._templates[1] @property def html_template(self): return self._templates[2] @classmethod def get_default(cls): try: return cls.objects.order_by('-date_create').all()[0] except IndexError: return None and the admin.py module class MessageAdmin(NewsletterAdminLinkMixin, ExtendibleModelAdminMixin, admin.ModelAdmin): logger.critical('MessageAdmin') save_as = … -
django-rq-scheduler not printing information on console window
I am referring to the official documentation from here. Here is my code: Directory Structure: settings.py file app1/jobs.py file Scheduled job in django-admin panel (time is 2 minutes after the current time) Issue I am expecting some log messages on the console (command prompt) after the specified time. But even after waiting for more than the specified time, there are no log messages. -
How to add notification feature in DRF?
I am new to Django. I have a question. How to add notification feature in Django Rest Framework? Like if a user has signed up, it's data should be popped up to frontend of owner as a notification. How to implement it's backend? Do we have to use django channels and web sockets? Why can't we do this with WSGI server which is supported by normal Django applications? e.g. class Employee(models.Model): some fields When object of class Employee is created, it's data should be popped up to frontend of it's owner as notification. -
i use video.js but i can't fast-forward when use on Django framework
i use video.js to play video and i create condition if videoPn( n = 1 to 17 ) = 0 video player hide progressControl and when videoPn = 1 video player show progressControl. my problem is when videoPn = 1 video player show progressControl but it can't fast-forward when i'm click at progressControl video will restart. But I tried to test it without Django. it's no problem var player = videojs("videoP"); function light(Cvideo) { for (let i = 0; i < videos.length; i++) { let video = videos[i]; if (videos[i].id === Cvideo) { //change name and src document.getElementById("nameV").innerHTML = videos[i].name; player.src({ type: "video/mp4", src: videos[i].src }); player.play(); if (!video["videoP" + (i + 1)]) { //hide progressControl player.controlBar.progressControl.hide(); player.on("timeupdate", function() { //percentage var percentage = (player.currentTime() / player.duration()) * 100; //display percentage document.getElementById("percentage").innerHTML = Math.round(percentage) + "%"; if (percentage === 100) { //if percentage = 100 change videoPn when n=i+1 video["videoP" + (i + 1)] = 1; //videoproมี = 1 var videopro = video["videoP" + (i + 1)] = 1; $.ajax({ type: "POST", url: "/update-video-progress/", data: { video_id: videos[i].id, videopro: videopro, }, success: function(response) { console.log("Video progress updated"); }, error: function(xhr, textStatus, errorThrown) { console.error("Failed to update video progress"); }, }); … -
can't get query strings in production mode but in development every thing is fine
i have a django app that should get query string params. and this works fine in my localhost. but when on deployed the app on python linux host , it encountered 500 server error. there isn't any errors in the stdr.log file . my url: path("foo",views.get_foo) my view: get_foo(request): model_foo= TestModel(name = request.GET.get("foo")) model_foo.save() return HttpResponse("done") thanks for helping -
Using Django "through" argument for saving additional information in ManyToMany field
I am trying to create a scenario where I may add an "order" of level (to add the degree of escalation) for the saved instances of a model "ContactPerson" according to some criteria (say seniority or position of responsibility). The form is intended to look someting like this: Contact Person Level Franc Correa 2 Liz Burnett 3 Christian Amarilo 3 Mark Tannit The Level values will be entered at runtime to the (already) created contact persons. (The empty field for the last entry in the above table signifies that a level is not yet assigned.) I have created the following models: class ContactPerson(models.Model): name = models.CharField(max_length=128) designation = models.CharField(max_length=128) class Level(models.Model): level = models.PositiveSmallIntegerField() desig_person = models.ManyToManyField(ContactPerson, through='Order') class Order(models.Model): contact_person = models.ForeignKey(ContactPerson, on_delete=models.CASCADE) level_order = models.ForeignKey(Level, on_delete=models.CASCADE) location = ... Now I create / add persons (in model ContactPerson) and later want to assign "level/degree of escalation" in model "Order" in field level_order at runtime. To that end I am using the following model form and assigning to an inlineformset_factory: class AssignEscalationLevelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AssignEscalationLevelForm, self).__init__(*args, **kwargs) self.auto_id = True class Meta: model = Order fields = ('contact_person', 'level_order', 'location') As already stated above, I want to …