Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need help in displaying items from ManyToMany relation in Django template
I am struggling with displaying items from manytomany field in my html file. models.py class Ingredients(models.Model): name = models.CharField('Nazwa', max_length = 100) ingredient_category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE) class ShoppingList(models.Model): name = models.CharField('Nazwa', max_length = 100) status = models.BooleanField(default = False) last_updated = models.DateTimeField('Ostatnia aktualizacja', auto_now=True) publish = models.DateTimeField('Stworzono', default=timezone.now) ingredient_list = models.ManyToManyField(Ingredients, related_name='shopping_list') slug = models.SlugField(unique=True, blank=True, max_length=254) views.py class HomePageView(TemplateView): template_name = "homepage.html" queryset= ShoppingList.objects.all() def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) shopping_list = ShoppingList.objects.all() context['shopping_list'] = shopping_list return context homepage.html {% for list in shopping_list.ingredient_list.all %} <div class="tab-pane fade {% if forloop.first %}show active{% else %}{% endif %}" id="list-{{list.id}}" role="tabpanel" aria-labelledby="list-{{list.id}}-tab">{{list.name}}</div> {% endfor %} -
Django how to validate a form in CreateView when using foreignkeys and using multiple databases
Hello This is my first question so please forgive the formatting: Current lab setup 1 project: library 1 app catalog 2 databases library_admin_db (admin-mysql) catalog_db (mysql1 I'm trying to add a database object on "catalog_db" database using a "CreateView" Class based view I already set up the Databases connection: DATABASES = { # Must use Default 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'library_admin_db', 'USER': 'root', 'PASSWORD': 'password', 'HOST': '192.168.164.128', 'PORT': '8002' }, 'catalog': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'catalog_db', 'USER': 'root', 'PASSWORD': 'password', 'HOST': '192.168.164.128', 'PORT': '8000', } } I set up the DATABASE_ROUTERS: DATABASE_ROUTERS = [ BASE_DIR / 'routers.db_routers.LibraryRouter'# the "MyApp1Router is the class inside the db_routers file" ] here is my model with the foreign keys: from django.db import models from django.urls import reverse import uuid # Create your models here. class Genre(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=600) isbn = models.CharField('ISBN', max_length=13, unique=True) genre = models.ManyToManyField(Genre) language = models.ForeignKey('language', on_delete=models.SET_NULL, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('book_detail', kwargs={"pk":self.pk}) class Language(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Author(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) date_of_birth = models.DateField(null=True,blank=True) class Meta: ordering = ['last_name','first_name'] … -
Issue with NoReverseMatch at Django website
I am making a web with Django-python, following a step by step tutorial, I put it below. My problem is the following: and this appears to me: NoReverseMatch in /. The reverse of 'login' was not found. 'login' is not a valid view Exception Type: NoReverseMatch. Exception Value: Failed to find the reverse side of 'login'. 'login' is not a valid view function or pattern name. And this is the error code: The reverse side of 'login' has not been found. 'login' is not a valid view function or pattern name. 8 {% url 'public:contact' as contact_url %} 9 <span>{% if request.path == contact_url %}Contacto{% else %}<a href="{{ contact_url }}">Contacto</a>{% endif%}</span> 10 <span> 11 <span style="float:right"> 12 {% if user.is_authenticated%} 13 {% url 'profile' as profile_url%} 14 <span>Hola {% if request.path == profile_url%}{{user.username }}{% else %}<a href="{{ profile_url}}">{{user.username}}</a>{%endif%}</span> 15 <!--<span> Hola <a href={% url 'profile' %}">{{user.username}}</a>!</span> --> 16 <span><a href="{% url 'logout' %}">Salir</a></span> 17 {% else %} 18 <span><a href="{% url 'login' %}">Ingresar</a></span> 19 {% endif %} 20 </span> 21 </nav> error line: 18 What can I do about this? Maybe it's a problem with the views or I will have to define login? If you can help me, thank … -
why is django server not working? (connection refused error)
I am doing a course : cs50 web programming with python and in project 2 Commerce while using python manage.py runserver I am getting this error: This site can’t be reached 127.0.0.1 refused to connect. this is project 2 commerce. https://cs50.harvard.edu/web/2020/projects/2/commerce/ I have not made any changes to the distribution code I am stuck please help me as soon as possible. -
How to have a number related to each one of many to many field objects? (e.g. A score for a homework a student has done)
I'm making an Learning Management System. There's this model called Homework and User model which is basically a model for students. class User(AbstractUser): # some code class Homework(models.Model): # some code ... students_done = models.ManyToManyField(User, blank=True, related_name='homeworks_done') I wanted to keep track of students that have done a specific homework and I did it by adding students_done field. Now I want the teacher to have the option to give each student a score for a done homework. How can I save the score in the database? I just can't figure out what field to use and how to use it. -
How to get a specific record in a lookup table in Django
I'm building a Django app that manages client data. I store phone numbers, email addresses, addresses, etc., in lookup tables. I would like to create a queryset that returns the primary numbers for all clients. Here is an abbreviated version of the client table: id last first etc 100426 Smith John etc 114988 Johnson Thomas etc An example of the phones table: id client_id type_id is_primary number 1 100426 1 t 427-567-8382 2 100426 2 f 427-567-7789 3 114988 1 t 914-223-4597 And finally, the phone_type table: id type 1 mobile 2 home 3 office 4 condo An extract of the client model: class Client(models.Model): id = models.IntegerField(primary_key=True) last = models.CharField(max_length=32) first = models.CharField(max_length=32) phone = models.ForeignKey( Phone, on_delete=models.PROTECT, blank=False, null=False ) The phone model: class Phone(models.Model): id = models.IntegerField(primary_key=True) client_id = models.IntegerField type_id = models.ForeignKey( PhoneType, on_delete=models.PROTECT, blank=False, null=False) is_primary = models.BooleanField country_code = models.CharField(max_length=5) phone_number = models.CharField(max_length=16) And the phone_type: class PhoneType(models.Model): id = models.SmallIntegerField(primary_key=True) type = models.CharField(max_length=16, blank=False, null=False) My ClientListView: class ClientListView(ListView): model = Client template_name = 'client/client_list.html' context_object_name = 'clients' def get_queryset(self): return Client.objects.order_by('-id').filter(status_id=3).select_related(Phone) The get_queryset function is a placeholder for now. How can I replace the get_queryset function so that I'm able to list … -
Why does celery worker keep trying to connect to amqp even though the broker is sqs?
I tried to configure broker via settings and directly from the celery file . Settings that apply to celery below. AWS_SQS_SECRET = os.environ.get("AWS_SQS_SECRET") broker_url = 'sqs://%s:%s@' % (AWS_SQS_ACCESS, AWS_SQS_SECRET) task_default_queue = os.environ.get("DEFAULT_QUEUE") AWS_SQS_REGION = os.environ.get("AWS_REGION") broker_backend = "SQS" broker_transport_options = { "region": AWS_SQS_REGION, # 'queue_name_prefix': '%s-' % 'dev' , # os.environ.get('ENVIRONMENT', 'development'), 'visibility_timeout': 7200, 'polling_interval': 1, } accept_content = ['application/json'] result_serializer = 'json' task_serializer = 'json' Also, as I mentioned, I tried to configure directly from the celery file. import os from celery import Celery from celery.schedules import crontab from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyApp.settings') AWS_SQS_ACCESS = os.environ.get("AWS_SQS_ACCESS") AWS_SQS_SECRET = os.environ.get("AWS_SQS_SECRET") app = Celery('MyApp') #,, broker='sqs://%s:%s@' % (AWS_SQS_ACCESS, AWS_SQS_SECRET), backend='django-db' # app.config_from_object('django.conf:settings') #, namespace='CELERY' CELERY_CONFIG = { "CELERY_TASK_SERIALIZER": "json", "CELERY_ACCEPT_CONTENT": ["json"], "CELERY_RESULT_SERIALIZER": "json", "CELERY_RESULT_BACKEND": None, "CELERY_TIMEZONE": "America/Sao_Paulo", "CELERY_ENABLE_UTC": True, "CELERY_ENABLE_REMOTE_CONTROL": False, } BROKER_URL = 'sqs://%s:%s@' % (AWS_SQS_ACCESS, AWS_SQS_SECRET) CELERY_CONFIG.update( **{ "BROKER_URL": BROKER_URL, "BROKER_TRANSPORT": "sqs", "BROKER_TRANSPORT_OPTIONS": { "region": "sa-east-1", "visibility_timeout": 3600, "polling_interval": 60, }, } ) app.conf.update(**CELERY_CONFIG) app.autodiscover_tasks() During deployment on elastik beanstalk , in the service I am running the command: $PYTHONPATH/celery -A celery worker -Q default-dev -n default-worker \ --logfile=/var/log/celery/celery-stdout-error.log --loglevel=DEBUG --concurrency=1 Tried to run before: $PYTHONPATH/celery -A MyApp worker -Q default-dev -n default-worker \ --logfile=/var/log/celery/celery-stdout-error.log --loglevel=DEBUG --concurrency=1 But … -
Django-CKeditor broken on Heroku
My django website is hosted on Heroku (with static files on AWS S3) and the ckeditor recently stopped working on my admin pages. If I check the console, I can see this error : Refused to execute script from 'https://mysite-web.herokuapp.com/admin/' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Any idea how to fix this ? -
CSS malfunctioning in social media platform chat between two users
Social Media Platform: I am trying to get the image to line up above the sent message as you would have it in most standard DMs: example But for some reason, my images stick to the right side of the chat box: without CSS When I add float: right; to my CSS the image and the text layer horizontally in a strange manner: with CSS Ideally, the image should be on the same side as the texts from the person who sent the image and should be just above the message that was attached to the image (as is commonplace). style.css: .sent-message { background-color: #d7a5eb; border-radius: 30px; padding: 10px 25px; width: 25%; float: right; } .received-message { background-color: #cc64c3; color: #000; border-radius: 30px; padding: 10px 25px; width: 25%; float: left; } .message-receiver-container { margin-left: 0; margin-right: auto; } .message-image-received { border-radius: 10px; max-width: 35%; height: auto; float: left; } .message-image-sent { border-radius: 10px; max-width: 35%; height: auto; float: right; } thread.html: {% for message in message_list %} <div class="row"> {% if message.sender_user == request.user %} <div class="col-md-12 my-1"> {% if message.image %} <div> <img src="{{ message.image.url }}" class="message-image-sent" /> </div> {% endif %} <div class="sent-message my-3"> <p>{{ message.body }}</p> </div> … -
Django - Disable Cache key warnings
I am currently designing a Django application and set up a database cache, increased the key size to 500 characters, however I constantly receive this warning: CacheKeyWarning: Cache key will cause errors if used with memcached: key_text (longer than 250) Reading through the documentation here: https://docs.djangoproject.com/en/3.2/topics/cache/ If you are using a production backend that can accept a wider range of keys (a custom backend, or one of the non-memcached built-in backends), and want to use this wider range without warnings, you can silence CacheKeyWarning with this code in the management module of one of your INSTALLED_APPS. I've created management folder in my app (tried various places) and added the code required inside it as management.py but it's not working. Has anyone managed to silence these warnings and can please share where they added it? Thanks -
How to convert image address and save to imagefield in Django
I want to convert the image address to image, and django-storages will automatically upload the image to cloud storage when saving the model. I have tried a few things with no success, any help would be great!(forgive my ugly English) class Register(APIView): permission_classes = [permissions.AllowAny] def post(self, request, *args, **kwargs): username = request.data.get('nickname', None) avatarUrl = request.data.get('avatarUrl', None) if not username or not avatarUrl: return Response(status=status.HTTP_400_BAD_REQUEST) # Convert image address to file, use django-storages to automatically upload images to cloud storage when model on save, so no need to save local image ... ... user, created = UserProfile.objects.get_or_create(username=username, defaults={'avatar': convert_image_from_url}) return Response(status=status.HTTP_200_OK) -
django - check if the user has saved the post in the template
How can i check if the user has saved the post or not? Post model: class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=50, default='slug') text = models.TextField(null=True, blank=True) text_allowed = models.BooleanField(default=True) image = models.ImageField(upload_to='posts/images/', null=True, blank=True) image_allowed = models.BooleanField(default=True) video = models.FileField(upload_to='posts/videos/', null=True, blank=True) video_allowed = models.BooleanField(default=True) server = models.ForeignKey(Server, on_delete=models.CASCADE, related_name='posts') creator = models.ForeignKey(User , on_delete=models.CASCADE, related_name='posts', null=True) created = models.DateTimeField(auto_now=True) type = models.CharField(max_length=5, choices=post_type_choices, default='text') votes_count = models.IntegerField(default=0) tag = models.ForeignKey(ServerTag, on_delete=models.CASCADE , default=1) Save model: class Save(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='saved') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_saves') created = models.DateTimeField(auto_now='True') I've tried: post-page.html: {% if request.user.user_saves %} <a href="{% url 'posts:save-post' post.id %}"><img class="save-btn" src="{% static 'posts/svgs/saved.svg' %}" alt="save post button"></a> //show this svg if the user has saved this post {% else %} <a href="{% url 'posts:save-post' post.id %}"><img class="save-btn" src="{% static 'posts/svgs/save.svg' %}" alt="save post button"></a> {% endif %} -
How to insert data into django db from a sql file
I have generated a dataset from mockaroo called x.sql want to import this into django models where the database is default a.k.a sqlite3 -
Django returns blank QuerySet despite names matching
I have a model Employee, where one of the fields is manager, which is a ForeignKey to another model called Manager. I am checking whether a manager value I'm passing through the previous page matches with an object of Employee that has the same manager, and I want to get only those objects where the manager matches. However, despite me having employees that have different managers each, I try filtering using Employee.objects.get(manager=manager) or Employee.objects.filter(manager=manager), and neither returns anything. filter returns a blank queryset and get says Employee matching query does not exist. despite it clearly matching. Any help would be appreciated, thanks! CODE views.py from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.utils import timezone from .models import Attendance from .models import Employee, Manager from datetime import datetime employee_list = ["John", "Jane", "Jacob", "Mark", "Jingleheimer", "Rob", "Schmidt"] # Create your views here. @login_required def home(request): return render(request, 'index.html') @login_required def attendance(request): manager_list = Manager.objects.all() now = timezone.now().date status = 0 for manager in manager_list: if ' ' in manager.name: manager.select_name = manager.name.replace(' ', '_') else: pass if request.method == 'POST': manager = request.POST.get('manager') print(manager) return redirect('mark_attendance', manager=manager) return render(request, 'attendance.html', { "date": now, "status": … -
Allauth - get SocialAccount.id after successful login/connect/signup
After the user connects their social account (which can be any of Google, Microsoft and even custom providers) and is redirected to /some/redirect/url, I need to get the ID of the account (SocialAccount model). A very simple example would be: user clicks on accounts/google/login/?process=connect&next=/some/redirect/url After successful connection (no matter if already exists or not), user is redirected to /some/redirect/url The page says "Your newly connected SocialAccount.id is 45" I could theoretically get all SocialAccount objects of this user and return the newest one but I want this to work also when the user just doesn't realize they already connected their account. How can I do that? EDIT: I'm also open to using cookies as a messenger for this ID. -
Why am I being told that temp_list is not defined when it is when I check if a word of list are in string [closed]
I’m on Django and I try to get subject of mail and check if a certain word are in the subject. For that I do : (all code here) def decode_str(word): h = make_header(decode_header(word)) s = str(h) return s class HomeAppView(TemplateView): template_name = "app_manager/index.html" # Déclarations des variables utiles. Ne pas toucher encoding = 'utf-8' final_list = [] ras = erreur = 0 lstSubjectRAS = [] lstSubjectError = [] # Listes des mots de RAS lst_RAS = [ "ras", "RAS", "réussi ", "terminée", "terminé" ] # Liste des mot d'erreurs lst_ERREUR = [ "error", "erreur", "échoué" ] # Déclarations attendu = 10 date = (datetime.date.today() - datetime.timedelta(30)).strftime("%d-%b-%Y") msg_from = '"Name"' # Tri result, data = m.search(None, '(FROM {msg_from} SENTSINCE {date})'.format(date=date, msg_from=msg_from)) ids = str(data[0], encoding) # Création d'une liste de message par ids id_list = ids.split() for emailid in id_list: temp_dict = {} result, data = m.fetch(str(emailid), "(RFC822)") email_body = data[0][1] mail = email.message_from_bytes(email_body) temp_dict['Sender'] = mail["From"] temp_dict['Date'] = mail["Date"] s = mail["Subject"] temp_dict['Subject'] = decode_str(s) if any(word in temp_dict['Subject'] for word in lst_RAS): ras = ras + 1 final_list.append(temp_dict) manque = attendu - (ras + erreur) Details : Firstly I declare a list of word which I will then … -
ERROR: Template does not exist / Used: Django + React + heroku
I created a simple note with django & react app. And I am trying to deploy to Heroku. I tried heroku open at terminal, but this error page came out. enter image description here Here is my environment and things i've tried for 2 days. File structure) project-folder api env frontend (my React app) build index.html public src package.json mynote (my Django main app) settings.py manage.py Procfile requirements.txt runtime.txt requirements.txt) asgiref==3.5.2 dj-database-url==0.5.0 Django==4.0.5 django-cors-headers==3.13.0 djangorestframework==3.13.1 gunicorn==20.1.0 psycopg2-binary==2.9.3 pytz==2022.1 sqlparse==0.4.2 tzdata==2022.1 whitenoise==6.2.0 runtime.txt) python-3.10.0 Procfile) web: gunicorn mynotes.wsgi --log-file - settings.py) """ Django settings for mynotes project. """ from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent #BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # for heroku deploy SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', '~') # for heroku deploy DEBUG = bool( os.environ.get('DJANGO_DEBUG', True) ) ALLOWED_HOSTS = [ '[here is my project name!].herokuapp.com', '127.0.0.1' ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'api', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True ROOT_URLCONF = 'mynotes.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'frontend/build') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mynotes.wsgi.application' … -
Django: ERROR (EXTERNAL IP): Invalid HTTP_HOST header ... - Correct host but spam queries?
Sometimes I get a wave of errors like this: [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'app.mysite.com'. You may need to add 'app.mysite.com' to ALLOWED_HOSTS. The thing is, app.mysite.com is the correct host, and it definitely is already in allowed host. However, the requests that are getting blocked are spam, sending: Post requests to '/uncensored' Requests to '/query?dns=DUIBAAA...' (long string of letters) Requests to '/doh/family-filter?dns=....' (long string) All have CONTENT_TYPE = 'application/dns-message' It makes sense that the queries are blocked, but it doesn't make sense that it's an invalid HTTP_HOST header error. Does HTTP_HOST check against something else in addition to allowed_hosts? -
Export selected rows in CSV with django-tables2
I'm using django-tables2 to create a table. I have added a CheckBoxColumn and it works fine in my form when sending data (i.e. upon form submit, it sends a list of all the checkboxes that I've ticked). My question is how can I use that to export ONLY the selected rows in CSV? I want to avoid using JS, as this way I'm afraid I lose the functionality that comes with TableExport. thanks in advance. -
Assign child field to parent when create with help of django-mptt
The question, is how can I create with help of django-mptt, a new sub with parent name (that is already in DB) ? like new product>account but with already FK for subs parent(by his name for example) Models: class Product(models.Model): account = models.OneToOneField( Account, primary_key=True, related_name='product', on_delete=models.CASCADE, ) class Account(models.Model): subs = models.ForeignKey( Subs, related_name='accounts', on_delete=models.CASCADE, ) class Subs(models.Model, MPTTModel): name = models.CharField(max_length=255) parent = TreeForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='subs') Serializers: class ProductCreateSerializer(CreateModelSerializer): subs = serializers.PrimaryKeyRelatedField(queryset=Subs.objects.all()) account = serializers.PrimaryKeyRelatedField(queryset=Account.objects.all()) class Meta: model = Product fields = "__all__" def create(self, validated_data): subs = validated_data.pop("subs") account = Account.objects.create( subs=subs, account=account, name=validated_data['name'] ) validated_data["account"] = account return super().create(validated_data) -
With an existing Django site, can I write a script that returns raw output, kind of like and API but simpler?
I have a very simple django site running on pythonanywhere.com; I'd like now add on a script that does something not directly related to the website. Specifically I'd like to run a script that takes a URL such as www.mysite.com/GetLatLong/V95AE16 In this case the V95AE16 is a postcode The url would execute the script GetLatLong.py using V95AE19 as input and then return raw data in the format 52.46723, -8.23564 This is to be used by a different application (nothing to do with python) which will just use my script like an API, just simpler, no CRUD, just giving a single value and getting some values in return Many thanks / Colm -
Django connect to a particular database based on the user
I have a scenario where each user has a separate database(about 100 customers). What could be best possible way of connecting to the database as per user ? including all the database connection names doesn't make sense because every time I want to add a user I need to modify the settings file again. I am new to Django. Can someone help me with this ? -
Django rules with abstract base class throw error after addition
Trying to add Django-rules to my Django project I am encountering the following issue: I have an abstract base class, which I am using to add a couple of common keys. Now I want to add default permissions to the abstract class, and overwrite them, if needed. Below are my abstract base class and an example of a subclass. class BaseModel(RulesModelBaseMixin): company_id = models.ForeignKey('company.Company', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey( 'user.User', on_delete=models.SET_NULL, null=True, blank=True) class Meta: abstract = True rules_permissions = { "can_create": can_create_in_company | is_superuser, "can_view": can_view_in_company | is_author | is_superuser, "can_edit": can_change_obj | is_author | is_superuser, "can_delete": can_delete_obj | is_author | is_superuser, } class Ticket(RulesModelMixin, BaseModel, metaclass=RulesModelBase): name = models.CharField(max_length=512, null=True, blank=True) description = models.TextField(blank=True, null=True) After adding this abstract base, I now get a seemingly unrelated error message from Django: Traceback (most recent call last): File "REPO_PATH/.venv/lib/python3.10/site-packages/django/utils/module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "REPO_PATH/.venv/lib/python3.10/site-packages/django/utils/module_loading.py", line 15, in cached_import import_module(module_path) File "/opt/homebrew/Cellar/python@3.10/3.10.4/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module … -
An image classification error type while using django-rest and react axios
I'm working on a classification image project with django rest framework and react using axios and 've got an error that kept me from manipulating my images As an api model.py from django.db import models from keras.utils import img_to_array, load_img import numpy as np from keras.applications.vgg16 import preprocess_input class PicUpload(models.Model): imagefile = models.ImageField(upload_to = 'pic_upload') car_Check=models.CharField(max_length=4,blank=True) damage=models.CharField(max_length=4,blank=True) location=models.CharField(max_length=10,blank=True) severity=models.CharField(max_length=10,blank=True) cost=models.CharField(max_length=20,blank=True) uploaded=models.DateTimeField(auto_now_add=True) def __str__(self): return 'Image classified at {}'.format(self.uploaded.strftime('%Y-%m-%d %H:%M:%S')) def save(self,*args,**kwargs): try: print(self.imagefile) print('xxxxxxxxxxxxxxxxxx') img =load_img(self.imagefile, target_size=(224, 224)) x = img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) except Exception as e: print('classification failed',e) super().save(*args,**kwargs) As a setting STATIC_URL = 'static/' STATICFILES_DIRS=[STATIC_DIR,] #PIC OR MEDIA PIC_ROOT=PIC_DIR PIC_URL='/pic_upload/' #PIC_DIR = os.path.join(BASE_DIR, 'pic_upload') #BASE_DIR = Path(__file__).resolve().parent.parent # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' This is what I get for response System check identified no issues (0 silenced). June 10, 2022 - 13:48:59 Django version 4.0.4, using settings 'cardamage.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. karhba.jpeg xxxxxxxxxxxxxxxxxx classification failed path should be path-like or io.BytesIO, not <class 'django.db.models.fields.files.ImageFieldFile'> [10/Jun/2022 13:49:13] "POST /api/PicUpload/ HTTP/1.1" 201 182 Knowing that I got this in my console data: {…}, status: 201, statusText: 'Created', headers: {…}, config: {…}, …} config: … -
django update boolean field in a signal (pre_save)
I've tried .update() and .save(updated_fields=list(kwargs.keys())) but it doesn't save the changes it looks good when stepping through it in debug mode then it reverts back for the test. Am I working on a separate copy or is caching a thing that I should be checking? in tests/test_status_model.py def test_status_set_tag_info_obsolete(self): """ check to see if the creation of a statusInfo object which runs a pre_save signal changes the soon_to_be_obsolete_tag to is_obsolete=True """ self.assertFalse(self.soon_to_be_obsolete_tag.is_obsolete) self.main_status_info = StatusInfoFactory( affected_tag=self.soon_to_be_obsolete_tag, status="o", # obsolete by=self.new_replacement_tag, ) self.assertTrue(self.soon_to_be_obsolete_tag.is_obsolete) # fails in status/models.py @receiver(pre_save, sender=StatusInfo) def status_change_modification(sender, instance, *args, **kwargs): """ Changes tags and concepts to be obsolete or deprecated. if a tag is obsolete or deprecated, all of the tag's concepts are obsolete or deprecated """ assert hasattr(instance.affected_tag, "id") # set up variables kwargs = {} if instance.status == "d": kwargs["is_deprecated"] = True elif instance.status == "o": kwargs["is_obsolete"] = True if instance.affected_tag_or_concept == "t": # Yes this works inner_tag_status_change(instance, **kwargs) def inner_tag_status_change(instance, **kwargs): """ update the is_updated fields for status_info kwargs is either: kwargs = {'is_obsolete': True} # or {'is_deprecated': True} """ affected = Tag.objects.filter(id=instance.affected_tag.id).first() affected.__dict__.update(**kwargs) affected.save(update_fields=list(kwargs.keys())) I think this is the smallest info I can get in here to make the problem make sense. Let …