Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
function print doesn't work in skulpt.min.js on django
I try to use skulpt in my django project i'm testing juste the instruction : print("hello") like this: <script src="{% static 'js/skulpt.min.js' %}" type="text/javascript"></script> <script src="{% static 'js/skulpt-stdlib.js' %}" type="text/javascript"></script> function runit(prog) { // var prog = document.getElementById("yourcode").value; // var mypre = document.getElementById("output"); // mypre.innerHTML = ''; prog = prog; prog = "print('hello')"; Sk.canvas = "mycanvas"; Sk.pre = "output"; Sk.configure({ output: outf, read: builtinRead, __future__: Sk.python3 }); try { var mypre = document.getElementById("output"); mypre.innerHTML = ""; eval(Sk.importMainWithBody("<stdin>", false, prog)); } catch (e) { // alert(e.toString()) var mypre = document.getElementById("output"); mypre.innerHTML = mypre.innerHTML + e.toString(); } } function outf(text) { var mypre = document.getElementById("output"); var bonneReponse = document.getElementById("trace_output").value.replace("&nbsp", " "); mypre.innerHTML = mypre.innerHTML + text; } } function builtinRead(x) { if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined) throw "File not found: '" + x + "'"; return Sk.builtinFiles["files"][x]; } ExternalError: TypeError: Cannot read properties of undefined (reading 'write') on line 1 when i switch to python 2 using skulpt.js instead of skulpt.min.js it works -
Live search in Django admin?
How would I implement live search in Django's admin panel? I want the change_list page to function with Ajax and return the search results without refreshing the page. Does Django expose any ModelAdmin methods that can implement such behaviour? I.e. change the response type from a regular HttpResponse to JsonResponse? -
DRF post nested object
I`m trying to post this json object { "name": "Country Name", "description": "Description here...", "generalInfo": { "capital": "Capital", "population": "Population", "highestPeak": "HighestPeak", "area": "Area" }, "timelineData": [ { "name": "Name 1", "ruler": "Ruler", "dateStart": "dateStart", "dateEnd": "dateEnd", "description": "description" }, { "name": "Name 2", "ruler": "Ruler", "dateStart": "dateStart", "dateEnd": "dateEnd", "description": "description" }, { "name": "Name 3", "ruler": "Ruler", "dateStart": "dateStart", "dateEnd": "dateEnd", "description": "description" } ] } But I`m receiving this error ValueError at /countries/ Cannot assign "OrderedDict([('capital', 'Capital'), ('population', 'Population'), ('highestPeak', 'HighestPeak'), ('area', 'Area')])": "Country.generalInfo" must be a "GeneralInfo" instance. Request Method: POST Request URL: http://127.0.0.1:8000/countries/ Django Version: 4.0.3 Here are my models.py: class GeneralInfo(models.Model): capital = models.CharField(max_length=200) population = models.CharField(max_length=200) highestPeak = models.CharField(max_length=200) area = models.CharField(max_length=200) class TimelineData(models.Model): name = models.CharField(max_length=200) ruler = models.CharField(max_length=200) dateStart = models.CharField(max_length=200) dateEnd = models.CharField(max_length=200) description = models.TextField(default='Description here...') class Country(models.Model): name = models.CharField(max_length=200, db_index=True) description = models.TextField(default='Description here...') generalInfo = models.ForeignKey(GeneralInfo, on_delete=models.CASCADE) timelineData = models.ManyToManyField(TimelineData) I have also overridden the create method for CountrySerializer and here are my serializers.py: class TimelineDataSerializer(serializers.ModelSerializer): class Meta: model = TimelineData fields= '__all__' class GeneralInfoSerializer(serializers.ModelSerializer): class Meta: model= GeneralInfo fields = '__all__' class CountrySerializer(serializers.ModelSerializer): timelineData = TimelineDataSerializer(many=True) generalInfo = GeneralInfoSerializer() class Meta: model= Country fields = … -
How to indexes ImageField in django-elasticsearch-dsl
Рello everyone! I am writing a site on Django. I am making a search system using django-elasticsearch-dsl. And I have a problem when I need to index an ImageField field in the BookDocument class in order to display a book image on the book search page Here is my Book model: books/models.py class Book(models.Model): title = models.CharField(max_length=120, default=' ', verbose_name='Назва') description = models.TextField(verbose_name='Опис') category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категорія') date_at = models.DateField(auto_now_add=True, verbose_name='Дата створення') image = models.ImageField(upload_to='photos/%Y/%m/%d/') authors = models.ManyToManyField(Author, verbose_name='Автори') content = models.FileField(upload_to='contents/%Y/%m/%d/', blank=True) price = models.IntegerField(verbose_name='Ціна', default='0') Here is my BookDocument class: search/documents.py @registry.register_document class BookDocument(Document): image = FileField() class Index: name = 'books' settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = Book fields = [ 'id', 'title', 'description', ] but the images are not displayed on the search page, and since there is no ImageField field in django-elasticsearch-dsl, and only this file is suitable for storing file data, I do not know how to change this behavior Perhaps someone has encountered such a problem and knows how to make it work -
Pytest keep missing return line in the same function that has been ran multiple time
I'm doing a project in django and I have 2 serializer like this: parent_serializer.py class ParentSerializer(serializer.Serializers): action = ChildSerializer() child_serializer.py class ChildSerializer(serializer.Serializers): ... def validate(self, attrs): ... **return attrs** There is an if statement in the validate function and i wrote all the tests needed for the if statement, but pytest coverage keep saying that it missed the return statement line (return attrs), which imo, supposed to run in every test case. I did try everything possible but nothing works. Please help me on that one -
Unable to get through .is_valid() validation of Django for POST request for Images field
The POST request for images does not get validated on my form, when i created a new form it worked fine and was able to save the images. but going back to same old form i tried making the body part similar to the old one but got the same message even tried to check the console for form.errors but couldn't find anything.Still trying to figure out what is it that's missing in input as per the console log ValidationError[This field is required]. console log for the POST Request made View.py function used to validate and get post models.py form.py ModelForm main layout html template <!DOCTYPE html> <html lang="en"> <head> <!-- <title>Encyclopedia</title> --> <title>{% block title %} {% endblock %}</title> <link rel="stylesheet" href="..\..\static\mywikiapp\style.css"> {% block head %} {% endblock %} </head> <body> <div class="main"> <div class="leftpart"> <h2 id="leftheading">Wiki</h2> <div class="search_container_confinement"> <form> <div class="searchcontainer"> <input type="text" name="q" placeholder="Search Encyclopedia"> </div> </form> </div> <div class="listcontainer"> <ul id="left_col_li"> <li><a href="{% url 'mywikiapp:index' %}">Home</a></li> <li><a href="{% url 'mywikiapp:create_new' %}">Create New Page</a></li> <li><a href="{% url 'mywikiapp:add_images' %}">Upload Images</a></li> <li><a href="">Random Page</a></li> </ul> </div> <div class="navbar"> <div> {% block navbar %}{% endblock %} </div> </div> </div> <div class="rightpart"> <!-- <h1>All Pages</h1> <div> <ul> <li>Css</li> <li>Django</li> <li>Git</li> … -
Extracting case insensitive words from a list in django
I'm extracting values from a csv file and storing these in a list. The problem I have is that unless there is an exact match the elements/strings don't get extracted. How would I go about a case insensitive list search in Django/Python? def csv_upload_view(request): print('file is being uploaded') if request.method == 'POST': csv_file_name = request.FILES.get('file') csv_file = request.FILES.get('file') obj = CSV.objects.create(file_name=csv_file) result = [] with open(obj.file_name.path, 'r') as f: f.readline() reader = csv.reader(f) #reader.__next__() for row in reader: data = str(row).strip().split(',') result.append(data) transaction_id = data[1] product = data[2] quantity = data[3] customer = data[4] date = parse_date(data[5]) try: product_obj = Product.objects.get(name__iexact=product) except Product.DoesNotExist: product_obj = None print(product_obj) return HttpResponse() Edit: the original code that for some reason doesn't work for me contained the following iteration: for row in reader: data = "".join(row) data = data.split(';') data.pop() which allows to work with extracted string elements per row. The way I adopted the code storing the elements in a list (results=[]) makes it impossible to access the elements via the product models with Django. The above mentioned data extraction iteration was from a Macbook while I'm working with a Windows 11 (wsl2 Ubuntu2204), is this the reason that the Excel data needs … -
Django 3.2.3 Pagination isn't working properly
I have a Class Based View who isn't working properly (duplicating objects and deleting some) Tested it in shell from django.core.paginator import Paginator from report.models import Grade, Exam f = Exam.objects.all().filter(id=7)[0].full_mark all = Grade.objects.all().filter(exam_id=7, value__gte=(f*0.95)).order_by('-value') p = Paginator(all, 12) for i in p.page(1).object_list: ... print(i.id) 2826 2617 2591 2912 2796 2865 2408 2501 2466 2681 2616 2563 for i in p.page(2).object_list: ... print(i.id) 2558 2466 2563 2920 2681 2824 2498 2854 2546 2606 2598 2614 -
How do I use a DB procedure from the django ORM?
For example, in MySQL, I would write: SELECT id, my_calc(id, '2022-09-26') as calculated FROM items; How do I tell the ORM to use this DB procedure and pass the parameters? Would I have to define a Func? Items.objects.annotate(calculated=...) -
No Post Data - Testing Django View with AJAX Request
I'm currently testing my Django application in order to add some CI/CD to it. However, most of my views contain an AJAX section for requests sent by the frontend. I saw that for testing those I can only just do something like this: response: HttpResponseBase = self.client.post( path=self.my_page_url, content_type='application/json', HTTP_X_REQUESTED_WITH='XMLHttpRequest', data={ 'id': '123456', 'operation': "Fill Details" } ) The XMLHttpRequest is making most of the magic here (I think), by simulating the headers that an AJAX request would have. However, in my view I have a section where I do: request.POST['operation'], but this seems to fail during tests since apparently no data is passed through the POST attribute. Here's the code of the view that I'm using right now: MyView(request): is_ajax: bool = request.headers.get('x-requested-with') == 'XMLHttpRequest' if is_ajax: operation = request.POST['operation'] I checked and my data is being passed in request.body. I could include an or statement, but it would be ideal if the code for views was not modified because of tests. Is there any way to get the client.post method to pass the data through the POST attribute? -
Sending a message to a specific group in Django Channels
I would like to connect every user who visits a particular page. Let's call this the, 'Waiting Room' to a websocket. When the user connects to a websocket they are subscribed to a group. The group is named after the user's user_id. So User1 and User would connect to the websocket and be subscribed to the groups; 1 and 2 respectively. After the user is connected, I trigger a method that sends a user_id the user has been matched with and room_id to my server. Assuming User1 is matched with User2. User1 would send User2 and room_id to the server. I then send a message back to the group associated with the user_id received. Meaning I send a message from User1's websocket to User2's client. However, when I implement this logic no messages are received by User2. This is what I have in consumers.py: class PracticeConsumer(AsyncConsumer): username_id = None async def websocket_connect(self, event): username = self.scope['user'] username_id = str(await self.get_user(username)) group_name = username_id await self.channel_layer.group_add( '{}'.format(group_name), self.channel_name ) await self.send({ "type": "websocket.accept" }) async def websocket_receive(self, event): received = event["text"] invite_data = received.split() matched_user = invite_data[0] username = invite_data[2] user_id = str(await self.get_user(matched_user)) my_response = { "message": "!!!!the websocket is … -
How to set priority in CELERYBEAT_SCHEDULE config?
In my Django app, I am trying to set the priority value to 6 for a Celery beat task, but the below doesn't work. What's the right way to set this value? I have other tasks in this config and want to set different priority values. CELERYBEAT_SCHEDULE = { 'some_task_name': { 'task': 'app_name.tasks.some_task_name', 'schedule': crontab(hour=18, minute=30), 'options': {'priority': 6} } } -
combining two arrays in Django
I'm working on a web that displays posts (like twitter). In Django views.py I wrote a code that makes two arrays and assigned the arrays to be used in the HTML template. views.py: def arrays(request): allposts = posts.objects.all() m = ['empty', 'like', 'unlike', 'like', 'unlike'] aa = [0, 1, 2, 3, 4] return render(request, "network/index.html" ,{'allposts': allposts, 'm':m, 'aa':aa}) the (m) array represents whether each post is liked or not(each object in the array has the arrangement which is equal to the post id) while the (aa) represents the id of each post in the database in index.html I want to show 'like' or 'unlike' for each post according to the arrangement in the array. in index.html {% for post in allposts %} <div> {% for object in aa %} {% if object == post.id %} <p>{{m.object}}</p> {% endif %} {% endfor %} </div> {%endfor %} but the problem is that I can't match the aa array and the m array in the HTML template but I can display {{m.1}} instead of {{m.object}}. so how can I match those two arrays? -
TypeError Error during template rendering
I'm facing this error when I add ForeignKeys in my Order table enter image description here Here are my tables enter image description here But when I remove the those ForeignKeys it works fine without giving an error... enter image description here enter image description here ...But I also can't access other tables enter image description here -
Getting None instead of Value from HTML form (Django)
Here below my HTML-template <form action="{% url 'test-data' %}" method="POST" name="test" enctype="multipart/form-data"> {% csrf_token %} <h2> {{ result }} </h2> <div class="d-flex justify-content-center"> <button type="submit" class="btn btn-primary">Show</button> </div> </form> my View.py def show_result(request): if request.method == "POST": result = request.POST.get('test') return HttpResponse(result) By pressing the button 'Show' I got None instead of {{ result }} value. So, how I can get a Value inside curly brackets? Thanks a lot for any help. -
Unable to POST data with the Django REST Framework : Not Found
I'm trying to figure out why the Django REST Framework throws a 404 Not Found when I POST data with the code below, because when I load the browsable API with the URL it correctly displays the object list with the HTML form to POST data. The Django project that serve the API run in a Docker container as well as the client, but in a separate Docker host. How could I fix the issue ? Server Console logs django-1 | Not Found: /api/strategy/target/ django-1 | [26/Sep/2022 14:27:05] "POST /api/strategy/target/ HTTP/1.1" 404 23 project/project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("api/strategy/", include("strategy.urls")), ] strategy/urls.py from django.urls import path, include from rest_framework import routers from strategy.api.views import TargetViewSet router = routers.DefaultRouter() router.register("target", TargetViewSet, basename="targets-list") urlpatterns = [ path('', include(router.urls)), ] strategy/views.py from rest_framework import viewsets from strategy.api.serializers import TargetSerializer from rest_framework.decorators import permission_classes from rest_framework.permissions import IsAdminUser # Create new model @permission_classes([IsAdminUser]) class TargetViewSet(viewsets.ModelViewSet): serializer_class = TargetSerializer queryset = Target.objects.all() Client res = requests.post("http://1.2.3.4:8001/api/strategy/target/", data=data, headers={'Authorization': 'Bearer {0}'.format(token)} ) -
Django Integrity Error at /accounts/login/ 1364, "Field 'id' doesn't have a default value"
I get the Django error when clicking on log in. Unfortunately I don't know which table is causing the problem. My complete error: IntegrityError at /accounts/login/ (1364, "Field 'id' doesn't have a default value") Request Method: POST Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 4.0.6 Exception Type: IntegrityError Exception Value: (1364, "Field 'id' doesn't have a default value") Exception Location: c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\MySQLdb\connections.py, line 254, in query Python Executable: c:\xampp\htdocs\django\ksfexpert\env\Scripts\python.exe Python Version: 3.10.0 Python Path: ['C:\xampp\htdocs\django\ksfexpert\src', 'C:\Users\kit\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\kit\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\kit\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\kit\AppData\Local\Programs\Python\Python310', 'c:\xampp\htdocs\django\ksfexpert\env', 'c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages'] Server time: Mon, 26 Sep 2022 14:46:52 +0000 Traceback Switch to copy-and-paste view c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\db\backends\utils.py, line 89, in _execute return self.cursor.execute(sql, params) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\db\backends\mysql\base.py, line 75, in execute return self.cursor.execute(query, args) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\MySQLdb\cursors.py, line 206, in execute res = self._query(query) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\MySQLdb\cursors.py, line 319, in _query db.query(q) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\MySQLdb\connections.py, line 254, in query _mysql.connection.query(self, query) … Local vars The above exception ((1364, "Field 'id' doesn't have a default value")) was the direct cause of the following exception: c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\views\generic\base.py, line 84, in view return self.dispatch(request, *args, **kwargs) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\utils\decorators.py, line … -
How İs it possible apply filtering to the imported data while using django-import-export package
By applying Form (not using Admin Panel) it is possible for users to import their data in xlsx format to the models practically. I have two models Task & Item. Each Task object has many Item objects in it. When it is intended to import a data file which includes mixed data, namely more than one tasks created by different user with their items, Django-import-export utility import all of them. But in some cases it is required to limit the import process by allowing the tasks which are created by the user itself and not whole task data. Can I overcome this issue by appling filter to data? def importData(request,pk): if request.method == 'POST': #query = Item.objects.filter(task_id = pk) item_resource = ItemResource() dataset = Dataset() new_items = request.FILES['importData'] imported_data = dataset.load(new_items.read(), format='xlsx') result = item_resource.import_data(dataset, dry_run=True) if not result.has_errors(): item_resource.import_data(dataset, dry_run=False) converted = str(pk) return HttpResponseRedirect('http://127.0.0.1:8000/'+'checklist/task/'+ converted + '/') else: return HttpResponse('Your Data is not Proper ! Please Try Again...') return render(request, 'checklist/import.html')enter code here class Task(models.Model): user = models.ForeignKey(User, verbose_name="Kullanıcı", on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(verbose_name="Kontrol Listesi Başlığı", max_length=200) description = models.TextField(verbose_name="Açıklama", null=True, blank=True) complete = models.BooleanField(verbose_name="Tamamlandı mı?", default=False) created = models.DateTimeField(auto_now_add=True, verbose_name='Kayıt Tarihi') update_date = models.DateTimeField(auto_now=True, verbose_name='Son Güncelleme') … -
How to use your own database for user authentication [closed]
I'am have created database with user data: class Users(models.Model): login = models.CharField(max_length=32, blank=False, unique=True, verbose_name='Login') password = models.CharField(max_length=255, blank=False, verbose_name='Password') email = models.EmailField(max_length=255, unique=True, verbose_name='Email') balance = models.IntegerField(verbose_name='Balance', null=True) class Meta: verbose_name = 'Users' verbose_name_plural = 'Users' ordering = ['id'] def __str__(self): return self.login I wanna use this database for register and auth. But not default database by django. What should I do? -
AttributeError: 'FieldInstanceTracker' object has no attribute 'saved_data'
Problem with a post_save signal? class Book(models.Model): class = models.ForeignKey(Class, on_delete=models.CASCADE, null=False) library = models.ForeignKey(Library, on_delete=models.CASCADE, null=False) created_at = models.DateTimeField(auto_now_add=True) tracker = FieldTracker() def update_service(sender, instance, **kwargs): if not library.exists(): book.delete() post_save.connect(update_service, sender=Library) lib/python3.7/site-packages/model_utils/tracker.py in set_saved_fields(self, fields) 106 self.saved_data = self.current() 107 else: --> 108 self.saved_data.update(**self.current(fields=fields)) 109 110 # preventing mutable fields side effects AttributeError: 'FieldInstanceTracker' object has no attribute 'saved_data' -
AttributeError when attempting to get a value for field `country` on serializer
I'm running into the following error, and been stuck on it the last two weeks. I don't know what it could possibly mean by 'int' object has no attribute 'country' in my case, and country exists in my serializer and model. If I remove country from the serializer, I get the same error with post_code. I haven't got a clue what could be going wrong Got AttributeError when attempting to get a value for field `country` on serializer `AddressSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `int` instance. Original exception text was: 'int' object has no attribute 'country' View: class Address(generics.RetrieveUpdateDestroyAPIView): permission_classes = [AddressPermission] queryset = Addresses.objects.all() def get_object(self): try: if self.request.COOKIES['access_token'] is not None: obj = get_object_or_404(self.get_queryset(), user=NewUser.objects.get(id=jwt.decode(self.request.COOKIES['access_token'], settings.SECRET_KEY, algorithms=["HS256"])['user_id'])) self.check_object_permissions(self.request, obj) return obj except: return status.HTTP_401_UNAUTHORIZED serializer_class = AddressSerializer Serializer: class AddressSerializer(serializers.ModelSerializer): class Meta: fields = ('country', 'organization_name', 'administrative_area', 'sub_administrative_area', 'locality', 'post_code', 'thoroughfare', 'premise') model = Addresses Model: class Addresses(models.Model): country = models.CharField(max_length=2) organization_name = models.CharField(max_length=150, null=True, blank=True) # State/Province administrative_area = models.CharField(max_length=150, null=True, blank=True) # County/District/Municipality sub_administrative_area = models.CharField(max_length=150, null=True, blank=True) locality = models.CharField(max_length=150, null=True, blank=True) post_code = models.CharField(max_length=12) # the actual street address thoroughfare = models.CharField(max_length=95) # … -
Best practice to resolve Now() vs timezone.now() sync differences across databse and web workers?
I have a checkconstraint on a django model, applied on a PostgreSQL database: from django.db import models from django.db.models import CheckConstraint, Q, F from django.db.models.functions import Now class Event(models.Model): mydate = models.DatetimeField() class Meta: constraints = [ CheckConstraint( check = Q(mydate__lte=Now()), name = 'check_my_date', ), ] The constraint ensures that mydate can not be in the future, but constraining it to be less than Now() which returns the start of the transaction time on the PostgreSQL server. I set mydate programmatically in the app: from django.utils import timezone now = timezone.now() myevent = Event.objects.create(mydate=now) However, this will often fail the checkconstraint. I assume this is because the setup I am using is Heroku, with a separate PostgreSQL and worker (app) instance. The PostgreSQL Now() timestamp appears to run a few seconds behind the web worker. What is best practice to sync/resolve this conflict? -
How to properly prefetch_related in django
One query is more than 10 times faster than the other, it looks like prefetch_related has no effect. How to do it correctly? # 400ms test = PZItem.objects.all().aggregate(Sum('quantity')) # 4000ms test = PZ.objects.prefetch_related('pzitem_set').aggregate(Sum('pzitem__quantity')) -
Need Help in django form widgets
I am in a middle of a project. I need help in using widgets. I have a Model for which i want a model form : My model is : class Appointments(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) app_time = models.DateTimeField() diognoses = models.TextField(max_length=1000, null=True, blank=True) prescriptions = models.TextField(max_length=250, null=True, blank=True) class Meta: unique_together = ('doctor', 'patient', 'app_time') def __str__(self): st = str(self.patient.user.name)+str(self.doctor.user.name) return st The corresponding model form is : class AppointmentBookForm(forms.ModelForm): app_time = forms.DateTimeField(widget=forms.SplitDateTimeWidget()) class Meta: model = Appointments fields = ['doctor','app_time'] Now for app_time I have split the date and time field which is already working fine. Now I want a dropdown for date and a suitable widget for time. The time should contain only hours and minutes. And Finally I also want to provide the options for timing depending on the date and doctor. -
SQLite to PostgreSQL Transfer - Connection Refused: Is the server running on that host and accepting TCP/IP connections?
Goal: Be able to solve for "Is the server running on that host and accepting TCP/IP connections?" error message. I have recently moved my Django database from SQLite to PostgreSQL following the steps on this link. When I run python manage.py runserver, I have no problems. I am launching the site through Heroku via GitHub, which deploys successfully. When I clicked on the Heroku site, I initially got a 500 error, which when I turned Debug = True, I received the following headline message: Exception Type: OperationalError at / Exception Value: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? The port of 5432 is correct. From what I have read, the issue comes from listen_addresses needing to be * but I cannot find this file on my Mac. I tried changing "Host name / address" to "*" from "localhost" in pgAdmin4 - this did not work. Full excerpt below: Environment: Request Method: GET Request URL: https://sherbert.herokuapp.com/ Django Version: 4.1.1 Python Version: 3.10.6 Installed Applications: ['posts', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template …