Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
reasons for serializer not validating data DRF
I am sending the data through postman as follows my model.py is as follows def get_upload_path(instance, filename): model = instance._meta name = model.verbose_name_plural.replace(' ', '_') return f'{name}/images/{filename}' class ImageAlbum(models.Model): def default(self): return self.images.filter(default=True).first() def thumbnails(self): return self.images.filter(width__lt=100, length_lt=100) class Photo(models.Model): name = models.CharField(max_length=255, null=True, blank=True) photo = models.ImageField(upload_to=get_upload_path, null=True, blank=True) default = models.BooleanField(default=False, null=True, blank=True) width = models.FloatField(default=100, null=True, blank=True) length = models.FloatField(default=100, null=True, blank=True) description = models.CharField(max_length=2000, null=True, blank=True) latitude = models.DecimalField(max_digits=11, decimal_places=2, null=True, blank=True) longitude = models.DecimalField(max_digits=11, decimal_places=2, null=True, blank=True) album = models.ForeignKey(ImageAlbum, related_name='album_data', on_delete=models.CASCADE, null=True, blank=True) my view.py is as follows class ImageAlbumListApiView(APIView): permission_classes = [IsAuthenticated] parser_classes = [MultiPartParser, FormParser, ] def get(self, request): image_album = ImageAlbum.objects.all() serializer = ImageAlbumSerializer(image_album, many=True) return Response(serializer.data) def post(self, request): serializer = ImageAlbumSerializer(data=request.data) print(request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) My serializer.py is as follows class PhotoSerializer(serializers.ModelSerializer): class Meta: model = models.Photo fields = '__all__' class ImageAlbumSerializer(serializers.ModelSerializer): album_data = PhotoSerializer(many=True, read_only=True) file = serializers.ListField( child = serializers.ImageField(max_length = 1000000, allow_empty_file = False, use_url = False, write_only = True), write_only=True) class Meta: ###Test### model = models.ImageAlbum fields = ['id', 'album_data', 'file'] read_only_fields = ['id'] def create(self, validated_data): #album_data = validated_data.get('album_data') print(validated_data) uploaded_files = validated_data.get('file') #image_info = validated_data.pop('images') album = models.ImageAlbum.objects.create() … -
Django ORM for fetching latest record for specific ID
How do I write a django ORM to fetch the most recent records from the table for a specific id. Example: I have table(tr_data) data like: id trs(foreign key) status last_updated 1 301 3 2022-11-28 06:14:28 2 301 4 2022-11-28 06:15:28 3 302 3 2022-11-28 06:14:28 4 302 4 2022-11-28 06:15:28 5 302 2 2022-11-28 06:16:28 I want to have a queryset values that gives me trs id with its latest status.I have tried with aggragate and MAX but not getting the desired result. Expecting ouput as : [{"trs":301, "status":4},"trs":302,"status":2}] -
How to get an records with each month in a date range of two fields?
I have a study year model which has a start and end date. class StudyYear(models.Model): date_begin = models.DateField(...) date_end = models.DateField(...) I need a Queryset in which there are records for each study year with a month in its date range (start_date:end_date) Example: For the study year (09/01/2022:01/02/2023), qs should contain records: ... (code=9_2022, name='September 2022'), (code=10_2022, name='November 2022'), (code=11_2022, name='October 2022'), (code=12_2022, name='December 2022'), (code=1_2023, name='January 2023'), (code=2_2023, name='February 2023'), ... Honestly, I have no idea how to solve this problem, I really hope for your help! -
how to compare dictionaries and color the different key, value
I have a django application. And I have two texboxes where data is coming from two different functions. So the data is displayed in the texboxes. But the key,value has to be marked red when there is a difference in the two dictionaries. So in this example it is ananas that has the difference. So I have the TestFile with the data: class TestFile: def __init__(self) -> None: pass def data_compare2(self): fruits2 = { "appel": 3962.00, "waspeen": 3304.07, "ananas": 30, } set2 = set([(k, v) for k, v in fruits2.items()]) return set2 def data_compare(self): fruits = { "appel": 3962.00, "waspeen": 3304.07, "ananas": 24, } set1 = set([(k, v) for k, v in fruits.items()]) return set1 def compare_dic(self): set1 = self.data_compare() set2 = self.data_compare2() diff_set = list(set1 - set2) + list(set2 - set1) return diff_set the views.py: from .test_file import TestFile def data_compare(request): test_file = TestFile() content_excel = "" content = "" content = test_file.data_compare() content_excel = test_file.data_compare2() diff_set =test_file.compare_dic() context = {"content": content, "content_excel": content_excel, "diff_set": diff_set} return render(request, "main/data_compare.html", context) and the template: {% extends 'base.html' %} {% load static %} {% block content %} <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div … -
Django Rest Framework's API for Razorpay Callback couldn't be authenticated
@api_view(['POST']) @permission_classes([]) #@permission_classes([IsNormalUser])# cant use, JWT misses @authentication_classes([]) def verifyRazorPay(request): if success: return Response(success) else: return Response(failure) As you can see in the code this is a callback API for Razorpay. But I couldn't make this secure by any of the permission_classes, authentication_classes because Razorpay doesnt use any of JWT tokens for headers that I use in my website application. How to secure this in any manner by authorizing .. that anonymous users cant throttle it. -
How to save a resized image Django?
I try to save both, an original and a resized image and can't understand on what step Django will understand from WHICH FIELD it will take the image to resize and then save. MODELS.PY: from django.db import models from django_resized import ResizedImageField class Post(models.Model): thumbnail = models.ImageField(upload_to ='uploads/posts/large/') thumbnail_small = ResizedImageField(size=[100, 100], upload_to='uploads/posts/small/') FORMS.PY class PostForm(forms.ModelForm): class Meta: model = Post fields = ['thumbnail','thumbnail_small'] HTML: <form method = "POST" action = "{% url 'adminpanel' %}" enctype = "multipart/form-data"> {% csrf_token %} <input type = "file" id = "file" name = "thumbnail" accept = "image/png, image/jpeg"> <button type = "submit" class = "btn" name = "apost">Add Post</button> </form> So, the question is, where will Django understand that it has to save image directly from the <input name = "thumbnail"> directly to thumbnail = models.ImageField(upload_to ='uploads/posts/large/') and also to thumbnail_small = ResizedImageField(size=[100, 100], upload_to='uploads/posts/small/')? Thanks in advance. -
django serializer error: images_data = self.context['request'].FILES KeyError: 'request'
models.py ` # from django.db import models from user.models import User from chat.models import TradeChatRoom, AuctionChatRoom class Goods(models.Model): class Meta: db_table = 'Goods' ordering = ['-created_at'] # 일단 추가해뒀습니다 seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sell_goods') buyer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='buy_goods', null=True) trade_room = models.ForeignKey(TradeChatRoom, on_delete=models.CASCADE) auction_room = models.ForeignKey(AuctionChatRoom, on_delete=models.CASCADE) title = models.CharField(max_length=256) content = models.TextField() category = models.CharField(max_length=32) status = models.BooleanField(null=True) predict_price = models.IntegerField() start_price = models.IntegerField() high_price = models.IntegerField(null=True) start_date = models.DateField(null = True) start_time = models.DateTimeField(null=True) created_at = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField(User, related_name='like_goods', null=True) class GoodsImage(models.Model): class Meta: db_table = "GoodsImage" goods = models.ForeignKey(Goods, on_delete=models.CASCADE) image = models.ImageField(upload_to='goods/') ` serializer.py from rest_framework import serializers from .models import Goods,GoodsImage class GoodImageSerializer(serializers.ModelSerializer): image = serializers.ImageField(use_url=True) def get_image(self, obj): image = obj.goods_set.all() return GoodsPostSerializer(instance=image, many = True, context = self.context) class Meta: model = GoodsImage field =('image',) class GoodsPostSerializer(serializers.ModelSerializer): image = GoodImageSerializer(many=True, read_only = True) class Meta: model = Goods fields = ( 'seller', 'buyer','auction_room','title','content', 'category','status','predict_price','start_price','high_price', 'trade_room','start_date','start_time','created_at','like','image', ) read_only_fields = ("seller",) def create(self, validated_data): goods = Goods.objects.create(**validated_data) images_data = self.context['request'].FILES for image_date in images_data.getlist('image'): GoodsImage.objects.create(goods = goods, image = image_date) return goods error images_data = self.context['request'].FILES KeyError: 'request' I want to save multiple images, but I keep getting an error. I don't … -
What is right order for defining django view decorators
I want to set more than one decorator for my django function view. The problem is that I can't figure out how should be the order of decorators. For example this is the view I have: @permission_classes([IsAuthenticated]) @api_view(["POST"]) def logout(request): pass In this case, first decorator never applies! neither when request is POST nor when it's GET! When I change the order, to this: @api_view(["POST"]) @permission_classes([IsAuthenticated]) def logout(request): pass the last decorator applies before the first one, which is not the order that I want. I want the decorator @api_view(["POST"]) to be applied first, and then @permission_classes([IsAuthenticated]). How should I do that? -
Mysterious Issues uploading images Django
I hope someone can help me out here, something strange and mysterious is happening with my code. I have a project which was working normally, but suddenly the images stopped to get uplodad. I was working on an update method in the viewset when I realized that. even more awkward is that I have two apps on my application one uploads the images normally and other doesn't. I have tried to change the upload_to direction on the field which is not been uploaded and noticed that the new direction hasn't been applied, the destination folder is saved in the database with a previous direction (even though the picture never gets uploaded) below you have the codes: first the result of an update: notice the address { "profile": 4, "card": "teste2", "points": 0, "created": "2022-11-29T16:05:33.502027Z", "updated": "2022-11-30T10:26:15.063888Z", "code": "673476", **"image": "http://127.0.0.1:7000/medias/media/app_user/img_DENklQy.jpg"** } now the models, notice the upload_to: class MyCards(models.Model): profile = models.ForeignKey(AppUserProfile, on_delete=models.CASCADE) card = models.ForeignKey(Cards, on_delete=models.CASCADE) points = models.IntegerField(default=0) **image = models.ImageField(upload_to='mycards', blank=True)** created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) code = models.CharField(max_length=6, blank=True, null=True) my settings: BASE_DIR = Path(__file__).resolve().parent.parent MEDIA_URL = '/medias/' MEDIA_ROOT = os.path.join(BASE_DIR, 'medias' ) viewset, I have removed the update overriding method, to check if was … -
My colleague and I argue is pizza or kebab better for increasing programming performance
My colleague and I argue is pizza or kebab better for increasing programming performance. Pizza is richer with carbohydrates, while kebab has more veggies and meat in it and is better balanced. We work in Django framework. We'd like to hear your professional opinion. We tried both pizza and kebab and after pizza we feel sleepy some time. While kebab doesn't get you sleepy, but it doesn't get you full either. -
How to use Lookups that span relationships in Django
I have models User, Store, Warehouse and Product. I need to get all products from the warehouse. User have a lot of stores. One store have a lot of warehouses. А product with the same identifier (SKU) can be stored in different warehouses. def get_queryset(self): return Product.objects.filter( warehouse__store__user_id=self.request.user.pk)\ .order_by('-offer_id') Am I right to filter products such way? -
Getting bad Request Error when I try to send formdata including an attachment to DRF Backend from React Native Frontend
I am working on a react native project where I have to send a "Request Financial Aid" form to backend, The form also consists of a file(image or pdf), I have used react native document picker to get the file then I used file uri to fetch the blob. The next thing I did is send the formdata to backend however my backend is not getting all the values which I send from frontend which may be the reason why I am getting Bad Request. Error Trace Here My Backend works fine when I send data from my web app so I know the issue isn't in the backend. This is How I am picking the file: const selectFile = async () => { // Opening Document Picker to select one file try { const res = await DocumentPicker.pickSingle({ type: [DocumentPicker.types.allFiles], }); console.log('res simple', res); console.log('res : ' + JSON.stringify(res)); //fetch uri from the response const fileUri = res.uri; console.log('res : ' + fileUri); setSingleFile(res); // handleAcceptedFiles(res); } catch (err) { setSingleFile(null); if (DocumentPicker.isCancel(err)) { ToastAndroid.show('Canceled', ToastAndroid.SHORT); } else { alert('Unknown Error: ' + JSON.stringify(err)); throw err; } } }; This is how I am getting blob using file uri. … -
Can I get error index with bulk_create/bulk_update?
I'm using bulk_create method to insert data from an Excel sheet to db. This data can be incorrect (ex: cell contains "Hello World" when it should be an integer) and I'd like to return user thorough information error. Currently, bulk_create raises a ValueError, ex: Field 'some_integer_field' expected a number but got 'Hello World'. Is it possible to get more details about this error, something like : **Line 4** - Field 'some_integer_field' expected a number but got 'Hello World'. without saving each object individually ? Does it even make sense since bulk_create produces a single transaction ? I'm running Django 4.1.3 with PostgreSQL 12. My code looks like self.MyModel.bulk_create(self.objects_to_create) -
Python virtualenv error with apache,plesk panel
I have a rest-django project. The project uses plesk panel, centos 7 and apache. When I run my project, I'm getting an error that requires the use of virtualenv as output. print: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'iyziwell.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() I use https://support.plesk.com/hc/en-us/articles/115002701209-How-to-install-Django-applications-in-Plesk- https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 my site https://api.iyziwell.com -
Filtering empty parameter on get request - Django
How do I filter if the get parameters is empty? foo_id (Model Foos) is a FK in Bars Model class BarsFilterSet(FilterSet): co_foo = CharFilter(field_name='foo_id__co_foo') class Meta: model = Bars fields = ['co_foo', 'language'] class GetBarsViewSet(viewsets.ModelViewSet): filterset_class = BarsFilterSet queryset = Bars.objects.all() serializer_class = BarsSerializer filter_backends = [DjangoFilterBackend] -
How to get 2 different classes in 1 model field in django?
I am working in a project, where I have to merge/combine different classes into one field. I want to do it that way, because I have two different classes ParkingArea1 and ParkingArea2 and I want to have the choice from the Admin and WebInterface, to select any of these two areas from a single drop-down list, and ideally store them in another's model field. These are my models: class ParkingArea1(models.Model): zone_name = models.Charfield(max_length=255, unique=True) # some more unique fields below def __str__(self): return self.zone_name class ParkingArea2(models.Model): area_name = models.CharField(max_length=200, db_index=True, null=True, unique=True) # some more unique fields below def __str__(self): return self.area_name class ChooseYourArea(models.Model): area = # here I want a field, which should be able to hold any of the above classes # some other stuff How should I reform my models to achieve that? NOTE: ParkingArea1 and ParkingArea2 are two actively used tables filled with data, so a change within these models wouldn't be optimal. I researched a bit but couldn't find something to fit my case. I understand that an abstract Base Class could be used for this case, but such a Base Class won't allow me to list all the areas that I want. Is there … -
ClusterMetadata not working as expected with given Apache Kafka
I try to get brokers under a cluster providing one of the bootstrap servers. When I provide localhost:29092, following code returns bootstrap-0 with given port. The response is the same for all inputs. clusterMeta = ClusterMetadata(bootstrap_servers=[bootstrap_server]) brokerList = [] for broker in clusterMeta.brokers(): brokerList.append(broker) return JsonResponse(json.dumps(brokerList), safe=False) Here's my docker container: version: '2' services: zookeeper-1: image: confluentinc/cp-zookeeper:latest environment: ZOOKEEPER_CLIENT_PORT: 2181 ZOOKEEPER_TICK_TIME: 2000 ports: - 2181:2181 kafka-1: image: confluentinc/cp-kafka:latest depends_on: - zookeeper-1 ports: - 29092:29092 environment: KAFKA_BROKER_ID: 1 KAFKA_ZOOKEEPER_CONNECT: zookeeper-1:2181 KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka-1:9092,PLAINTEXT_HOST://localhost:29092 KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 -
rest_framework_swagger installation - HTTP 401 Unauthorized
I have installed rest_framework_swagger successfully, after that I set url in urls.py file project: from django.contrib import admin from django.urls import path, include, re_path from unimiproject.router import router from rest_framework.authtoken import views from rest_framework.schemas import get_schema_view from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), re_path(r"^appjud/",include("appjud.urls")), path('api/', include(router.urls)), path('api-token-auth/', views.obtain_auth_token, name='api-token-auth'), path('openapi/', get_schema_view( title="School Service", description="API developers hpoing to use our service" ), name='openapi-schema'), path('docs/', TemplateView.as_view( template_name='documentation.html', extra_context={'schema_url':'openapi-schema'} ), name='swagger-ui') ] but if I browse http://172.18.0.1:7000/openapi/ I get this: Schema GET /openapi/ HTTP 401 Unauthorized Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Token { "detail": "Authentication credentials were not provided." } Why do I get "Authentication credentials were not provided"? It should show me schema of all apis not to test they. -
Django HTMX forms passing id of the foreign key chosen
This is my models.py class Services(models.Model): name = models.CharField(max_length=50) price = models.FloatField() description = models.CharField(max_length=500, null=True) # employees = def __str__(self): return self.name class Venue(models.Model): name = models.CharField(max_length=50) services = models.ManyToManyField(Services) description = models.CharField(max_length=500, null=True) capacity = models.FloatField() venue_price = models.FloatField(null=True) # available = def __str__(self): return self.name class Order(models.Model): venue = models.ForeignKey(Venue, on_delete=models.SET_NULL, null=True, default=1) services = models.ManyToManyField(Services, null=True) total_price = models.FloatField(null=True) # date = In my html i made a set of radio buttons with the venue foreign keys from order. When the user chooses the venue they want i want the services to change based on what services are available in that venue. I don't understand how i can send a htmx request to views that passes a pk for what venue has been chosen. This is my html <div class="container"> <div hx-post="{% url "planner:create"%}" hx-swap="beforeend" hx-trigger="click" hx-target="#services" class="container form-check-inline"> {{ form.venue }} </div> </div> <div id="services"></div> This is views.py class EventCreateView(CreateView): model = Order form_class = OrderForm context_object_name = "venue" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) venue = Venue.objects.get(pk=???) context["services"] = venue.services.all() return context def get_template_names(self, *args, **kwargs): if self.request.htmx: return "planner/order_form_partial.html" else: return "planner/order_form.html" This is urls.py urlpatterns = [ path("create/", EventCreateView.as_view(), name="create"), ] -
ModuleNotFoundError: No module named 'PIL' , A problem came when I run my Django Project
When I try to run my Django project, it came an error:'ModuleNotFoundError: No module named 'PIL''. I try install Pillow in my virtual environment, but it still can't work. enter image description here -
Django AttributeError: 'bytes' object has no attribute '_committed'
Hi I have API in REST Framework. I send on mobile phone POST request with multiple images. My views.py: images = request.FILES.get('images') ad=models.Ad.objects.create(title=request.data['title'], content=request.data['content'],category=cat_id) for image in images: img = models.Images.objects.create(ad=ad,image=image) img.save() and i get error on POST request: AttributeError: 'bytes' object has no attribute '_committed' request.FILES : <MultiValueDict: {'images': [<InMemoryUploadedFile: scaled_image_picker5837141763302518082.jpg (image/png)>, <InMemoryUploadedFile: scaled_image_picker9163246472297616682.jpg (image/png)>]}> -
How to check if a ManyToManyField is subset of a queryset while filtering a queryset of a model in Django
class OrganizationUser(models.Model): pass class Feedback(models.Model): teams_shared_with = models.ManyToManyField('team.Team', related_name="feedback") class Team(models.Model): leads = models.ManyToManyField('organizations.OrganizationUser', related_name='teams_lead_at') members = models.ManyToManyField('organizations.OrganizationUser', related_name='teams_member_at', blank=True) I have the above models, all the fields were not shown. I want to filter those feedback which are shared in any team where I am a member or an admin. I would like to do something like: Feedback.objects.filter(teams_shared_with is a subset of organization_user.teams_lead_at.all()|organization_user.teams_member_at.all()) How would I do that? -
Django Polymorphic - Migrating a model that extends from a model that extends from PolymorphicModel
I have this kind of situation right now : Suppose I have 2 models that extends django Models, name it Post and Question It looks like this class Post(models.Model): ... class Question(models.Model): ... These two models has already have its own table in database and perhaps some other Model relates through a Foreign Key. Now suppose that I want to make another model that extends a PolymorphicModel from django-polymorphic, name it Commentable So it looks like this class Commentable(PolymorphicModel): ... And the two existing model wants to extend these new class like class Question(Commentable): ... class Post(Commentable): ... Now my question is how can migrate all the existing data including their related models from the existing Question and Post so they can be migrated and maintaining their Integrity? I know that one of the possible solution is to create a temporary model for Question and move all the existing data there deleting all the old data But this solution is kinda "poor" to maintaining the data integrity and it means that all the related model must be maintained in such a way so that their Foreign Key points to the updated primary key after migrating Is there any better approach … -
Invalid model identifier while migrating my data from sqlite3 to PostgreSQL
I'm trying to migrate my Wagtail application from sqlite3 to PostgreSQL but I'm getting an error saying Invalid model identifier: 'wagtailsearch.sqliteftsindexentry' This is while I type in the command: python manage.py loaddata data.json I get this error: Traceback (most recent call last): File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\apps\config.py", line 235, in get_model return self.models[model_name.lower()] KeyError: 'sqliteftsindexentry' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\serializers\python.py", line 181, in _get_model return apps.get_model(model_identifier) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\apps\registry.py", line 213, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\apps\config.py", line 237, in get_model raise LookupError( LookupError: App 'wagtailsearch' doesn't have a 'sqliteftsindexentry' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\DELL\Desktop\Mdrift_Wagtail\mdrift\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\management\commands\loaddata.py", line 102, in handle self.loaddata(fixture_labels) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\management\commands\loaddata.py", line 163, in loaddata self.load_label(fixture_label) oad_label for obj in objects: File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\serializers\json.py", line 70, in Deserializer yield from PythonDeserializer(objects, **options) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\serializers\python.py", line 103, in Deserializer Model = _get_model(d["model"]) File "C:\Users\DELL\Desktop\Mdrift_Wagtail\venv\lib\site-packages\django\core\serializers\python.py", line 183, in _get_model raise base.DeserializationError( django.core.serializers.base.DeserializationError: Problem … -
I want to create a report of all update history of my lead model in django
I have a Training_Lead model, in my team i have 5-6 members who can edit this lead from there id's. I want to create a report of Update history that who is update lead and when, fro that i have create a two coloum names last_modification and last_modification_time which is automaticaly update when someone update lead. class Training_Lead(models.Model): handel_by = models.ForeignKey(UserInstance, on_delete=models.PROTECT) learning_partner = models.ForeignKey( Learning_Partner, on_delete=models.PROTECT, blank=False, null=False) assign_to_trainer = models.ForeignKey( Trainer, on_delete=models.PROTECT, null=True, blank=True) course_name = models.CharField(max_length=2000) lead_type = models.CharField(max_length=2000) time_zone = models.CharField(choices=(('IST', 'IST'), ('GMT', 'GMT'), ('BST', 'BST'), ( 'CET', 'CET'), ('SAST', 'SAST'), ('EST', 'EST'), ('PST', 'PST'), ('MST', 'MST'), ('UTC', 'UTC')), max_length=40, blank=False, null=False) getting_lead_date = models.DateTimeField(null=True, blank=True) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) lead_status = models.CharField(choices=(('Initial', 'Initial'), ('In Progress', 'In Progress'), ('Follow Up', 'Follow Up'), ( 'Cancelled', 'Cancelled'), ('Confirmed', 'Confirmed'), ('PO Received', 'PO Received')), max_length=40, blank=False, null=False) lead_description = models.CharField(max_length=9000, blank=True, null=True) last_modification = models.CharField(null=False, blank=False, max_length=500) last_modification_time = models.DateTimeField(auto_now_add='True') def __str__(self): return str(self.assign_to_trainer) class Meta: ordering = ['start_date']