Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get the profile of a user we click on?
I made this blog and I want to when click on a user's profile from any post the website goes to that specific use's profile I mean the one who wrote the post but right now I can only get the profile picture of the current logged in user what should I do? if I need to post more code please let me know Thanks in advance my profile page {% extends "base.html" %} {% load static %} {% block content %} <div class="frame"> <div class="center"> <div class="profile"> <div class="image"> <div class="circle-1"></div> <div class="circle-2"></div> <img src="{{ post.author.profile.image.url }}" width="70" height="70"> </div> <div class="name">{{ post.author }}</div> <div class="job">Visual Artist</div> <div class="actions"> <button class="btn">Follow</button> <button class="btn">Message</button> </div> </div> <div class="stats"> <div class="box"> <span class="value">523</span> <span class="parameter">Posts</span> </div> <div class="box"> <span class="value">1387</span> <span class="parameter">Likes</span> </div> <div class="box"> <span class="value">146</span> <span class="parameter">Follower</span> </div> </div> </div> </div> {% endblock %} -
Django set up api
I want to use django as backend to create an api that can pass to Frontend, so i just created the api but it cant work, i just want testing in Insomnia but it always cant find the urls, but i have write the path. I need to use the JSONView so i can test the api in Insomnia, someone help to see where i wrong in the path This is my whole code in app views.py import ret from django.shortcuts import render from django.http import HttpResponse from . import models from django.http import JsonResponse from json import JSONDecodeError # Create your views here. class JSONView: def dispatch(self, request, *args, **kwargs): try: input_data = self.parse_input_data(request) ret = {'success': False} return super().dispatch(request, input_data=input_data, ret=ret, *args, **kwargs) except JSONDecodeError: return JsonResponse({'success': False, 'error': 'Invalid JSON data'}) def parse_input_data(self, request): pass class ProductView(JSONView): def post_product_list(self, request, input_data, ret): product = models.Product.objects.values() ret['success'] = True ret['product'] = product @classmethod def as_view(cls): pass This is my whole code in app urls from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('api/Product/product_list/', views.ProductView.as_view(), name='product_list'), ] This is my whole code in project urls """ URL configuration for jqe_shop … -
django-auditlog: traversing relationships to get LogEntries of related objects
For tracking changes, I've created a mixin to add auditlog to model components to make tracking change uniform. It's paying dividends when it's time to generate reports about what's changed. class ChangeMixin: history = AuditlogHistoryField() def get_all_changes(self, range_start=DAY_START, range_end=DAY_END): """ returns all the changes on this instance within a defined time period. The default period is today. :type range_end: datetime :type range_start: datetime """ result = [] if range_start > range_end: return result if self.history is None: return result result = LogEntry.objects.get_for_object(self).filter(timestamp__range=(range_start, range_end)) return result However, there's a fly in the ointment that this solution doesn't address: how to get the corresponding bits from related objects. That is, if there is a one to many or a many to many relationship, how do pursue the relationship to get the target data? For example, if there's a one to many relationship, say Book to Genre, the LogEntry stores the id of the Genre in the change record and the hope is get the text version of the record whose id is in the LogEntry. That is, the genre for a book, say the Hobbit, might get changed from fiction to fantasy. The LogEntry record for the Hobbit might show this as … -
How do I pass dynamic values to Django urls to avoid NoReverseMatch at error
I am trying to build a hotel reservation app with Django, but I am having trouble passing the data through the app. I continue to get this error NoReverseMatch at /search_results/ Reverse for 'more_info_page' with keyword arguments '{'room_type': 'double', 'check_in_date': '2023-12-07', 'checkout_date': '2023-12-09', 'guests': '1'}' not found. 1 pattern(s) tried: ['more_info_page/(?P<room_type>[^/]+)/(?P<check_in_date>[^/]+)/(?P<check_out_date>[^/]+)/(?P[^/]+)/\Z'] I cannot understand how I should pass these to the URL. Here is the HTML line causing the problems <a href="{% url 'more_info_page' room_type=room_type check_in_date=checkin_date checkout_date=checkout_date guests=guests %}" class="btn btn-primary">More Info</a> Here is my search_results view def search_results(request): if request.method == 'POST': checkin_date = request.POST.get('checkinDate') checkout_date = request.POST.get('checkoutDate') guests = request.POST.get('guests') check_in_date = datetime.strptime(checkin_date, '%Y-%m-%d').date() check_out_date = datetime.strptime(checkout_date, '%Y-%m-%d').date() available_rooms = Room.objects.filter(available=True) booked_rooms = Reservation.objects.filter( check_in_date__lte=check_out_date, check_out_date__gt=check_in_date ).values_list('room_id', flat=True) available_rooms = available_rooms.exclude(id__in=booked_rooms) available_room_types = available_rooms.values_list('type', flat=True).distinct() context = { 'checkin_date': checkin_date, 'checkout_date': checkout_date, 'guests': guests, 'available_room_types': available_room_types, } return render(request, 'results.html', context) else: return HttpResponse("Method not allowed") Here is my URL pattern path('more_info_page/<str:room_type>/<str:check_in_date>/<str:check_out_date>/<str:guests>/', views.more_info_page, name='more_info_page'), I have tried various permutations of passing the context, but I continue to get this reverse error. -
Potential Recommendations for a Computer Science Bachelor's Degree final project
I have a friend who will be finishing his Computer Science bachelor's degree next semestre, and he's trying to think what he could do for his final project. He plans to use Python as his main language, with potential frameworks like Kivy and/or Django. He's also considering using real data from his university if given permission for his project. So far he hasn't gotten any luck comming up with project ideas that can apply something computer science related such as AI or simulation. He also needs to make sure that it isn't exclusively an information system project (like if the project is just a simple dashboard or a normal website that won't do much). If anyone can offer any recommendations for what could be a good computer science final project for my friend i'd be very grateful. -
OperationalError: could not translate host name "db" to address: Name or service not known
I am using django on a project and we are switching from sqlite3 to postgres so we need to add postgres to docker. For some reason the webservice wont connect to postgres. Here is my docker-compose and settings. services: db: image: postgres:latest restart: always container_name: db environment: - POSTGRES_USER=pipeline_user - POSTGRES_PASSWORD=password - POSTGRES_DB=pipeline_service ports: - "5432:5432" networks: - django webservice: build: context: ./webservice dockerfile: WebService.Dockerfile command: python ./src/manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" depends_on: - db networks: - django links: - db:db djangoq: build: context: ./webservice dockerfile: WebService.Dockerfile command: python ./src/manage.py qcluster ports: - "8001:8000" depends_on: - db networks: - django links: - db:db ui: build: context: ./ui dockerfile: UI.Dockerfile ports: - "4200:80" depends_on: - webservice networks: django: driver: bridge DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': 'pipeline_service.sqlite3', # } 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'pipeline_service', 'USER': 'pipeline_user', 'PASSWORD': 'password', 'HOST':'db', 'PORT':'5432' } } Can anyone see what I'm missing? I have found several other people with this issue and most of the solutions were adding networks to the docker-compose.yml file or setting the container_name for postgres, but those haven't worked for me. -
static files for django admin can't be found while running asgi server
Here is my settings.py # ...other settings STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = 'static/' # ...other settings Then I run python manage.py collectstatic uvicorn Django_Channels.asgi:application --port 8000 --workers 4 --log-level debug --reload this collects static (after that I do have static folder at the root folder), starts the asgi server, but when I go to the admin page it looks like without any CSS or JS files. Just a bunch of unorganised text. Here are the logs from terminal: Here what logs look likeINFO: 127.0.0.1:51770 - "GET /static/admin/css/dashboard.css HTTP/1.1" 404 Not Found Not Found: /static/admin/css/responsive.css INFO: 127.0.0.1:51770 - "GET /static/admin/css/responsive.css HTTP/1.1" 404 Not Found Not Found: /static/admin/js/theme.js INFO: 127.0.0.1:51769 - "GET /static/admin/js/theme.js HTTP/1.1" 404 Not Found Not Found: /static/admin/js/nav_sidebar.js INFO: 127.0.0.1:51770 - "GET /static/admin/js/nav_sidebar.js HTTP/1.1" 404 Not Found I am always having a bad time with staticfiles, could please somebody tell me what am I doing wrong? -
Why am I getting a CSRF Token Verification Error when submitting a post request using Django?
I have a simple form to send an email to my personal email. I'm able to send the email fine in the development environment, but in the production environment (I use Heroku and the Mailgun addon for hosting and Cloudflare for my domain) I get a 403 Forbidden Error. Heroku provides my SSL certificate for my site. I checked my middleware is in the correct order, and I have my production environment settings as follows: DEBUG = False SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True ALLOWED_HOSTS = [ 'anonymousdomain.com', 'www.anonymousdomain.com', 'pointer1.herokudns.com', 'pointer2.herokudns.com'] DATABASES = { 'default': dj_database_url.config() } EMAIL_HOST = os.environ.get('MAILGUN_SMTP_SERVER', '') EMAIL_PORT = os.environ.get('MAILGUN_SMTP_PORT', '') EMAIL_HOST_USER = os.environ.get('MAILGUN_SMTP_LOGIN', '') EMAIL_HOST_PASSWORD = os.environ.get('MAILGUN_SMTP_PASSWORD', '') I checked the headers when making the request and the origin is the same as the referrer except the referrer has a trailing slash at the end of the domain but I don't think that should be an issue (e.g. the origin is https://www.anonymousdomain.com and referrer is https://www.anonymousdomain.com/). My allowed hosts is allowing all the domains and domain pointers that I use in my DNS (the one's given by Heroku when you add a custom domain) as well. The only thing I can … -
Change Django rest framework Response Class
This is my first question here I want to change the default Response classe for Django rest framework, I've found this article https://dextrop.medium.com/creating-a-custom-response-class-for-django-rest-framework-4c1a9a65561b But it doesn't seem that DEFAULT_RESPONSE-CLASS is supported by DRF settings Any idea ? Thank you very much -
django-fsm FSMKeyField transition identifier
I'm currently facing an issue while trying to define a transition identifier using the 'type' field of a ForeignKey model in Django. After carefully reading the documentation, I noticed that the examples provided primarily utilize the primary key for transition identifiers. Here are some examples: Test examples I'm wondering if anyone has experience or insights into how to specify a transition identifier using the 'type' field of a ForeignKey. Any guidance or examples demonstrating the correct approach in such scenarios would be greatly appreciated. Thank you! class Stage(models.Model): class Type(models.TextChoices): SUBSCRIBED = ( "SUBSCRIBED", _("Subscribed"), ) SELECTED = ( "SELECTED", _("Selected"), ) APPROVED = ( "APPROVED", _("Approved"), ) name = models.CharField(max_length=255) type = models.CharField( max_length=255, choices=Type.choices, default=Type.CUSTOM, ) class Recruitment(models.Model): class Status(models.TextChoices): ACTIVE = ("ACTIVE", _("Active")) INACTIVE = ("INACTIVE", _("Inactive")) stage = FSMKeyField(Stage, on_delete=models.RESTRICT, protected=True) @transition( field=stage, source=[Stage.Type.SUBSCRIBED], #This not works target=Stage.Type.SELECTED, ) def select(self, description=None, by=None): return "Candidate was selected!" I want to discover a way to implement a feature. -
Is it possible to filter Django objects by a list of dictionaries?
Let's say I have a queryset of django objects i.e. Blog with fields id, hits, title and also a list of dictionaries which represent those objects: blog_list = [{'id': 1, 'hits': 30, 'title': 'cat'}, {'id': 2, 'hits': 50, 'title': 'dog'}, {'id': 3, 'hits': 30, 'title': 'cow'}] One of the django object has a value different from one specified in the list of dictionaries. For example, I have a blog instance with id = 1, hits = 30, but title = 'new cat' Right now I do: for blog in queryset: for entry in blog_list: if blog.id == entry['id'] and blog.title != entry['title']: print(f'It is the blog entry with id {blog.id}') But it looks suboptimal and too complicated. Is there a smart way to find such object? -
Scalingo : serving static files for Django ASGI
I've been trying to deploy a Django ASGI app on Scalingo for a few days, and I can't manage to serve the static files. When I load the app I get a 404 on the css file. My Procfile contains only this line : web: gunicorn gingembre.asgi --worker-class=uvicorn.workers.UvicornWorker --log-file - And if I run this command locally, it works, static files included. Following Scalingo documentation, my settings.py file contains the following lines : BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_ROOT = 'staticfiles' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) I've been tweeking these settings for a while now, and I don't know what to try. I read a lot about whitenoise, but it don't seems compatible with ASGI (this PR is not merged yet). -
Appending to a JSONField using update_or_create in Django
I'm trying to efficiently append a value to a JSONField (hobbies) in a Django model using the update_or_create method. I know it is easy to do this by initially calling the update_or_create method, then I get the hobbies field, append the information and the save again. However, I want to avoid hitting the database twice. I tried using the F() expression but I'm getting django.db.utils.OperationalError: (3156, 'Invalid JSON value for CAST to DOUBLE from column history at row 1') Here's the relevant code snippet: # models.py class UserProfile(models.Model): ... hobbies = models.JSONField(default=list) user_profile, created = UserProfile.objects.update_or_create( user=user, defaults={ "hobbies": F("hobbies") + ["Music"] } ) I would really appreciate any help. Thanks -
How to multiple upload images in Django (and dispaly them as carousels)?
I would like add multiple upload images for single product page carousels (so, I need four [] (or {}?..) of images). I need multiple upload because number of photos in different product cards may be different: from 2 to 6. Now I can select multiple files to upload in the admin panel but can't save it. I have an error: TypeError at /admin/product/product/8/change/ Field 'id' expected a number but got <TemporaryUploadedFile: CON_1_mob.jpg (image/jpeg)>. Request Method: POST Request URL: http://127.0.0.1:8000/admin/product/product/8/change/ Django Version: 5.0 Exception Type: TypeError Exception Location: /home/a/.local/lib/python3.10/site-packages/django/db/models/fields/__init__.py, line 2114, in get_prep_value Raised during: django.contrib.admin.options.change_view My code: models.py: from django.db import models from django.conf import settings from multiupload.fields import MultiFileField class Product(models.Model): carousel_items = models.ManyToManyField('ProductImage', related_name='carousel_items', blank=True) carousel_items_mob = models.ManyToManyField('ProductImage', related_name='carousel_items_mob', blank=True) interior_items = models.ManyToManyField('ProductImage', related_name='interior_items', blank=True) interior_items_mob = models.ManyToManyField('ProductImage', related_name='interior_items_mob', blank=True) # many another fields def __str__(self): return self.product_full_name class ProductImage(models.Model): id = models.AutoField(primary_key=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to='product_items/%Y/%m/%d') forms.py: from django import forms from .models import Product, ProductImage from multiupload.fields import MultiFileField class CustomProductForm(forms.ModelForm): carousel_items = MultiFileField(min_num=1, max_num=10, required=False) carousel_items_mob = MultiFileField(min_num=1, max_num=10, required=False) interior_items = MultiFileField(min_num=1, max_num=10, required=False) interior_items_mob = MultiFileField(min_num=1, max_num=10, required=False) class Meta: model = Product fields = '__all__' def save(self, commit=True): … -
How automatize adding a product in stripe
i'm trying to add stripe at my django project and i need to put a custom proce every time i want to buy something. Im doing a house rental type of site so i could do 2 things: 1- Automatize the proccess, creating a script that would create a product with the exact proze of the shopping cart 2-Instead of creating a product with the price of the shopping cart, create a product everytime y add a new house to the database and then buying it all in stripe Personally i would prefer the first one but i dont know if its possible. Someone could help with this? checkout_session = stripe.checkout.Session.create( payment_method_types = ['card'], line_items = [{ 'price': total_post_gestion*100, 'quantity': 1,}] #This is what i have at the moment but stripe tells me i need to have a price tagged to a product and doesen't let me put an integer -
Django dumpdata to dump all tables without data
I have been using dumpdata in Django for a while. The fact is that dumpdata dumps all of the data including table details. Now, I have a requirement to dump all the tables without even including the data. So, that I can use this instead of the migrate Django command. The reason for not using the migrate Django command because it's taking so long to migrate DB. I have a feeling if I can successfully dump all tables without data, this would be a more optimized but not recommended way to loaddata to my DB. -
How to install packages in docker container that has already been started
I am building a django app with docker. After i`ve already built my container, I've added an ImageField to one of my models. When I ran docker-compose run web(my service name) python3 manage.py makemigrations, it gave me an error, that I have to install Pillow: web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.12/threading.py", line 1052, in _bootstrap_inner web_1 | self.run() web_1 | File "/usr/local/lib/python3.12/threading.py", line 989, in run web_1 | self._target(*self._args, **self._kwargs) web_1 | File "/usr/local/lib/python3.12/site-packages/django/utils/autoreload.py", line 64, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.12/site-packages/django/core/management/commands/runserver.py", line 133, in inner_run web_1 | self.check(display_num_errors=True) web_1 | File "/usr/local/lib/python3.12/site-packages/django/core/management/base.py", line 556, in check web_1 | raise SystemCheckError(msg) web_1 | django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: web_1 | web_1 | ERRORS: web_1 | system.Task.image: (fields.E210) Cannot use ImageField because Pillow is not installed. web_1 | HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". After that I tried to install with docker-compose run web python3 -m pip install Pillow, it seemed, like it installed it: Starting db ... done Creating app_web_run ... … -
django channels error: websocket connection failed
I have django project what need websocket connection to send message via django channels. i coded project and it's good in my localhost but when i deploy project in cPanel it returns WebSocket connection to 'wss://rahapeyk.com/' failed: in a browser console. settings.py ASGI_APPLICATION = 'rahapeyk.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', } } asgi.py import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rahapeyk.settings') # application = get_asgi_application() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from social import routing application = ProtocolTypeRouter( { 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ) } ) routings.py from django.urls import path from social.consumers import ChatConsumer websocket_urlpatterns = [ path('', ChatConsumer.as_asgi()), ] server.js const chat = new WebSocket( 'ws://' + window.location.host + '/' ); chat.onopen = function (e) { console.log('successfully'); } chat.onclose = function (e) { console.log('unexpectedly happened'); } how to keep the websocket connection when i deploy project without any error? -
Web world wind implementation in python django [closed]
I am trying to implement web world wind through django framework. The plan is viewing some flight data on virtual globe. For that i tried to use nasa web world wind. I managed to view the index page through manage.py runserver. But the virtual globe is not coming. Any help Page is rendered from server, js controls are loading but the globe is not loading. -
Django 4, ValueError: 'MyModel' instance needs to have a primary key value before this relationship can be used
The issue is a result from the update to django 4, in prior versions the issue was not present. When performing a reverse lookup on a foreign key relation, if the object being used for the reverse look up has not been save to the db (The object has no pk) an exception is raised, ValueError: 'MyModel' instance needs to have a primary key value before this relationship can be used. For example: class Author(models.Model): name = models.CharField(max_length=100) biography = models.TextField() class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE) publication_date = models.DateField() new_author = Author(name='John Doe', biography='A new author') reverse_look_up = new_author.book_set.all() # this raises the issue. In django 3.2 and lower, performing this action wouldn't raise an error but rather return an empty queryset of book. You can solve this issue manually, by checking if the object has an id and then only performing the look up if it does, or by saving the object before hand, however I perform this kind of look up in numerous places and it would be difficult to do so. Would there be anyway to perform a generic fix for this, whether it be a change I can make to the model … -
Django Channels chat with one user
I completed my Django Channels. I have confusion about. How to make conversation between two user (me and user2) only. Is it possible to make conversation between only two user (me and user2) without making group If I make group than anyone can join the group and the user2 need to join the group. How can I send messages direct to the user2 -
Do repeated imports into views affect performance in a Django application?
In a situation like this: # views.py def myView(request): import something import other something.doStuff() other.doOtherStuff() return render(request, 'page.html', context) def myOtherView(request): import something import other something.doThings() other.doOtherThings() return render(request, 'page2.html', context) Is importing stuff at view-level a bad practice? Does it affect performance? # views.py import something import other def myView(request): something.doStuff() other.doOtherStuff() return render(request, 'page.html', context) def myOtherView(request): something.doThings() other.doOtherThings() return render(request, 'page2.html', context) Is this second version better/faster? -
Trying to run django project & i get this error mysql.connector.errors.ProgrammingError: 1045(28000)
I am trying to run a project i downloaded from the internet 'geymmanage' i installed all the required libraries. I have also installed mysql and sqlite3 as well (in the project settings i found sqlite3 as backend) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } and in the views.py conn = mcdb.connect(host="localhost", user="root", passwd="", database='myproject1') I tried running the django project but it gives me this error `raise get_mysql_exception( mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) Detailed Error Watching for file changes with StatReloader Performing system checks... Successfully connected to database Exception in thread django-main-thread: Traceback (most recent call last): File "/home/gedion/Downloads/gymmanagement (1)/virt/lib/python3.11/site-packages/mysql/connector/connection_cext.py", line 308, in _open_connection self._cmysql.connect(**cnx_kwargs) _mysql_connector.MySQLInterfaceError: Access denied for user 'root'@'localhost' (using password: NO) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.11/threading.py", line 1038, in _bootstrap_inner self.run() File "/usr/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/home/gedion/Downloads/gymmanagement (1)/virt/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/gedion/Downloads/gymmanagement (1)/virt/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "/home/gedion/Downloads/gymmanagement (1)/virt/lib/python3.11/site-packages/django/core/management/base.py", line 485, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "/home/gedion/Downloads/gymmanagement (1)/virt/lib/python3.11/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/gedion/Downloads/gymmanagement (1)/virt/lib/python3.11/site-packages/django/core/checks/urls.py", … -
Django signals for different apps
I need to have separate signals for each app of my project. But after saving a model in one of the apps signals trigger from all apps, so I have duplicated messages from my signals. What is the right way to set up signals for different apps of Django project? signals.py of my app1: # -*- coding: utf-8 -*- import logging from django.db.models.signals import post_save from django.dispatch import receiver from .models import * @receiver(post_save) def log_app1_updated_added_event(sender, **kwargs): '''Writes information about newly added or updated objects of app1 into log file''' logger = logging.getLogger(__name__) app1_object = kwargs['instance'] if kwargs['created']: logger.info(f'added {app1_object }') else: logger.info(f'updated {app1_object }') signals.py of my app2: # -*- coding: utf-8 -*- import logging from django.db.models.signals import post_save from django.dispatch import receiver from .models import * @receiver(post_save) def log_app2_updated_added_event(sender, **kwargs): '''Writes information about newly added or updated objects of app2 into log file''' logger = logging.getLogger(__name__) app2_object = kwargs['instance'] if kwargs['created']: logger.info(f'added {app2_object }') else: logger.info(f'updated {app2_object }') apps.py of my app1: from django.apps import AppConfig class App1Config(AppConfig): name = 'App1' def ready(self): from app1 import signals apps.py of my app2: from django.apps import AppConfig class App1Config(AppConfig): name = 'App2' def ready(self): from app2 import signals and here … -
Cant get rid of FileNotFoundError in Django ImageField
I have a django model Product which has an image field class Product(BaseProduct): img_height = models.PositiveIntegerField(editable=False, null=True, blank=True) img_width = models.PositiveIntegerField(editable=False, null=True, blank=True) file = models.ImageField('Image', upload_to=product_img_path, height_field='img_height', width_field='img_width', null=True, blank=True, max_length=255) Now because I loaded the products from an Excel file with records over 15,000 there are few that the image path in the file field does not actually exist in my directory. This causes my code to raise a FileNotFoundError every time i try to for product in Product.objects.all() before I am even able to catch the error with a try-except block. I'd like to have an iteration where I can check if the file exists and set the file field to null for records with non-existing files. But this is impossible because the error is raised once I try to call an instance of the artwork or I create the iteration. So the code below: products = Product.objects.all() for product in products: try: if product.file: pass except FileNotFoundError: product.file = None product.save() Raised error: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\user\\project\\media\\products\\blahblah.jpeg' and the stack trace shows error was raised from the iteration line for product in products: I have tried following this thread without any …