Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django keyword reject argument 'disabled'
I try make 2 fields in fieldset possible to edit (others should be only visible), but I have problem with parameters: my code: def get_fieldsets(self, request, obj=None): fieldsets = self.fieldsets if request.user.groups.filter(name='copywriter').exists(): editable_fields = ['author', 'month'] readonly_fields = [field for field in self.fieldsets[0][1]['fields'] if field not in editable_fields] fieldsets = [(None, {'fields': editable_fields})] + [(None, {'fields': readonly_fields, 'disabled': True})] return fieldsets But anytime when I go to record view, I see "Fieldset.init() got an unexpected keyword argument 'disabled'" error. How can I fix it? I don't know where exactly is error, I'm using keyword from documentation, but it doesn't work. -
Create multiple choice field dynamically
My purpose is to create a django form to select devices filtered by country and club fields. My form is this: class MyForm(Form): country = ChoiceField(choices=some_choices, initial=None) club = CharField(widget=Select()) expiration_date = DateField() sales_info = ChoiceField(choices=SALES_TYPES, initial=None) devices = MultipleChoiceField(widget=CheckboxSelectMultiple(choices=[])) def clean_devices(self): devices = self.cleaned_data.get("devices") if not devices: raise ValidationError("At least one device must be selected.") return devices def save(self): ... views.py class MyFormView(LoginRequiredMixin, FormView): template_name = "store/my_template.html" form_class = MyFormView def get_success_url(self): return reverse('init_device') def form_valid(self, form): init_device = form.save() if init_device: return super().form_valid(form) return super().form_invalid(form) def form_invalid(self, form): logger.error(form.errors) my_template.html <form action="{% url 'init_device' %}" method="post"> {% csrf_token %} ... <select id="id_devices" name="devices" multiple> I populate select field via javascript in this way: let device_select = document.getElementById("id_devices"); serialIds.forEach(serialId => { let option = document.createElement("option"); option.text = serialId; option.value = serialId; device_select.add(option); }); I obtained filtered devices form db using a websocket by now I can't pass them to the form because this error raises: ValueError: The view path.view didn't return an HttpResponse object. It returned None instead. Then I print form.errors and this is showed <ul class="errorlist"><li>devices<ul class="errorlist"><li>Select a valid choice. device_attriubte is not one of the available choices.</li></ul></li></ul> Can anyone help me? Thank you in advance! -
How can I use python function in html? [closed]
I am a beginner in django and I am developing django code. The previous programmer linked html files to Django with js instead of using template tag. I want to use Python function in my template, is there a solution? -
Creating a custom serializer in django
I am facing a problem, because I have to create a custom serializer to fulfill my needs. These are my models: class PublicID(models.Model): TYPE_FIELDS = ( ('M', 'monkey'), ('A', 'alien'), ('P', 'person'), ) public_id = models.CharField(unique=True, max_length=48, editable=False) obj_type = models.CharField(choices=TYPE_FIELDS, max_length=1) class Request(models.Model): source = models.ForeignKey(PublicID, related_name='source_request_set', on_delete=models.CASCADE) dest = models.ForeignKey(PublicID, related_name='dest_request_set', on_delete=models.CASCADE) class Monkey(models.Model): nickname = models.CharField(max_length=255) public_id = models.OneToOneField(PublicID, related_name='monkey', blank=True, on_delete=models.CASCADE) class Alien(models.Model): alias = models.CharField(max_length=255) public_id = models.OneToOneField(PublicID, related_name='alien', blank=True, on_delete=models.CASCADE) class Person(models.Model): first_name = models.CharField(max_length=255) public_id = models.OneToOneField(PublicID, related_name='person', blank=True, on_delete=models.CASCADE) Note that all types of obj_types can send Request to every type of obj_types. e.g. we can have a Monkey which sends a request to an Alien through their unique PublicIDs. My Serializer looks like this: class RequestSerializer(serializers.ModelSerializer): class Meta: model = Request exclude = ['id'] def validate_source(self, value): obj_type = value.get('obj_type') if obj_type is None: raise serializers.ValidationError('`obj_type` field is required.') # other checks return value def validate_dest(self, value): obj_type = value.get('obj_type') if obj_type is None: raise serializers.ValidationError('`obj_type` field is required.') # other checks return value def run_validation(self, attrs): source = attrs.get('source') dest = attrs.get('dest') if source is None or dest is None: raise serializers.ValidationError('`source` and `dest` fields are ' 'required.') self.validate_source(source) self.validate_dest(dest) … -
Hey. I have an error when try to install mysqlclient to my Django project on Mac
Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [43 lines of output] mysql_config --version ['8.0.32'] mysql_config --libs ['-L/usr/local/Cellar/mysql/8.0.32/lib', '-lmysqlclient', '-lz', '-L/usr/local/lib', '-lzstd', '-L/usr/local/opt/openssl@1.1/lib', '-lssl', '-lcrypto', '-lresolv'] mysql_config --cflags ['-I/usr/local/Cellar/mysql/8.0.32/include/mysql'] ext_options: library_dirs: ['/usr/local/Cellar/mysql/8.0.32/lib', '/usr/local/lib', '/usr/local/opt/openssl@1.1/lib'] libraries: ['mysqlclient', 'resolv'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/usr/local/Cellar/mysql/8.0.32/include/mysql'] extra_objects: [] define_macros: [('version_info', "(2,1,1,'final',0)"), ('version', '2.1.1')] running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-universal2-cpython-311 creating build/lib.macosx-10.9-universal2-cpython-311/MySQLdb copying MySQLdb/init.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb creating build/lib.macosx-10.9-universal2-cpython-311/MySQLdb/constants copying MySQLdb/constants/init.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb/constants warning: build_py: byte-compiling is disabled, skipping. running build_ext building 'MySQLdb._mysql' extension creating build/temp.macosx-10.9-universal2-cpython-311 creating build/temp.macosx-10.9-universal2-cpython-311/MySQLdb clang -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch arm64 -arch x86_64 -g -Dversion_info=(2,1,1,'final',0) -D__version__=2.1.1 -I/usr/local/Cellar/mysql/8.0.32/include/mysql -I/Users/pro/.local/share/virtualenvs/storefront-qb_mvtC8/include -I/Library/Frameworks/Python.framework/Versions/3.11/include/python3.11 -c MySQLdb/_mysql.c -o build/temp.macosx-10.9-universal2-cpython-311/MySQLdb/_mysql.o -std=c99 xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun error: … -
Mutiple Forms Saved using one unique ID
I'm trying to save mutiple forms for spe_form using a unique ID for gen_format the same time using the template below by clicking on save button. Could you please help me with that? The code works only for one save for only form of spe_form but not for many def preps(request, prep=None): if prep_General: info = Mprep.objects.get(id=prep) else: info = Mprep() # Handle form submissions if request.method == 'POST': # Instantiate the forms with submitted data gen_form = MGForm(request.POST, instance=info) spe_form = MSForm(request.POST, prefix='preps') if gen_form.is_valid() and spe_form.is_valid(): gen_form.save() preps = spe_form.save(commit=False) preps.prep = info preps.save() messages.success(request, 'Information saved successfully') return redirect('preps_view', prep=info.id) else: messages.error(request, 'Error in saving information') else: gen_form = MGForm(instance=info) spe_form = MSForm(prefix='preps') context = {'gen_form': gen_form, 'spe_form': spe_form} return render(request, 'base.html', context) <div class="container mt-5"> <h1>Measurements Prep</h1> <form method="post"> {% csrf_token %} <div class="form-row"> <div class="form-group col-4"> {{ gen_form.project|as_crispy_field }} </div> <div class="form-group col-4"> {{ gen_form.cell|as_crispy_field }} </div> <div class="form-group col-4"> {{ gen_form.sample|as_crispy_field }} </div> </div> <br> <table id="myTable" class="table" data-toggle="table" data-mobile-responsive="true" data-pagination="true" data-height="460"> <tbody> <tr> <th>{{ spe_form_set.name|as_crispy_field }}</th> <th>{{ spe_form_set.value|as_crispy_field }}</th> <th>{{ spe_form_set.unit|as_crispy_field }}</th> </tr> </tbody> <button id="add-row-button" class="btn btn-primary mt-4">Add Row</button> </table> <input type="submit" class="btn btn-primary mt-4" value="Save"> </form> </div> <script> document.getElementById("add-row-button").addEventListener("click", function () … -
how to show vue js variables in django
I've this simple code in a **django ** in test.html: <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> <div id="app">the message:{{ message }}</div> <script> const { createApp } = Vue createApp({ data() { return { message: 'Hello Vue!' } } }).mount('#app') </script> in urls.py: urlpatterns = [ path('test', dashboard_views.test,name='test'), in views.py def test(request): return render(request,"test.html") output on screen: the message: how can I fix this to show "Hello Vue!" -
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