Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AJAX modal not opening in Django template using query in url
I'm trying to create a modal to open a window with the following url: http://127.0.0.1:8003/dados/add_dados?filter=crew So in urls.py: path('add_dados', add_dados, name="add_dados"), Follow the code below: <h2>Modal Example</h2> <!-- Trigger/Open The Modal --> <button id="myBtn">+ Add</button> <!-- The Modal --> <div id="myModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <span class="close">&times;</span> </div> </div> <script> document.getElementById('myBtn').onclick = function(){ $.ajax({ url:"{% url 'add_dados' %}?filter=sample_unit_trap", type:'GET', data_type: 'html', success: function(data){ $('#modal-content').html(data); $("#modal-content").modal('show'); } }); } </script> But the popup does not open. Any suggestion to make open the window with the page content add_dados?filter=sample_unit_trap -
How to make Django Wagtail API Private
I am trying to find a solution to make the Wagtail API v2 private, i.e being accessible only by having an API key, but I don't seem to be able to find solutions online. Does anyone have any idea how to do this? Thanks! -
How to create a code field in django form and save it as a json to the db
I am having a usecase where I want to have a code snippet field in django and use that code field value and save it as a json in the DB. class TestForm(forms.Form): rule_name = forms.CharField(max_length=200) rule_code = forms.CharField(max_length=200) the rule_code field should be able to accept code and when reading I should be able to parse as json. eg: rule_code = a+b while parsing it should be as json. eg: {"data":{"lval":"a", "rval": "b", "log":"+"}} any suggestion will be helpful. Thanks -
how to have a django form validator run on each object with ModelMultipleChoiceField rather than the queryset as a whole
I have a modelform which generates a series of checkboxes to add children to a parent part. I have created a validator that checks for cyclic relationships. I'm currently getting errors however because "proposed_child" is a queryset containing however many values the user has selected. How do I have this validator run on each object in that queryset? def __init__(self, qs, part, *args, **kwargs): super(AddPartToAssemblyForm, self).__init__(*args, **kwargs) self.part = part self.fields['children'] = forms.ModelMultipleChoiceField( queryset=qs, widget=forms.CheckboxSelectMultiple ) def clean_children(self): proposed_child = self.cleaned_data['children'] part = self.part validate_acyclic_relationship(part, proposed_child) class Meta: model = Part fields = ['children'] -
a problem with twilio outbound call in django
im trying to implement twilio in my django app to make outbound calls. but there is a probelm. in following code, the sample app get the phone number from a django form. https://github.com/TwilioDevEd/browser-calls-django/blob/main/browser_calls/static/js/browser-calls.js but what I wanna do is calling random phone numbers which is stored in my db. I have a django model in my app and there is a random selector function. How can I do that? all the example files is flask framework and I dont know how can I call random phone numbers in my db and record them. -
Django 4 with sqlite3 JSONField creating a "TEXT" column instead of "JSON"
I'm using Django 4 with SQLite3 database (although I will use mysql in production). I have a model such as this: class Video(models.Model): title = models.CharField(max_length=180) meta = models.JSONField(default=dict) I would expect that the column type of "meta" should be "JSON", but actually the migration creates it as a "TEXT" column and then encodes/decode the json data as a string. This is a problem because you lose JSON field capabilities (such as updating only certain keys, not updating the entire encoded string). From reading it appears that sqlite3 supports JSON field type, so how can I force Django to use it? -
How can i print form.errors in a template in django
I am a beginner in django.. How can i print form.errors in a template in django. I want to print each error below each field. I pass errors using below code from view using AJAX else: return JsonResponse({"error": form.errors}, status=400) -
error with docker container in bitbucket pipelines
I'm deploying my dockerized Django app using bitbucket pipelines but unfortunately, the pipeline already creates two containers but not the last one the error and my files are attached below. error ERROR: for db Cannot create container for service db: authorization denied by plugin pipelines: -v only supports $BITBUCKET_CLONE_DIR and its subdirectories Encountered errors while bringing up the project. docker-compose.yml version: "3.8" services: db: container_name: db image: "postgres" restart: always volumes: - postgres-data:/var/lib/postgresql/data/ app: container_name: app build: context: . restart: always volumes: - static-data:/vol/web depends_on: - db proxy: container_name: proxy build: context: ./proxy restart: always depends_on: - app ports: - 80:8000 volumes: - static-data:/vol/static volumes: postgres-data: static-data: bitbucket-pipelines.yml image: python:3.7.2 pipelines: default: - step: services: - docker caches: - docker - pip script: - pip install docker-compose - docker-compose -f docker-compose-deploy.yml up --build - pipe: atlassian/aws-code-deploy:0.2.5 variables: AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY COMMAND: 'upload' APPLICATION_NAME: $APPLICATION_NAME ZIP_FILE: 'application.zip' S3_BUCKET: $S3_BUCKET VERSION_LABEL: 'my-app-2.0.0' - pipe: atlassian/aws-code-deploy:0.2.5 variables: AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY COMMAND: 'deploy' APPLICATION_NAME: $APPLICATION_NAME DEPLOYMENT_GROUP: $DEPLOYMENT_GROUP WAIT: 'true' S3_BUCKET: $S3_BUCKET VERSION_LABEL: 'my-app-2.0.0' IGNORE_APPLICATION_STOP_FAILURES: 'true' FILE_EXISTS_BEHAVIOR: 'OVERWRITE' definitions: services: docker: memory: 3072 `` -
Pass variable to tables2?
In trying to follow the DRY principle for python, I am attempting to define some information about a column in tables2 with a variable. I can see that the variable is being passed to my init function, but I can't see it in the main body of my class. Is there a better way to do this? Below is a simplified version of the table that I am trying to use. class StuffTable(tables.Table): input(self.FontClass) # the variable is not showing up here columnAttributes = {"style": "font-size: 12px; max-width:120px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"} columnHeaderAttributes = {"class": f"mb3 { self.FontClass }"} columnFooterAttributes = {"style": "font-size: 12px; font-weight: bold; max-width:120px; overflow: hidden; text-overflow: ellipsis;"} Type = tables.Column(verbose_name="", attrs={"th": columnHeaderAttributes, "td": columnAttributes}) TypeDescription = tables.Column(verbose_name="Type", attrs={"th": columnHeaderAttributes, "td": columnAttributes}) Column3= tables.Column(attrs={"th": columnHeaderAttributes, "td": columnAttributes}) Column4= tables.Column(attrs={"th": columnHeaderAttributes, "td": columnAttributes}) def __init__(self, *args, **kwargs): temp_fontclass = kwargs.pop("FontClass") super(StuffTable, self).__init__(*args, **kwargs) self.FontClass = temp_fontclass input(self.FontClass) # this does show that the variable is being passed -
Hot Reload with django template and react?
Is hot reloading possible while mounting react components into our Django template? As part of improving our UX, we are adding react component to our page to bring dynamic content on every customer interaction. I have successfully set up the react inside our Django and placed bundle.js into a static path using Webpack. Now using Webpack watch we are able to load the latest changes on the page. In this setup, we can't bring hot reloading and source in the browser devtools console to debug and speed up our development. Note: The application is not a SPA also not a Restful design for now. -
How to set initial value for all students to present in College management system | django admin inline
I am building College management system in django including features such as quiz, lms and attendance and so on. I want to set All students default attendance status to Present in django admin inline. So teacher dont have to hammer the status checkbox for every student, every student should be present by default and teacher only have to uncheck the status for whom who are absent. I have googled a lot but having hard time figuring out the solution. This is what I want: My model: class Attendance(models.Model): course = models.ForeignKey(settings.COURSE_MODEL, on_delete=models.CASCADE) date = models.DateField(default=datetime.now) class AttendanceStatus(models.Model): attendance = models.ForeignKey(Attendance, on_delete=models.CASCADE) student = models.ForeignKey(settings.STUDENT_MODEL, on_delete=models.CASCADE) status = models.BooleanField() And here is the admin. class AttendanceStatusInline(admin.TabularInline): model = AttendanceStatus can_delete = False fields = [ 'student', 'status' ] autocomplete_fields = [ 'student' ] @admin.register(Attendance) class AttendanceAdmin(admin.ModelAdmin): list_display = [ 'course', 'date'] autocomplete_fields = ['course'] inlines = [ AttendanceStatusInline ] Thanks in advance. -
envrionment variables with dokcer-compose in bitbucket pipelines
I have a Django app that is dockerized and I want it to deploy it using bitbucket pipelines, but the error is I use env file in docker-compose.yml which I can't put in my repo, so how can I overcome it. docker-compose.yml version: "3.8" services: db: container_name: db image: "postgres" restart: always volumes: - postgres-data:/var/lib/postgresql/data/ env_file: - prod.env app: container_name: app build: context: . restart: always volumes: - static-data:/vol/web env_file: - prod.env depends_on: - db proxy: container_name: proxy build: context: ./proxy restart: always depends_on: - app ports: - 80:8000 volumes: - static-data:/vol/static volumes: postgres-data: static-data: settings.py EMAIL_HOST = os.environ.get('EMAIL_HOST') bitbucket-pipelines.yml image: python:3.7.2 pipelines: default: - step: services: - docker caches: - docker - pip script: - pip install docker-compose - docker-compose -f docker-compose-deploy.yml up --build - pipe: atlassian/aws-code-deploy:0.2.5 variables: AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY COMMAND: 'upload' APPLICATION_NAME: $APPLICATION_NAME ZIP_FILE: 'application.zip' S3_BUCKET: $S3_BUCKET VERSION_LABEL: 'my-app-2.0.0' - pipe: atlassian/aws-code-deploy:0.2.5 variables: AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY COMMAND: 'deploy' APPLICATION_NAME: $APPLICATION_NAME DEPLOYMENT_GROUP: $DEPLOYMENT_GROUP WAIT: 'true' S3_BUCKET: $S3_BUCKET VERSION_LABEL: 'my-app-2.0.0' IGNORE_APPLICATION_STOP_FAILURES: 'true' FILE_EXISTS_BEHAVIOR: 'OVERWRITE' definitions: services: docker: memory: 3072 -
Django structure vs Clean archirecture
We want to create a new project in python language(out project is in digital advertising), we choose the Django framework for developing it, BUT we have a problem for choosing architecture. Some of us want to use the Django default structure for file naming, project structure and etc, but another is like to use a clean architecture structure. We are very happy to know your opinion Django strcture advantage: simple, have a good document, Writing code is much less Clean Architecture advantage: top programmer use this, other python developers(flask/fatapi) comfortable with it -
How to start publish or use my django project that i made on Blogger or wordpress?
I Develop and design Django project , chat site for desktop and mobile app - its my first time! Q - ist possible to use it in blog-spot ? ot word-press ? the files i code it by python and HTML for front-end. -
Sort by nested Embedded Document List
obj = self.get_object() # Need to add sorting here submited_talents_page = paginator.paginate_queryset( obj.doc_list, request ) the list lloks like this: obj.doc_list = [{ "user": ObjectId("12123124"), "viewers": [], "application": ObjectId("34322") } ] application: "timestamp": "<timestamp>", "code": "DEF" } I need to sort the application.timestamp inside obj.doc_list. -
Set id inside filter on serializer automatically
I'm trying to get the total count from specific Model inside a Serialization. "results": [ { "event_id": 24, "unique_visitors": 1, "returned_visitors": 2 }, ] The two value that i retrive in unique_visitors and returned_visitors come from one other module. What i did in serializer.py: unique_visitors = EventCounter.objects.filter(is_unique=True).filter(event_id=24).count() returned_visitors = EventCounter.objects.filter(is_unique=False).filter(event_id=24).count() def get_unique_visitors(self, obj): return self.test1 def get_returned_visitors(self, obj): return self.test2 What i try to do is to have inside the filter(event_id=24) the id of current object automatically. Can you help me please? -
How to have a Save draft option for profile creating form in django
I have view.py and model.py files for user creation, but I want an option for users that he/she can either submit the form and create the profile or can just hit the Save draft button to come later and submit the form. What would be the best way to achieve the above-said thing. -
Django guardian add a group to a user in the admin panel
When I create a group in django guardian's admin integration, how can I add that group to a user's groups in the admin panel -
Nginx auth could not identify password
I'm trying to deploy a Django application to a local Ubuntu server. While following the nginx docs, I encountered an issue while trying to restart nginx after updating the conf file. This is the output from journalctl -xe -- The job identifier is 154. Mar 02 10:43:38 cmac-srv03 systemd[44001]: tracker-extract.service: Succeeded. -- Subject: Unit succeeded -- Defined-By: systemd -- Support: http://www.ubuntu.com/support -- -- The unit UNIT has successfully entered the 'dead' state. Mar 02 10:43:40 cmac-srv03 dbus-daemon[44023]: [session uid=1001 pid=44023] Activating service name='org.freedesktop.secrets' requested by '> Mar 02 10:43:40 cmac-srv03 gnome-keyring-daemon[44513]: couldn't access control socket: /run/user/1001/keyring/control: No such file or dire> Mar 02 10:43:40 cmac-srv03 gnome-keyring-d[44513]: couldn't access control socket: /run/user/1001/keyring/control: No such file or directory Mar 02 10:43:40 cmac-srv03 dbus-daemon[44023]: [session uid=1001 pid=44023] Successfully activated service 'org.freedesktop.secrets' Mar 02 10:43:52 cmac-srv03 pulseaudio[44008]: GetManagedObjects() failed: org.freedesktop.DBus.Error.NoReply: Did not receive a reply. Possi> Mar 02 10:43:58 cmac-srv03 tracker-store[44147]: OK Mar 02 10:43:58 cmac-srv03 systemd[44001]: tracker-store.service: Succeeded. -- Subject: Unit succeeded -- Defined-By: systemd -- Support: http://www.ubuntu.com/support -- -- The unit UNIT has successfully entered the 'dead' state. Mar 02 10:47:56 cmac-srv03 sudo[45528]: pam_unix(sudo:auth): conversation failed Mar 02 10:47:56 cmac-srv03 sudo[45528]: pam_unix(sudo:auth): auth could not identify password for [subhaac] This is my … -
How to check the users and if the user is correct then marked the ordered section tick in Django
I want to check the user and if the user is correct then marked the order other wise make it as False on Boolen Type, I have attached the SS of output and it's code def orderList(request): order_qs = User.objects.get(username=request.user.username) if request.method == "POST": status = request.POST.get("order") if (order_qs): Order.objects.update(ordered = status) else: Order.objects.update(ordered = False) order = Order.objects.get(user = request.user) context = { 'order' : order, } return render(request, 'user_accounts/order_item.html',context) -
NameError: name '_mysql' is not defined - Django tailwind
When I run python manage.py runserver, my django server runs and I can see my webpage, however some of the tailwind doesn't work. When I then stop that server and run python manage.py tailwind start, the localhost:8000 doesn't show my webpage, but my terminal says that it is running. When I then stop the tailwind server running, and run python manage.py runserver, I get an error saying NameError: name '_mysql' is not defined. I am unsure why this is happening, here is my full stack trace: Traceback (most recent call last): File "/Users/maxculley/Desktop/ESD COURSEWORK/venv/lib/python3.8/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/maxculley/Desktop/ESD COURSEWORK/venv/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib Referenced from: /Users/maxculley/Desktop/ESD COURSEWORK/venv/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so Reason: image not found During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/maxculley/Desktop/ESD COURSEWORK/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/Users/maxculley/Desktop/ESD COURSEWORK/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute django.setup() File "/Users/maxculley/Desktop/ESD COURSEWORK/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/maxculley/Desktop/ESD COURSEWORK/venv/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/maxculley/Desktop/ESD COURSEWORK/venv/lib/python3.8/site-packages/django/apps/config.py", line 300, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen … -
Django Admin /admin two times one server different port
currently I facing an issue to create two django projects parallel working on one server system. Konfiguration: nginx ubuntu server such as 1.1.1.1 django project 1 such as 1.1.1.1/admin with Port 8000 django project 2 such as 1.1.1.1/demo/admin2 with Port 9000 Currently if I start both (django project 1 and 2) manage.py runserver successful and if I change path("admin/", django.contrib.admin.sites.urls) to path("admin2/", django.cotntrib.admin.site.urls) this gives me the Not Found Error. Is there any way to use two django projects parallel on one server in a different GitHUb folder structure and the same IP ? -
How to disallow specific character input to a CharField
I have a model in which I want to disallow the input of special characters(+,-,/,%, etc) in the title field: class Article(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title Can I accomplish this in the model itself? Or do I have to do something with the forms.py so that users arent able to post a form with special chars in the title. How exactly can I accomplish this? -
Scheduling a satutus change using celery in django
In my program, I have scheduled a task that is aimed at changing the status of insurance to Expiré if the due date is equal to the current date when I run the program. The script supposes to loop up throughout the Contract's table and fetches the rows that are corresponding to the condition we used in the script. However, it is changing the status of the whole table including rows that should not be affected by the imposed condition. Here is the jobs.py file that is scheduling the task of changing the status of the insurance to Expiré if the condition is true. from assurance_auto.models import Contrat from datetime import datetime, timedelta,date from django.conf import settings def status_schedule(): contractList = Contrat.objects.all() for contrat in contractList: if contrat.get_NbDays()<=date.today() and contrat.statut_assurance=='Encours': contractList.update(statut_assurance='Expiré') print('Numéro de contrat est :',contrat.numero_de_contrat,\ ' et le statut est: ',contrat.statut_assurance) else: break Below is the updater.py file. This function is about scheduling the execution time of the job from datetime import datetime from apscheduler.schedulers.background import BackgroundScheduler from .jobs import status_schedule def start(): scheduler = BackgroundScheduler() scheduler.add_job(status_schedule, 'interval', seconds=5) scheduler.start() In the apps.py file, I have the program below which consists of running the updater file once the program … -
Build a wizard without django-formtools in Django
Are there any django libraries to help build wizard based interfaces that are not formtools/wizard ? formtools/wizard has some properties that make it hard to test, moving forward and back between forms is tightly integrated with rendering, making it hard to unit test the forms themselves. Similarly session storage is tightly integrated. Other issues, come from the coding style of when it was written over a decade ago. So, as much as this will get voted down, I'm not asking for preferences, just any libraries that help with making wizards, I also understand this could be coded manually.