Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Flutter WEB sending file to Django Rest Framework Backend
So in my flutter front end (WEB). I am using Image_picker and then image_cropper packages to obtain a file. I know flutter web doesn't support Dart/io so instead you have to send your image in a mulitpart request FromBYtes. Normally for an ios/android flutter app you can use fromFile. Now I send that to my backend as bytes. however, my django rest framework view isnt able to save the image to my model. here is the code and step by step: final imagetoSendToAPIasbytes = await cropImageFile.readAsBytes(); List<int> imageaslistint = imagetoSendToAPIasbytes.cast(); final response = await uploadImage(imageaslist, profileid); uploadimage function: var profilepic = await http.MultipartFile.fromBytes( "profilepic", imageaslistint); request.files.add(profilepic); http.StreamedResponse response = await request.send(); var responseByteArray = await response.stream.toBytes(); ofcourse this is not the full code. But I am able to send it to the back end. my django backend view to handle: @api_view(['PATCH', ]) @throttle_classes([updateprofileprofilepicThrottle]) @parser_classes((MultiPartParser, FormParser, JSONParser)) def updateprofileprofilepic(request,): try: user = request.user except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) try: if request.method == "PATCH": profileobjid= json.loads(request.data['profileid']) profileobj = Profile.objects.get(creator = user, id = profileobjid) profileobj.profilepic.delete(False) print(request.FILES['profilepic']) print(json.loads(request.data['profilepic'])) profileobj.profilepic= json.loads(request.data['profilepic']) profileobj.save() usualy (request.FILES['profilepic']) allows me to save a file (from ios/android) however thats when its sending as a mulitipart request.fromPATH. So now (json.loads(request.data['profilepic'])) im … -
I want to autogenerate a username in django
I want to create my own username for users in django from django.contrib.auth import get_user_model from datetime import date from django.dispatch import receiver from django.db.models.signals import pre_save from django.db import models User = get_user_model() # auto username @receiver(pre_save, sender=User) def set_username(sender, instance, created, **kwargs): if created: instance.username = 'User-' + str(date.year) + '-' + str(instance.id) instance.save() so I created this signals.py file and I added this signals file to the app.py file in the app context but still it is not making any progress can someone help me to generate an username while filling the form. -
How to PREVENT AWS EB from running migration
I have a Python/Django app and I'm trying to get it deployed to AWS Elastic Beanstalk. I'm using the EB CLI. What I've run into is similar to others (e.g. Deploying Django to Elastic Beanstalk, migrations failed). But I can't get past the migration failure that is blocking a successful eb deploy. I removed the .ebextensions/db-migrate.config file from my project, but it seems like it's cached somewhere since the logs still show this: ... 2022-12-01 22:14:21,238 [INFO] Running config postbuild_0_ikfplatform 2022-12-01 22:14:21,272 [ERROR] Command 01_migrate (source /var/app/venv/*/bin/activate && python3 manage.py migrate) failed 2022-12-01 22:14:21,272 [ERROR] Error encountered during build of postbuild_0_ikfplatform: Command 01_migrate failed ... How can I prevent EB from somehow magically running the migration command (which is no longer in my project)? FYI: I can successfully migrate the RDS DB from my local computer which is fine for now. -
How to generate plaintext files from an HTML template?
Getting plaintext files from an HTML using python code. Like Django, using jinja templating from the jinja2 library to display data parsed into the context from the view function. I'll like to know all the different ways in which I can get the plaintext version of the jinja template, and most of all "it should be formatted". Example Jinja template <div>{{ book.name }}</div> <p> The author of the book is {{ book.author }}.</p> <p> For more description, go to "{{ book.url }}"</p> <div> <p>Some important notions on the book</p> <ol> {% for items in points %} <li>{{ items }}</li> {% endfor %} </ol> </div> </div> Plaintext version Python For Beginners The author of the book is John Doe. For more description, go to "https://mybooks.example.com/book1" Some important notions on the book - Variable - Strings - File R/W operations - Loops - Conditions what different options can I have to do this in Django or python and getting over a 100 of such files from the database. -
Loader pops up and hangs when there is a form error on page submission
I am currently using this javascript to popup a loader when I click the submit button. The loader works fine when there is no form error and shows the response after waiting. However, the loader keeps spinning when there is a form input error and the request does not get submitted to backend but loader keeps spinning infinitely. $('#submitBtn').click(function () { $('#loader').removeClass('hidden') // $('#loader').html('Loading').addClass('loadcontent') // $("#loading").html("Loading"); }) </script>``` How can I make this loader script run only when there is no form input error? I am using Django, Javascript, html and I am a beginner in JS. -
Django project to show list of categories as list then the category url displays all posts in that category
I am working on a Django project where I would like to display list of all categories on the homepage as links. When one clicks a category, they are taken to a page whereby all the posts under that field are displayed. Inside the list of posts page, I would like to show the title as the name of the category. Also I would like the url to have the name of the category. My code is working fine in rendering those pages, but my issue is that it uses id instead of the slug field. When I replace .id with .slug, I get the error: ValueError at /category/electricals Field 'id' expected a number but got 'electricals` Here is my Models.py: class Category(models.Model): title = models.CharField(max_length=100) image = models.ImageField(null=True, blank=False) slug = models.SlugField(unique=True, null=True) def __str__(self): return self.title class Service(models.Model): category = models.ForeignKey('Category', on_delete=models.CASCADE) title = models.CharField(max_length=100) image = models.ImageField(null=True, blank=False) description = models.TextField(null=False, blank=False) service_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) slug = models.SlugField(unique=True, null=True) def __str__(self): return self.title And here is my views.py; def landing_page(request): categorys = Category.objects.all() context = {'categorys':categorys} return render(request, 'users/homepage.html', context) def categories(request, cats): category_services = Service.objects.filter(category=cats) context = {'cats':cats,'category_services':category_services } return render(request, 'users/categories.html', context) … -
How can get products for active owners (users) only with Django Rest Framework?
I'm creating an e-commerce API with DRF. I would like to retrieve and display only active products from active owners (users) using a ModelViewSet How can I do this? Here is my code : views.py class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer parser_classes = (MultiPartParser, FormParser) search_fields = ['title', 'description'] ordering_fields = ['price', 'last_update'] permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsVendorOrReadOnly, IsOwnerOrReadOnly] def get_queryset(self): return Product.objects.filter(is_active=True) # WHEN I'M USING THIS COMMENT CODE, I CAN'T RETRIEVE ONE PRODUCT BY PK # products = Product.objects.all() # new_products = [] # for p in products: # if p.owner.is_active and p.is_active: # new_products.append(p) # return new_products def perform_create(self, serializer): serializer.save(owner=self.request.user) -
Django Serializer - how to check if a ListField is valid?
I'm currently working on a practice social media app. In this app, current users can invite their friends by email to join the app (specifically, joining a 'channel' of the app, like Discord). I'm working on unit tests to ensure that emails are valid. I'm working with serializers for the first time and I'm trying to move past some issues I've been having. Functionality: the user enters in a friend's email address. For the purposes of this test, the email address needs to be at least 6 characters long. So something like "a@a.co" (6 char) would be acceptable, but "a@a.c" (5 char) would not be accepted. Users can enter up to 10 emails at a time. What I'm currently struggling with is what function to use for "is_valid"? I know Django forms has something for this, but I haven't found a satisfactory method for serializers. Here is what's currently in serializers.py. from django.core.validators import MinValueValidator, MaxValueValidator from rest.framework.fields import ListField from rest.framework import serializers class EmailList(ListField): """Will validate the email input""" def to_internal_value(self, data): # if the EmailList is not valid, then a ValidationError should be raised--here's where I'm wondering what to put raise serializers.ValidationError({"invalid_email": "Email is invalid, please recheck".}) … -
Django future scheduling app that needs a previously filled out db
I am stuck with Django trying to create a "To" and "From" for the entire database (on a daily timescale). I need to catalogue events that will happen years in the future, and have them able to be queried by a user for later presentation. Here is what I am after: So I would like Django to make a daily database from now until say 2050. So my question is, do I need to make a db beforehand using MS SQL and have it prefilled out? Or is there some way to utilize Django with this type of task? My model creation is pathetic but here it is anyways: class Coal(models.Model): datenum = models.DateField(db_column='DateNum', max_length=10, blank=True, null=True) GN1 = models.IntegerField(default = 0) GN2 = models.IntegerField(default = 0) KnownOutages = models.IntegerField(default = 0) UnknownMonthlyAmount = models.IntegerField(default = 0) -
ModuleNotFoundError: No module named 'proj'
I ran into this problem and searched many resources but couldn't find a solution. My Django project was running successfully on my local. But when I deployed it to the server, it kept getting the following error. ModuleNotFoundError: No module named 'proj' I installed all the required libraries and all the settings should be correct as they worked fine on my OSX. (venv) [root@10-10-7-140 vanilla]# python manage.py runserver Traceback (most recent call last): File "/data/www/vanilla/vanilla/venv/lib/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/data/www/vanilla/vanilla/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 74, in execute super().execute(*args, **options) File "/data/www/vanilla/vanilla/venv/lib/python3.8/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/data/www/vanilla/vanilla/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/data/www/vanilla/vanilla/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/data/www/vanilla/vanilla/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/data/www/vanilla/vanilla/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/python3.8/python3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'proj' … -
Problem with Google Charts using Python Django
Started getting this problem once I tried using 2 graphs at the same time on my html+css template. I'm doing arrays like this on my views.py file (sending to the html file as context variable): array1 = [["x axis", "y axis"] , ["a", 0] , ["b", 3], ["c", 1]] array2 = [["x axis", "y axis"] , ["j", 1] , ["k", 5], ["l", 8]] Then I'm showing my graphics like this: <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['bar']}); google.charts.setOnLoadCallback(drawChart1); function drawChart1() { var data1 = google.visualization.arrayToDataTable({{ array1|safe }}); var options1 = { chart: { title: 'This', subtitle: 'That', }, backgroundColor: '#FFFFFF', bars: 'horizontal' // Required for Material Bar Charts. }; var chart1 = new google.charts.Bar(document.getElementById('barchart_material1')); chart1.draw(data1, google.charts.Bar.convertOptions(options1)); } </script> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['bar']}); google.charts.setOnLoadCallback(drawChart2); function drawChart2() { var data2 = google.visualization.arrayToDataTable({{ array2|safe }}); var options2 = { chart: { title: 'this', subtitle: 'that', }, backgroundColor: '#FFFFFF', bars: 'horizontal' }; var chart2 = new google.charts.Bar(document.getElementById('barchart_material2')); chart2.draw(data2, google.charts.Bar.convertOptions(options2)); } </script> <div class="card_view"> <div id="barchart_material1" style="width: 700px; height: 300px;"></div> </br> </br> <div id="barchart_material2" style="width: 700px; height: 300px;"></div> </br> </br> </div> But then I get a "Undefined renderer" kinda problem. Any help? -
Keep getting MIME error when trying to attatch css file Django
I know this question has been asked before but I have tried to implement the answers to those forums but none have worked for me so far. Here is my folder: Files Here is my html file: {% include 'main.html' %} {% load static %} <head> <link rel="stylesheet" type="text/css" href="projects.css"/> </head> <body> <h1 style="text-align: center">Projects</h1> <h1>{{projects}}</h1> {% for project in context %} {% with 'jweb/images/'|add:project.image as project_photo %} <div class="card-wrap"> <div class="card"> <h2 class="card-header">{{project.title}}</h2> <div class="card-image"> <img src="{% static project_photo %}"> </div> </div> </div> {% endwith %} {% endfor %} </body> {% include 'pagebottom.html' %} Here is my css: .card-wrap{ width: auto; } .card{ background: blue; padding:3rem; border:none; box-shadow: 0 2px 5px 0 rgb(0,0,.2); border-radius: .25rem; } .card-image{ min-width: 0; min-width: 0; } .card-image > img{ height:100%; width:100%; object-fit:contain; } Here is my settings.py: import os import mimetypes mimetypes.add_type("text/css", ".css", True) from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "django-insecure-zzk5%zz_)k%47o$9+-hocf_2azb@wj@)k89b=^18xk*80g!ekq" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = … -
First view in DJANGO tutorial -> Page not found (404)
I was doing tutorial "Writing your first Django app, part 1" and I got stuck in "Write your first view". I have fulfil all instructions regardings files. When I go to http://127.0.0.1:8000/ then I can see "The install worked successfully! Congratulations!" but if I go to http://localhost:8000/polls/ then I see: Page not found (404) Request Method: GET Request URL: http://localhost:8000/polls/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, polls/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. In this case according instructions I should see "Hello, world. You're at the polls index". I attached 2 files content and 2 interesting screens (why does it emphasize?). views.py urls.py views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] I was looking answer in Stack Overflow (also in hints) or YouTube but unfortunately without success. Interesting but in another computer it works, but on my … -
HTML table styling is behaving strange when generated with python, table in table?
I am generating a table in HTML from a Django model, and although the table headers and rows seem to be correct, the table is displaying strangely, with a seemingly differently formatted table as parent element. What is causing this behavior? I was not able to find supporting documentation... <style> table,th,td { border:2px solid green; border-spacing: 10px; } <div class="container"> <table id="labrequestoverview"> <tr> {% for item in model_headers %} <th>{{ item |capfirst }}</th> {% endfor %} </tr> {% for all_rows in query_results %} <tr> {% for every_column in all_rows %} <td>{{ every_column }}</td> {% endfor %} </tr> {% endfor %} </table> </div> -
what is best practices in having too many dynamic html elements in a single templates in django
pretty new to django and coding...I am currently building a page that has serveral independenent divs that get updated from a single click event. I have all these different divs(features) on a single page and I am starting its looking bad, cluttered. will dividing these different divs affect the functionality of the main page since i intend to have all these elements update dynamically independent of each other. and if it's possible, will it affect perfomance? I have a page full of divs that work. I am trying to break these divs into multiple html template elements using the extend feature in django {% extends 'template_name.html' %} will this work? -
Match with Django import_export with multiple fields
I would like to import a CSV in Django. The issue occurs when trying to import based on the attributes. Here is my code: class Event(models.Model): id = models.BigAutoField(primary_key=True) amount = models.ForeignKey(Amount, on_delete=models.CASCADE) value = models.FloatField() space = models.ForeignKey(Space, on_delete=models.RESTRICT) time = models.ForeignKey(Time, on_delete=models.RESTRICT) class Meta: managed = True db_table = "event" class Space(models.Model): objects = SpaceManager() id = models.BigAutoField(primary_key=True) code = models.CharField(max_length=100) type = models.ForeignKey(SpaceType, on_delete=models.RESTRICT) space_date = models.DateField(blank=True, null=True) def natural_key(self): return self.code # + self.type + self.source_date def __str__(self): return f"{self.name}" class Meta: managed = True db_table = "space" class Time(models.Model): objects = TimeManager() id = models.BigAutoField(primary_key=True) type = models.ForeignKey(TimeType, on_delete=models.RESTRICT) startdate = models.DateTimeField() enddate = models.DateTimeField() def natural_key(self): return self.name def __str__(self): return f"{self.name}" class Meta: managed = True db_table = "time" Now, I create the resource that should find the right objects, but it seems it does not enter into ForeignKeyWidget(s) at all: class AmountForeignKeyWidget(ForeignKeyWidget): def clean(self, value, row=None, **kwargs): logger.critical("<<<<< {AmountForeignKeyWidget} <<<<<<<") name_upper = value.upper() amount = Amount.objects.get_by_natural_key(name=name_upper) return amount class SpaceForeignKeyWidget(ForeignKeyWidget): def clean(self, value, row, **kwargs): logger.critical("<<<<< {SpaceForeignKeyWidget} <<<<<<<") space_code = row["space_code"] space_type = SpatialDimensionType.objects.get_by_natural_key(row["space_type"]) try: space_date = datetime.strptime(row["space_date"], "%Y%m%d") except ValueError: space_date = None space = Space.objects.get( code=space_code, type=space_type, source_date=space_date ) return … -
Get key, values from Queryset in Django
I want to create a chart using chart js in my Django application. I made a query from my Shift object to get employers' org name and count of job openings that each employer has published. The result is like this: queryset = Shift.objects.values('employer__org_name').annotate(count=Count('id')) #id is job id and employer org name is a foreign key from Employer object. query result: <QuerySet [{'employer__org_name': 'employer1_org', 'count': 10}, {'employer__org_name': 'employer2_org', 'count': 9}]> There are two employers in the dataset. The first one called "employer1_org" which has published 10 jobs in total, and the second one called "employer2_org", it has published 9 jobs. In the chart, the x axis would be "employer__org name" and y axis is "count of job openings". Perhaps I should get data like this? {"employer1_org":10},{"employer2_org":9} or what is your suggestion? This is my view: def chart(request): queryset = Shift.objects.values('employer__org_name').annotate(count=Count('id')) # to be filled # return render(request,'chart.html') -
Why does adding more fields to this widget lead to a keyError?
I'm working on a form in my Django project. I wanted to add a bootstrap class to my input fields. I tried to do this with the following code: class CategoryForm(ModelForm): class Meta: model = Category fields = '__all__' labels = { "sub_category":"Sub category (if any):" } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['category_name','sub_category','category_info','category_video'].widget.attrs.update({'class':'form-control'}) But when I load the page I get this: KeyError at /academy/category_form ('category_name', 'sub_category', 'category_info', 'category_video') Is this not possible? Do I have to add a new line for every field in my form? So like this: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['category_name'].widget.attrs.update({'class':'form-control'}) self.fields['sub_category'].widget.attrs.update({'class':'form-control'}) self.fields['category_info'].widget.attrs.update({'class':'form-control'}) .... This would make for some long lines of code if I have to do this for every form which does not make sense of follow DRY. -
Django ORM Query to find average between timestamps
I am struggling to figure out how to structure a query. I have three models that I inherited, tickets, comments, and actions: class Ticket(models.Model): date = models.DateTimeField(default=datetime.datetime.now, blank=True) subject = models.CharField(max_length=256) description = models.TextField() And class Comments(models.Model): date = models.DateTimeField(default=datetime.datetime.now, blank=True) comment = models.TextField() action = models.ForeignKey(Label, on_delete=models.CASCADE, limit_choices_to={'group__name': 'action'}, related_name='action_label') ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) And class Label(models.Model): name = models.CharField(max_length=50) group = models.ForeignKey(LabelGroup, on_delete=models.CASCADE) My goal is to get an average timespan between Ticket.date (opened) and the latest Comment.date of type Label.name = containment. Lastly, I want to pass in a date range (start_date, end_date) to limit to only tickets within that time period. Ultimately, I want to return: { avg_time_to_contain: 37, avg_time_to_recover: 157 } from a DRF view. The query set I have so far is: queryset = Comments.objects.filter(ticket__date__gte=start_date, ticket__date__lte=end_date).filter(action__name__icontains="containment").distinct(ticket).aggregate(avg_containment=Avg(F(date)- F(ticket__date))) I am getting an error, saying incident is not defined. I believe that is due to my distinct function but I am having a hard time getting my brain to translate into what I am after. Pseudo code for the query (in my thinking), Grab comments that have tickets (FK) with dates between start / end date Filter by the action (FK) name having the work containment … -
How should i set DJANGO_SETTINGS_MODULE, django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND
i'm just start to learn Django and during create a priject i get a problem: "django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND..." I met description fo this problem on Staciverflow but i don't understand in which file i should set DJANGO_SETTINGS_MODULE??? Please, give me detail description I tried set this environment variable in my virtualenv which i use for my project in "activate" file, but it did'nt help me. Maybe my question is stupid but i really don't understand, sorry -
Chrome ignores <a> tag's target argument when link is programmatically "clicked"
I have a project that is implemented with Django, Dojo and JS. I've been banging my head against this issue all week and cannot find any hints online as to what the problem might be. Hopefully someone here has either run into this issue as well and can shed some light on the problem. I have an unordered list <ul> similar to the following: `<ul> <li><a target="displayArea" id="pre-select" href="foo.html>Foo</a></li> <li><a target="displayArea" href="bar.html">Bar</a></li> <li><a target="displayArea" href="baz.html">Baz</a></li> </ul>` ``` elsewhere in the code is the target iframe: ``` `<iframe style="border: none;" name="displayArea" id="displayArea" width="100%" height="95%" title="Report Area"></iframe>` ``` When I mouse over and click "Foo" it works as expected, "Foo" is displayed in the iframe shown above. If, however, I execute the following script which is immediately after the \</ul\> in the code: ``` `<script> window.document.getElementById('pre-select').click(); </script>`` ``` "Foo" is not displayed in the iframe, instead it briefly appears in the host window frame then disappears. I'm not sure why there is a difference clicking directly on the link as it appears in the \<ul\> or executing the \<script\> that does the "click" programmatically. Any insight would be greatly appreciated... As stated in the problem description I expected the link to appear … -
Local server won't go through my URL pattern on my local server
I'm new to Django and I'm facing a problem that I can't solve despit my research... I'v already made small django projects without this error but since I reformat my computer (I can't see the link but that's context!) i'm having this problem. So when I'm running a django project this is what my browser shows me despite others urls in my project Django doesn't go trhough my urls I'v tried with an almost empty project but a least one more url and still have the same page. urls.py in the main file (src/mynotes/urls.py): from django.contrib import admin from django.urls import path, include urlpatterns = [ path('index/', include('dbnotes.urls')), path('admin/', admin.site.urls), ] settings.py in the main project (src/mynotes/settings.py): INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dbnotes' ] urls.py in the app (src/dbnotes/urls.py): from django.urls import path from . import views urlpatterns = [ path("", views.homepage, name="homepage"), ] views.py in the app (src/dbnotes/views.py): from django.http import HttpResponse def homepage(request): return HttpResponse("Hello, world. You're at the polls index.") Even stranger, when i change "path('admin/', admin.site.urls)" I still get the admin page with the same route. Even if i change 'admin/' or admin.site.urls. It looks like my local server display an over … -
Django doesn't connect to postgresql database using docker-compose
Yes i know this question has been asked, and the usual error is making the DB_HOST = docker service name, in my case db. Here's my docker-compose.yml: version: "3" services: db: image: postgres:latest restart: always ports: - "54320:5432" expose: - "54320" volumes: - ./database-data:/var/lib/postgresql/data/ # persist data even if container shuts down environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres # POSTGRES_HOST_AUTH_METHOD: trust django: build: ./api restart: always command: ["python", "manage.py", "runserver", "0.0.0.0:8000"] volumes: - ./api:/app/api ports: - "8000:8000" depends_on: - db raddl_admin: build: ./frontend/raddl_admin stdin_open: true # docker run -i tty: true # docker run -t command: ["npm", "start"] ports: - "3000:3000" volumes: - ./frontend/raddl_admin:/app/frontend/raddl_admin - /app/frontend/raddl_admin/node_modules volumes: database-data: # named volumes can be managed easier using docker-compose Logging the django service gives: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "db" (172.18.0.2) and accepting TCP/IP connections on port 54320? So it's clearly trying to connect to db on that port and my environment vars are set for the django instance. I can even ping my db service from my django service: docker exec -it 1f764333ace2 bash | ping db PING db (23.221.222.250): 56 data bytes 64 bytes from 23.221.222.250: icmp_seq=0 ttl=50 time=42.055 ms … -
Which technique for database design is better for performance?
I need to create a Django PostgreSQL Database with a field in multiple tables to use it like a filter for the users, but I don't know what technique to use for performance. I can create a table with the field and make a foreign key for every table. class Tablefilter(models.Model): filter_field = models.Field() class Tablefilted(models.Model): table_filter = models.ForeignKey(Tablefilter) Or in my models just create a extend for that field in every model. class Tablefilter(models.Model): filter_field = models.Field() class Tablefilted(Tablefilter): field = models.Field() -
Django Value Error "seek of closed file" using PIL for image resize when updating a record
I have the following model: class Players(models.Model): team = models.ForeignKey(Teams, verbose_name=_('Team'), on_delete=models.CASCADE) player_name = models.CharField(_('Player Name'),max_length=200) player_description = models.TextField(_('Player Description')) player_image = models.ImageField(_('Profile Pic'),upload_to='upload/player_image', null=True, blank=True) player_social = models.CharField(_('Social Media Tag'),max_length=200) class Meta: verbose_name = _("Players") verbose_name_plural = _("Players") def __str__(self): return self.team.team_name + ' - ' + self.player_name def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.player_image: image_resize(self.player_image, 250) The last function will call another for image resizing taking the file and an expected max width: # Use PIL to resize images; set target width on each def image_resize(image, tgt_width): img = PIL.Image.open(image) img.load() width, height = img.size target_width = tgt_width h_coefficient = width/tgt_width target_height = height/h_coefficient img = img.resize((int(target_width), int(target_height)), PIL.Image.ANTIALIAS) img.save(image.path, quality=100) img.close() image.close() My view for updating is as follows: @method_decorator(superuser_required, name='dispatch') class PlayerUpdateView(UpdateView): model = Players template_name = 'scoreboard/players/player_update.html' form_class = PlayersForm context_object_name: str = 'player' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) team_id = Players.objects.get(pk=self.kwargs['pk']).team.id context["team"] = Teams.objects.get(pk=team_id) return context def form_valid(self, form): form.save() return super().form_valid(form) def get_success_url(self): team_id = Players.objects.get(pk=self.kwargs['pk']).team.id return reverse_lazy('team_detail', kwargs={'pk': team_id}) It doesn't matter if I provide a new image file or not, I get the same "seek of closed file" error: File "D:\00_www\hts-score\overlay\scoreboard\models.py", line 62, in save image_resize(self.player_image, 250) File "D:\00_www\hts-score\overlay\scoreboard\models.py", …