Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why doesn't echo copy over github secret to .env file
I have a Django app that collects the secret key from a '.env' file in my local directory, I have added this .env to .gitignore so it doesn't get uploaded to github, the only problem is I have now deployed the app to AWS EC2 and I'm using github as a codepipeline, so now the app can't obtain the secret key as it doesn't have the .env file to read from. I've added my secret key to 'github secrets' which is in the repository settings , from what I've read online using echo to get the key and write to a new .env file on startup would work, only problem is the key doesn't echo over to the .env file , yet the file is created with the following command. What's going wrong, please advise on how to fix?: setup_env.sh #!/bin/bash cd /home/ubuntu/djangoapp1/djangoapp1/settings touch .env echo SECRET_KEY=${{ secrets.SECRET_KEY }} > .env appspec.yml version: 0.0 os: linux files: - source: / destination: /home/ubuntu/ hooks: BeforeInstall: - location: scripts/setup_env.sh timeout: 6000 runas: ubuntu AfterInstall: - location: scripts/install_python_dependencies.sh timeout: 6000 runas: ubuntu -
How to download Excel Sheet from Server using openpyxl on Django?
my Frontend calls the Django-Server via AJAX get HTTP Request to export data from the database to an excel-file. Therfore Im using openpyxl. I want to download the HTTP-Response on client side but only get excel files i cannot open or with undefined data. here is my javascript request: $.ajax({ url: '/documentation/export/get' + '/' + var_1 + '/' + var_2, type: 'get', responseType: 'blob', success: function(response) { console.log("EXCEL Success") // var contentType = 'application/vnd.ms-excel'; var contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; var filename = "TEST.xlsx" var blob = new Blob([response], { type: contentType }); var downloadUrl = URL.createObjectURL(blob); var a = document.createElement("a"); a.href = downloadUrl; a.download = filename; document.body.appendChild(a); a.click(); } }); Here is my server-side python code, views.py: from openpyxl import Workbook def documentation_export (request, var_1, var_2): excel_data = [ ['header1', 'header2', 'header3', 'header4', 'header5'], [1,4,5,6,7], [5,6,2,4,8] ] if excel_data: wb = Workbook(write_only=True) ws = wb.create_sheet() for line in excel_data: ws.append(line) response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') # response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=mydata.xlsx' wb.save(response) return response The data for the excelfile / workbook is right now still an exampel from the internet. If I use the code as posted, no download starts at all. If I use the out commented "vnd.ms-excel" instead, I … -
Chaquopy: Python: Is there any way to run Django Apps on Android
I've made a Django Web App which I want to deploy on Android.Recently, I came across a gradle plugin Chaquopy. But as soon as I deploy django app using Chaquopy, It doesn't give desired result and rather gives runtime exceptions.Kindly describe any method using (or even without using) Chaquopy to deploy Django App on Android as .apk -
command and control django server
I am developing a command and control server to control my client-server connected to it via rest API. I am done with Crud APIs for tasks that will be performed but I am having trouble with task management between my client-servers I want to fetch the tasks and then make a single configuration file for all clients but I am not sure what is the best way to do it. I have some ideas please help me figure out the best one :- generate new configuration settings everytime client server perform get call for the configuration settings. this will be slow if i have more tasks. generate new configuration everytime a task is modified, added , deleted along with time stamp. so that clients can check if the config file they are using is old or new compared to the one they received when making get call for configuration. -
Redis not connected with Django in Apache server
Possible SECURITY ATTACK detected. It looks like somebody is sending POST or Host: commands to Redis. This is likely due to an attacker attempting to use Cross Protocol Scripting to compromise your Redis instance. Connection aborted. Please any one can help me on this above error in the apache server -
Django Internationalization : pre choose the language_code but not the one from the settings
Im using django internationalization and im facing a problem: I've been successfully translating my project but i may need more : A user can send a message(the message is known and stored into TextField model ) to an other one, for now if UserA send a message to UserB UserB will receive the message in UserA LANGUAGE_CODE : Can i change it to make UserB to receive message into UserB LANGUAGE_CODE ? Example : UserA is french he selects "envoyer Joyeux anniversaire" to UserB And UserB is english and will receive : "UserA sent you a message :"Joyeux anniversaire" nb: i would rather not show up my code because it's way too big , if you want me to explain my problem with my code ill create a simplest one summarizing the functionalism -
Django custom models.Manager queryset field undefined
I'm implementing a soft delete for class Animal. Following the example in the docs I created a custom manager for it, but the query field, 'Inactive_Date' is undefined. I tried putting the AnimalManager class def inside the Animal class def; no help. Code from models.py: class AnimalManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(Inactive_Date == None) class Animal(models.Model): Name = models.CharField(max_length=64, unique=True) Inactive_Date = models.DateField(null=True, blank=True) Animal_Type = models.ForeignKey(Animal_Type, null=True, on_delete=models.SET_NULL, default=None) Comments = models.CharField(max_length=255, blank=True) def __str__(self) -> str: return (self.Name) def delete(self): self.Inactive_Date = datetime.datetime.today() self.save() objects = AnimalManager() # omits inactive animals -
saving formset by passing it the id of another formset in which it is nested
Hi I have a formset named groups and inside there is another formset named exercises. My problem lies in saving the various formset exercises created in the group formset to which they belong. I am attaching a photo to make you better understand the situation, in the photo the blue boxes (formset exercises) must be saved in the first green box (formset groups) VIEWS def creazioneView(request): gruppiFormSet = formset_factory(GruppiForm, extra=1) eserciziFormSet = formset_factory(EserciziForm, extra=1) if request.method == "POST": schede_form = SchedeForm(request.POST) gruppi_formset = gruppiFormSet(request.POST, prefix='gruppi') esercizi_formset = eserciziFormSet(request.POST, prefix='esercizi') if schede_form.is_valid() and gruppi_formset.is_valid() and esercizi_formset.is_valid(): schedaName = schede_form.cleaned_data['nome_scheda'] scheda = schede_form.save(commit = False) scheda.utente = request.user scheda.save() for gruppo in gruppi_formset: gruppi_instance = gruppo.save(commit = False) gruppi_instance.gruppi_scheda = Schede.objects.get(nome_scheda = schedaName) gruppoName = gruppi_instance.dati_gruppo gruppi_instance.save() for esercizi in esercizi_formset: esercizi_instance = esercizi.save(commit = False) esercizi_instance.gruppo_single = DatiGruppi.objects.get(dati_gruppo = gruppoName) esercizi_instance.save() return redirect('/lista-gruppi/') else: schede_form = SchedeForm() gruppi_formset = gruppiFormSet(prefix='gruppi') esercizi_formset = eserciziFormSet(prefix='esercizi') context = {'schede_form': schede_form, 'gruppi_formset': gruppi_formset, 'esercizi_formset': esercizi_formset} return render(request, "crea.html", context) MODELS class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey(Gruppi, on_delete = models.CASCADE, related_name = 'gruppo') class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey(User, on_delete = … -
Django/python images not displayed
I have tried all combinations (ex: {{ cars.image_main.url }} , {{ car.image_main.url }}). If anyone can give me a hand i will appreciate. I'm beginner in this, i don't have enough time to learn and practice and i follow some times youtube and udemy classes. Im on this for 1 day and my brain is not working at all as far as i can see. Thank you in advance for an advice or solution. models.py: class Car(models.Model): dealer = models.ForeignKey(Dealer, on_delete=models.DO_NOTHING) brand = models.CharField(max_length=100) CATEGORY = ( ('New', 'New'), ('Used', 'Used') ) category = models.CharField(max_length=50, choices=CATEGORY) image_main = models.ImageField(upload_to='images') image1 = models.ImageField(upload_to='images', blank=True) image2 = models.ImageField(upload_to='images', blank=True) image3 = models.ImageField(upload_to='images', blank=True) image4 = models.ImageField(upload_to='images', blank=True) image5 = models.ImageField(upload_to='images', blank=True) image6 = models.ImageField(upload_to='images', blank=True) image7 = models.ImageField(upload_to='images', blank=True) image8 = models.ImageField(upload_to='images', blank=True) image9 = models.ImageField(upload_to='images', blank=True) image10 = models.ImageField(upload_to='images', blank=True) image11 = models.ImageField(upload_to='images', blank=True) image12 = models.ImageField(upload_to='images', blank=True) image13 = models.ImageField(upload_to='images', blank=True) image14 = models.ImageField(upload_to='images', blank=True) image15 = models.ImageField(upload_to='images', blank=True) body_style = models.CharField(max_length=100, blank=True) engine = models.CharField(max_length=100, blank=True) stock_number = models.IntegerField(blank=True, null=True) mpg = models.CharField(max_length=100, blank=True) exterior_color = models.CharField(max_length=100, blank=True) interior_color = models.CharField(max_length=100, blank=True) drivetrain = models.CharField(max_length=100, blank=True) mileage = models.IntegerField(blank=True, null=True) sold = models.BooleanField(default=False, blank=False) transmission = models.CharField(max_length=50, blank=True) YEAR_CHOICES … -
Geeting error during adding a comment as notnull
I don't understand why I am getting this one I tried making null=True, blank=True but still, it does not solve my error, at last, I thought of sending it here ...!! please tell me where I am going wrong Models.py class Certification(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) course_name = models.CharField(max_length=255) course_image = models.ImageField() course_taken = models.CharField(max_length=255) mentor_name = models.CharField(max_length=20, blank=True, null=True) slug = models.SlugField(unique=True, null=True) #body = RichTextField() body = RichTextUploadingField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.course_name class Comment(models.Model): certificate = models.ForeignKey(Certification, on_delete=models.CASCADE) name = models.CharField(max_length=200) body = models.TextField(null=True, blank=True) forms.py class CommentForm(ModelForm): class Meta: model = Comment fields = '__all__' exclude = ['certificate'] def __init__(self, *args, **kwargs): super(CommentForm, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs.update( {'class': 'form-control form-control-sm',}) self.fields['body'].widget.attrs.update( {'class': 'form-control form-control-sm',}) Views.py def certificatePage(request,pk): certi = Certification.objects.get(id=pk) count = certi.comment_set.count() comments = certi.comment_set.all() form = CommentForm() if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.certi = certi comment.save() context = { "certi": certi, 'count':count, 'comments':comments, 'form':form } return render (request, 'base/certificate.html',context) Click On The Image To See The Error -
defined property on user model not working
I am trying to get the received message count, but i am getting nothing in the template , also i have defined my modal after User , any better way of doing it this property is on User model @property def get_message_count(self): try: messages_count = Messages.objects.filter(message_thread__receiver = self,opened=False).count() except ObjectDoesNotExist: messages_count = 0 return messages_count model class MessageThreads(models.Model): sender = models.ForeignKey( User, on_delete=models.SET_NULL, related_name='sender', null=True) receiver = models.ForeignKey( User, on_delete=models.SET_NULL, related_name='receiver', null=True) created_date = models.DateField(auto_now_add=True) created_time = models.TimeField(auto_now_add=True) class Messages(models.Model): message_thread = models.ForeignKey(MessageThreads,on_delete=models.CASCADE,null=True) message = models.TextField(max_length=600,blank=True) sent_date = models.DateField(auto_now_add=True) sent_time = models.TimeField(auto_now_add=True) opened = models.BooleanField(default=False) def __str__(self): return f"{self.message[:10]}" -
How to populate a model field with a Django signal after updating another model field?
I have a list of tasks that are created by the admin and as the task start dates are set by individual agents, I would like to use a signal to assign the tasks to that agent. Models.py class Task(models.Model): name = models.CharField(max_length=20, blank=True, null=True) agent = models.ForeignKey("Agent", on_delete=models.SET_NULL, null=True) start_date = models.DateField(null=True, blank=True) notes = models.TextField(default=0, null=True, blank=True) -
ImportError: cannot import name 'DjangoDash' from 'django_plotly_dash'
I'm attempting to follow the django-plotly-dash tutorial https://django-plotly-dash.readthedocs.io/en/latest/simple_use.html but when using the code directly from this page: import dash import dash_core_components as dcc import dash_html_components as html from django_plotly_dash import DjangoDash app = DjangoDash('SimpleExample') # replaces dash.Dash app.layout = html.Div([ dcc.RadioItems( id='dropdown-color', options=[{'label': c, 'value': c.lower()} for c in ['Red', 'Green', 'Blue']], value='red' ), html.Div(id='output-color'), dcc.RadioItems( id='dropdown-size', options=[{'label': i, 'value': j} for i, j in [('L','large'), ('M','medium'), ('S','small')]], value='medium' ), html.Div(id='output-size') ]) @app.callback( dash.dependencies.Output('output-color', 'children'), [dash.dependencies.Input('dropdown-color', 'value')]) def callback_color(dropdown_value): return "The selected color is %s." % dropdown_value @app.callback( dash.dependencies.Output('output-size', 'children'), [dash.dependencies.Input('dropdown-color', 'value'), dash.dependencies.Input('dropdown-size', 'value')]) def callback_size(dropdown_color, dropdown_size): return "The chosen T-shirt is a %s %s one." %(dropdown_size, dropdown_color) and trying to run the server, I get the error ImportError: cannot import name 'DjangoDash' from 'django_plotly_dash' Is this deprecated and they haven't updated the tutorial or some other reason? -
NOT NULL constraint failed error when attempting to save using createview
This is my first post to SO, so please let me know if I've missed any important details. I am working on updates to a home-grown DJango based ticketing system. I have two "parent" models (ParentProjects and Projects) that capture details about work we want to track. Both models have a number of columns that store information in the associated table as well as some FK relations. I have set up a generic class-based detail view for objects in both the Project table. The ParentProject table uses a function based view to accomplish the same task of loading the parent project details. The problem I am having is that I cannot add a new entry to the IDTasks model that automatically inserts the Parent Project id. I am able to add a new IDTask from within the admin site (or from the "client" site if I enable the "parent" field within the modelform) and then manually selecting the parent I wish to associate the IDTask to. I can also edit an existing IDTask from within the Parent Project detail template and everything saves successfully. When I attempt to add an IDTask using the createview, Django reports a Not NULL contraint … -
how to disable password in Dj Rest Auth?
i have an application and the new user can only register with OTP message from phone so i want to disable password in API and user can register with OTP only this is my serializers.py class CustomRegisterSerializer(RegisterSerializer): email=serializers.EmailField(required=True) image=serializers.ImageField(required=True) phone=serializers.CharField(required=True) address=serializers.CharField(required=True) gender=serializers.ChoiceField(choices=GENDER,required=True) birthday=serializers.DateField(required=True) password1=serializers.CharField(required=False) password2=serializers.CharField(required=False) def get_cleaned_data(self): super(CustomRegisterSerializer,self).get_cleaned_data() return { 'email': self.validated_data.get('email',""), # 'password1': self.validated_data.get('password1',""), # 'password2': self.validated_data.get('password2',""), 'username': self.validated_data.get('username',""), 'phone': self.validated_data.get('phone',""), 'address': self.validated_data.get('address',""), 'gender': self.validated_data.get('gender',""), 'birthday': self.validated_data.get('birthday',""), 'image': self.validated_data.get('image',"") } def validate_phone(self,value): if Account.objects.filter(phone__iexact=value).exists(): raise ValidationError(f"{value} is already registered") def validate_image(self,value): size=value.size / (1024 * 1024) type=os.path.splitext(value.name)[1] if size > 2 or type != ".jpg": raise ValidationError("image size is more than (2Mb)") def save(self, request): user = super().save(request) user.set_unusable_password() user.username=self.data.get("username") user.first_name=self.data.get("username") user.save() myacount=user.account myacount.image=request.FILES["image"] myacount.type="Patient" myaccount.phone=self.data.get("phone") myaccount.birthday=self.data.get("birthday") myaccount.gender=self.data.get("gender") myaccount.address.add(name=self.data.get("address")) myacount.save() return user i will be very happy for your answer -
Could not find a version that satisfies the requirement pywin32==301 , heroku error
I have tried to remove that file pywin32 from requirements but still it shows this error. I have searched for a method to remove this module but till now I have not found anything useful. This is my requirements.txt file asgiref==3.3.4 astroid==2.7.3 backcall==0.2.0 bcolors==1.0.2 beautifulsoup4==4.9.3 bs4==0.0.1 certifi==2021.5.30 cffi==1.14.6 chardet==4.0.0 cheroot==8.5.2 cloudpickle==1.6.0 colorama==0.4.4 cryptography==3.4.7 decorator==5.0.9 defusedxml==0.7.1 distlib==0.3.2 dj-database-url==0.5.0 Django==3.2.4 django-crispy-forms==1.12.0 django-extensions==3.1.3 django-filter==2.4.0 django-heroku==0.3.1 djangorestframework==3.12.4 filelock==3.0.12 gunicorn==20.1.0 idna==2.10 ipykernel==5.5.5 ipython==7.24.1 ipython-genutils==0.2.0 isort==5.9.3 jaraco.functools==3.3.0 jedi==0.18.0 jupyter-client==6.1.12 jupyter-core==4.7.1 lazy-object-proxy==1.6.0 Markdown==3.3.4 matplotlib-inline==0.1.2 mccabe==0.6.1 more-itertools==8.8.0 oauthlib==3.1.1 parso==0.8.2 pickleshare==0.7.5 Pillow==8.2.0 platformdirs==2.3.0 prompt-toolkit==3.0.19 psycopg2==2.9.1 pycparser==2.20 Pygments==2.9.0 PyJWT==2.1.0 pylint==2.10.2 pymongo==3.11.4 pypiwin32==223;platform_system == "Windows" python-dateutil==2.8.1 python3-openid==3.2.0 pytz==2021.1 pywin32==301;platform_system == "Windows" pyzmq==22.1.0 requests==2.25.1 requests-oauthlib==1.3.0 simplejson==3.17.2 six==1.16.0 social-auth-app-django==5.0.0 social-auth-core==4.1.0 soupsieve==2.2.1 spyder-kernels==2.0.0 sqlparse==0.4.1 termcolor==1.1.0 toml==0.10.2 tornado==6.1 traitlets==5.0.5 urllib3==1.26.5 virtualenv==20.4.7 wcwidth==0.2.5 web.py==0.62 whitenoise==5.3.0 wrapt==1.12. I am getting this error when I use git push heroku master ERROR: Could not find a version that satisfies the requirement pywin32==301 (from -r /tmp/build_53cc9ad9/requirements.txt (line 57)) (from versions: none) remote: ERROR: No matching distribution found for pywin32==301 (from -r /tmp/build_53cc9ad9/requirements.txt (line 57)) This is the full error message Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: eea743c20e6fc3b759e5d6061939723626cbb910 remote: ! remote: ! We have detected that you have … -
Can we use Django-cacheops in Django 3+ versions?
I am updating the django project form 1.3 to Django 3.2 I am trying to use Django-cacheops as I already built in my old version project, but its give me the error of File "C:\Users\mahad\projects\Allay\env\lib\site-packages\cacheops\simple.py", line 9, in <module> from django.utils.hashcompat import md5_constructor ModuleNotFoundError: No module named 'django.utils.hashcompat' Is this library is deprecated or I can use it? If yes then give me the way to do it or kindly refer some extra plugin for saving the cache with redis -
authentication failed when I use postgresql with django
OS: AWS linux django3.2.7 python 3.7 psql (PostgreSQL) 13.3 I am trying to use postgresql with django. I changed setting.py like below: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbname', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432', } } I created a password for postgre and I successfully logged in as this user. $ sudo su - postgres Last failed login: Sun Sep 26 18:21:57 JST 2021 on pts/4 There were 6 failed login attempts since the last successful login. -bash-4.2$ psql Password for user postgres: psql (13.3) Type "help" for help. postgres=# However, when I tried to execute this: $ python3 manage.py runserver I got this error: django.db.utils.OperationalError: FATAL: Ident authentication failed for user "postgres" I am not sure what is the problem and would like to know how I can fix this. Thank you in advance! -
Unable to start Django server inside docker container
I am unable to connect to the Django server on a docker container. I am trying to use 0.0.0.0:8000 to connect and I used "docker-compose up" to create a container. docker-compose.yaml version: '3.7' services: server: build: context: ./PriceAlertWeb dockerfile: Dockerfile image: serverimg3 container_name: servercon3 ports: - 8000:8000 Dockerfile FROM python:3.7 WORKDIR /ServerCode/ COPY . /ServerCode/ RUN pip install -r req.txt CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] I am able to create a container successfully. But when I try accessing it with "http://127.0.0.1:8000/userDetails/", I'm unable to see my content. Please note that when I try running "python manage.py runserver 0.0.0.0:8000" on my local, my application functions as expected. (Screenshots below) -
How to add geocoder to django-leaflet's (admin) form widget
I tried to add leaflet-contrtol-geocoder(https://github.com/perliedman/leaflet-control-geocoder) to django-leaflet's widget. Added below script, and I can see geocoder icon added and function correct. window.addEventListener("map:init", function (event) { var map = event.detail.map; // var options = { url: "http://localhost:3100/v1", expanded: false, bounds: false, sources: 'whosonfirst' }; geocontrol = L.control.geocoder(options); geocontrol.addTo(map); }); But this way it won't update associated textarea for geom field. I tried to modify leaflet-control-geocoder to fire L.Draw.Event.CREATED instead of just addLayer, but leaflet.forms.js use a flag to ignore events of other draw controls: // We use a flag to ignore events of other draw controls for (var toolbar in drawControl._toolbars) { drawControl._toolbars[toolbar].on('enable disable', function (e) { this._acceptDrawEvents = e.type === 'enable'; }, this); } Any idea how this can be done? I can't find a place to set _acceptDrawEvents for geocoder control. Thanks! -
How to store django model's logs individually in another database?
I've been using auditlogs, and models_logging recently. The issue with them is that they store all the logs in a single table in my mongodb. I want to store the logs individually. Is there any way or any package that offers such features? -
Use React CDN and Django on same server and port
I'm using django for the backend and render the webUI from the django templates. Now I wanted to dive into React and migrate to a client side rendered UI. My idea is to setup django to only load the first (index.html) page where all the react cdn scripts (react, reactDOM, react-router, prop-types, axios, ...) and component scripts are loaded and their state will then be handled on the client machine. My idea was to reduce the load on the application server due to the fact that the app server will have to handle a lot of concurrent users, a lot of api hits, input-ouput operations, high CPU consumption, handle multiple tcp connections, have high RAM usage which will accumulated take up a lot of resources. For that reason I didn't want to build a react app and run it on the same machine on a dedicated port, because it will run next to the django application and take up RAM resources. But the problem with the cdn variant of react is that I don't know how to use all the other modules that are pre-delivered when creating a react app create-react-app: prop-types, axios, and many more. Do I have to … -
Extracting a fied value from JsonResponse in Django and pass it to Ajax Jquery
I'm creating a dropdown list select with ajax and Jquery in Django The expected behavior is when I choose the first select, the ajax will fill the second one This is what I have for while: models.py class MaintenanceEquipment(models.Model): equip_id = models.CharField(max_length=30, auto_created=False, primary_key=True) line_nm = models.CharField(max_length=20, blank=True, null = True) sequence = models.CharField(max_length=30, blank=True, null = True) equip_model = models.CharField(max_length=30, blank=True, null = True) def __str__(self): return self.equip_id views.py: def maintenanceIssueView(request): equipment_list = MaintenanceEquipment.objects.all() context = {'equipment_list':equipment_list} return render(request, 'maintenance/maintenanceIssue.html', context) def load_equipment(request): from django.core import serializers if request.method == 'GET': line_nm = request.GET.get('line_nm') equipment = MaintenanceEquipment.objects.filter(line_nm=line_nm) instances = serializers.serialize('json', equipment) print(instances) return JsonResponse({ "status_code": 200, "instances": instances, }, safe=False) urls.py: urlpatterns = [ path('maintenanceIssueView/', views.maintenanceIssueView, name="maintenanceIssueView"), path('ajax/load_equipment/', views.load_equipment, name="ajax_load_equipment"), ] maintenanceIssue.html: <form method="POST" id="maintenanceForm" data-equipment-url="{% url 'ajax_load_equipment' %}" novalidate> {% csrf_token %} <div style="text-align:left;" class="container-fluid"> <div style="text-align:left;" class="form-row"> <div class="form-group col-md-6"> <label for="line_nm" style="font-size:medium;">Line</label> <select class="form-control" id="line_nm" name="line_nm" > {% for instance in equipment_list %} <option id="{{ instance.line_nm }}" value="{{ instance.line_nm }}">{{ instance.line_nm }}</option> {% endfor %} </select> </div> <div class="form-group col-md-6"> <label for="sequence" style="font-size:medium;">Machine</label> <select class="form-control" id="sequence" name="sequence"></select> </div> </div> </div> </form> <script> $("#line_nm").change(function () { var url = $("#maintenanceForm").attr("data-equipment-url"); var line_nm = $(this).val(); $.ajax({ url: url, … -
Pycharm / Django defer Oracle Database connection
I have a Django project that connects to an Oracle database - implemented in PyCharm. I would like the app to monitor the connection and display a status as to whether the database is up or down. I stopped the listener to simulate an error. However, when I start the PyCharm server to test the functionality, the app immediately attempts a database connection and fails. Is it possible to defer the database connection until I can command one within the app? Here is the error traceback on server startup: C:\Users\steve\PycharmProjects\Tools\venv\Scripts\python.exe C:/Users/steve/PycharmProjects/Tools/Tools/manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\steve\PycharmProjects\Tools\venv\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\steve\PycharmProjects\Tools\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\steve\PycharmProjects\Tools\venv\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\steve\PycharmProjects\Tools\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\steve\PycharmProjects\Tools\venv\lib\site-packages\django\db\backends\oracle\base.py", line 229, in get_new_connection return Database.connect( cx_Oracle.DatabaseError: ORA-12541: TNS:no listener The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\steve\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\steve\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\steve\PycharmProjects\Tools\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper … -
Django dropdown list - change to None during edit
I have a model with month choice field (from January to December). When I want to edit model by generic UpdateView, field with month is shown by '----', but I don't want to change the month. Is there a proper way to display in form month that was decalared when creating object? In model: months_choice =( "1": "January", "2": "February", and so on ) date = models.CharField(max_length=3, choices=months_choice) Rendered form shows this: [I want display here the month that was declared earlier] [1]: https://i.stack.imgur.com/cUys8.png