Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django overriding a formfield with a queryset gives KEY ERROR
I am creating a chained dropdown list, Where selection-options of dropdown field B is based on value of field A. It works fine on Create, But when updating, it gives me a key error even though I am overriding the field to display the Selections based on the current instance of the form. I am able to print out the query set in console but when passed into the form gives a Key error. Searched for a very long time. Any help would be appreciated. Thanks!! Models.py class ReadingArea(models.Model): ReadingAreaNo = models.IntegerField() ReadingAreaNM = models.CharField(max_length=20) def __str__(self): return self.ReadingAreaNM class StoreMaster(models.Model): StoreNO = models.IntegerField() ReadingAreaNo = models.ForeignKey(ReadingArea, on_delete=models.CASCADE) class Meta: unique_together = ['StoreNO','ReadingAreaNo'] def __str__(self): return str(self.StoreNo) class MeterMaster(models.Model): MeterID = models.IntegerField(unique=True) ReadingAreaNo = models.ForeignKey(ReadingArea, on_delete=models.CASCADE) StoreNO = models.ForeignKey(StoreMaster,on_delete=models.CASCADE) def __str__(self): return str(self.MeterID) Forms.py from structure.models import MeterMaster,ReadingArea, StoreMaster class MeterMasterForm(ModelForm): class Meta: model = MeterMaster fields = ['MeterID','ReadingAreaNo','StoreNO'] def __init__(self, *args, **kwargs): super().__init__(*args,**kwargs) self.fields['StoreNO'].queryset = ReadingArea.objects.none() if 'ReadingAreaNo' in self.data: try: ReadingAreaNo_id = int(self.data.get('ReadingAreaNo')) self.fields['StoreNO'].queryset = StoreMaster.objects.filter(ReadingAreaNo_id=ReadingAreaNo_id).order_by('StoreNo') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: print('The queryset in console' , StoreMaster.objects.filter(ReadingAreaNo__ReadingAreaNo = self.instance.ReadingAreaNo.ReadingAreaNo)) self.fields['StoreNo'].queryset = StoreMaster.objects.filter(ReadingAreaNo__ReadingAreaNo = self.instance.ReadingAreaNo.ReadingAreaNo) … -
Django Field 'id' expected a number but got 'test'
I try to make login. When user enter its username and password inputs. Django should match the datas from database if it exists or not but when I write HosLocUser = Hospital_Local_User.objects.filter(email=username, password=passwo) It gives this error Field 'id' expected a number but got 'test'. My codes here def login(request): if request.method == 'POST': username = request.POST.get("email") passwo = request.POST.get("password") try: HosLocUser = Hospital_Local_User.objects.filter(email=username, password=passwo) except ValidationError as e: return HttpResponse(e) if not HosLocUser: return HttpResponse("User is not found") else: output = {"jwt": generateJWT.jwt_creator(60, username, passwo)} return JsonResponse(output) return render(request, 'Login.html') Related model class Hospital_Local_User(models.Model): id = models.AutoField(primary_key=True) email = models.CharField(max_length=45) password = models.CharField(max_length=45) phone = models.CharField(max_length=45) def __str__(self): return f'Id = {self.id}, name = {self.email}' -
I am unable to import views in my app's urls.py file
I added the necessary stuffs for the work. Edited settings.py and added my app in the INSTALLED APPS, included the include function in urls.py of the base, typed a def in views.py file even. All that is bugging is the app urls.py. I did worked on django multiple time, but still can't figure out. Help me out, please! Grateful Settings.py INSTALLED_APPS = [ 'first', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] view.py from django.shortcuts import render, redirect, HttpResponse def home(request): return HttpResponse("YES") Base urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('first.urls')), ] App url.py from django.urls import path from first import views #problem here urlpatterns = [ path('', views.home), #and problem here ] File-tree ├───banner │ │ db.sqlite3 │ │ manage.py │ │ │ ├───banner │ │ │ asgi.py │ │ │ procfile │ │ │ requirements.txt │ │ │ settings.py │ │ │ urls.py │ │ │ wsgi.py │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ settings.cpython-39.pyc │ │ urls.cpython-39.pyc │ │ wsgi.cpython-39.pyc │ │ __init__.cpython-39.pyc │ │ │ └───first │ │ admin.py │ │ apps.py │ │ forms.py │ │ models.py │ │ tests.py │ … -
Systemd: Messages are logged at the end of script execution
I have Django site that have custom management command that sync data from one system to database every 5 min. In the script for the command there is serveral log messages. When I manually execute the command, everything is working fine and each log message is outputed to stdout/stderr at the time as it should be. No problem here. For running the command every 5min, I setup systemd service and timer and it is working as it should be with one minor thing. All messsages from the script are logged in systemd at the time when the script execution ended, not at the time when they happened. The script is usually running about one minute and log message is outputed sporadically as each subtask in the script has ended. In my case, systemd logged all messages as if they happend at the same time, more precisely at the end of execution. So, log is looking something like this and pay attention on timestamp of messages. Jul 16 09:20:01 SmallServer systemd[1]: Started DjngoSite Sync daemon. Jul 16 09:20:40 SmallServer python[21265]: Task 1 completed Jul 16 09:20:40 SmallServer python[21265]: Task 2 completed Jul 16 09:20:40 SmallServer python[21265]: Task 3 completed Jul 16 … -
the procution rq schedule job exmple
you should use django command to run schedule job https://docs.djangoproject.com/en/3.2/howto/custom-management-commands/ enter image description here then run python manage.py rq_crontab_job then run python manage.py rqscheduler --queue crontab_job them run python manage.py rqworker crontab_job i think the first answer is greate,but in multi-Progress enviroment may have some probelm,you should only run once to pub job in queue! -
How to connect django with cosmos db using SQL API?
I want to connect Django with Azure Cosmos DB. Either with Core SQL. Do we have any existing libraries we can use to achieve it? -
How to save a file using django's File object
I am using Celery to strip the audio from an uploaded video file. I want to save the audio file into my model where the video file is. So this is what I am trying: # model class Video(models.Model): file = models.FileField( validators=[ FileExtensionValidator( allowed_extensions=["mp4", "mov", "flv", "mkv", "avi"] ) ] ) processed_file = models.FileField( validators=[FileExtensionValidator(allowed_extensions=["flac"])], null=True, blank=True, ) # celery task output_audio_file = str(settings.MEDIA_ROOT) + "/" + str(video_obj.pk) + ".flac" ffmpeg.input(video_obj.file.path).output( output_audio_file, **{ "ac": 1, "ar": 16000, "format": "flac", }, ).run() dj_file = File(open(output_audio_file)) video_obj.processed_file = dj_file video_obj.save() This raises the Detected path traversal attempt in '/app/proj/media/49.flac' exception. I also tried with the context manager, with the video_obj.processed_file.save() method. All of which raise TypeError, AttributeError, UnicodeDecodeError and so on. I feel like the answer could be so simple but I just couldn't find it. -
Module 'rest_framework.request' has no attribute 'method' Django error
I'm having a strange error and I didn't find answers nowhere and that's mean that I need your help(again). So, I'm having two views in my views.py file and I'm trying to adding GET and POST methods for one view, I've tried to check the method with request. Method but rest frame work module tells me that has no that attribute, can you help me, please, with a fix for this issue? Thank you! In models.py I have: class ChatViewSet(ConversationViewSet): @api_view(['GET', 'POST']) def get_chat(self, **kwargs): if request.method == 'GET': information = Chat.objects.all() tutorials_serializer = ChatSerializer(information, many=True).data return JsonResponse(tutorials_serializer, safe=False) elif request.method == 'POST': tutorial_data = JSONParser().parse(request) tutorial_serializer = ChatSerializer(data=tutorial_data) tutorial_data['status'] = 'new' tutorial_data['chat_id'] += 1 if tutorial_serializer.is_valid(): tutorial_serializer.save() return JsonResponse(tutorial_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(tutorial_serializer.errors, status=status.HTTP_400_BAD_REQUEST) In urls.py: urlpatterns = [ url(r'^conversation/', ConversationViewSet.get_all), url(r'^conversation/(?P<pk>[0-9]+)$', ConversationViewSet.get_by_id), url(r'chat', ChatViewSet.get_chat), ] And error: if request.method == 'GET': AttributeError: module 'rest_framework.request' has no attribute 'method' -
How to disable password requirement for the Django admin app?
I'd like to disable the password requirement for the Django admin app. Is that possible and if so how? -
How can I filter the field so that when I select a category, only those products that belong to this category are displayed?
My models, category and product. Each product has a category field, which is linked through ForeignKey. class Category(models.Model): name = models.CharField(max_length=50, unique=True) description = models.TextField() image = models.ImageField(upload_to='category', blank=True) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=50, unique=True) description = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='product', blank=True) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'product' verbose_name_plural = 'products' def __str__(self): return self.name And views, a product category can be selected and when I click on a category, I want the product to appear only in that category class CategoriesList(LoginRequiredMixin, ListView): login_url = 'login/' template_name = 'index.html' model = Category class ProductsList(ListView): template_name = 'products.html' model = Product def get_queryset(self): return super().get_queryset().filter(category=category_id) -
How to serve Images with Heroku and Django
After deoploying to heroku it was initially working fine, but would disappear (I'm assuming because of the unmounting thing) So some googling and I changed DEBUG = False and also added ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'HEROKU LINK'] but that didn't fix the problems and now my images are not even being shown after upload I've looked at a few solutions but nothing that really explains (or particularly works), it shows my image location as HEROKU-LINK/media/photos/2021/07/16/dev.jpeg Using Heroku for Django Media Files My static files are fine, they don't disappear only my images. I have the heroku postgres addon as a database, do I need to add something like CLoudinary or AWS S3? Or is there a way to get it working normally with Heroku (and not adding more cost to my side project blog) my settings.py STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'build/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') my model class BlogPost(models.Model): title = models.CharField(max_length=100, default='Title') slug = models.SlugField() category = models.CharField(max_length=55, choices=Categories.choices, default=Categories.RANDOM) thumbnail = models.ImageField(upload_to='photos/%Y/%m/%d/') excerpt = models.CharField(max_length=150) month = models.CharField(max_length=9) day = models.CharField(max_length=2) year =models.CharField(max_length=4, default='2021') content = models.TextField() featured = models.BooleanField(default=False) hide = models.BooleanField(default=False) date_created = models.DateTimeField(default=datetime.now, blank=True) -
Adding a maximum limit to the number of post using python
I need to limit the number of post in Django queries. I have tried to add a min and max but nothing seemed to have worked. view.py: class HomeView(ListView): model = Post template_name = 'home.html' ordering = ['-id'] -
Should I use docker in order to be able to run ChomeDriver on Azure Web App Services in Django Server?
Recently I have started a Django server on Azure Web App Service, now I want to add a usage of "ChromoDriver" for web scraping, I have noticed that for that I need to install some additional Linux packages (not python) on the machine. the problem is that it gets erased on every deployment, does it mean that I should switch to Docker ? -
Unable to connect aws RDS to django local
I am trying to connect my local django application to amazon RDS (tried with both MySQL and PostgreSQL) but I am not able to connect as it shows the following errors, Currenty seeking answer for PostgreSQL: In my Settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'database_name', 'USERNAME': 'my_username', 'PASSWORD': 'my_password', 'HOST': 'database-abc.xxx.us-region-yyy.rds.amazonaws.com', 'PORT': '5432', } } In AWS database configuration: Error: Is the server running on host "database-abc.xxx.us-region-yyy.rds.amazonaws.com" (69.420.00.121) and accepting TCP/IP connections on port 5432? I reffered to all the available data but still am unable to resolve this issue! Thanks in advance! -
Saving User details in UserDetail Table using One-To-One Relation Django Rest API
I am new to django. I am trying to save User details in another table using One-To-One relation by following Django document but is giving me an error Models.py class UserDetails(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) phone=models.CharField(max_length=10) address=models.CharField(max_length=200,default="") created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) objects=models.Manager() def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserDetails.objects.create(user=instance,phone="",address="") receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.userdetails.save() Serializer.py class UserDetailsSerializer(serializers.ModelSerializer): class Meta: model = UserDetails fields= ['phone','address'] class CreateUserSerializer(serializers.ModelSerializer): user=UserDetailsSerializer() class Meta: model =User fields=['id','url','username','email','password','user'] def create(self, validated_data): user_data=validated_data.pop('user') user=User.objects.create(**validated_data) UserDetails.objects.create(user=user,**user_data) return user When i write above in serializer.py user=UserDetailsSerializer(read_only=True) else give me following error Got AttributeError when attempting to get a value for field user on serializer CreateUserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'user'. I found one way to make it work but I have to define every field manually but I want the above serializer to work Working Serializer.py class CreateUserSerializer(serializers.HyperlinkedModelSerializer): last_login=serializers.ReadOnlyField() date_joined=serializers.ReadOnlyField() phone=serializers.CharField(source='userdetails.phone') address=serializers.CharField(source='userdetails.address') updated=serializers.ReadOnlyField(source='userdetails.updated') # password=serializers.CharField(style={'input_type':'password'},write_only=True) class Meta: model = User fields=['id','first_name','last_name','username','password','phone','address','url','email','is_superuser','is_staff','last_login','date_joined','updated'] extra_kwargs={ 'password':{'write_only':True}, } def create(self, validated_data): userdetails_data=validated_data.pop('userdetails') user=User.objects.create_user(**validated_data) user.userdetails.phone=userdetails_data.get('phone') user.userdetails.address=userdetails_data.get('address') user.save() return user -
How to write reverse function of django mptt data migration
I am writing a data migration for an old table, In this migration, I want to rebuild the tree so that I can persevere the old parent-child relationship. Here is how I am doing this: # Generated by Django 3.0.6 on 2021-07-14 13:03 from django.db import migrations, transaction from mptt import register, managers def rebuild_tree(apps, schema_editor): Category = apps.get_model('core', 'Category') manager = managers.TreeManager() manager.model = Category register(Category) manager.contribute_to_class(Category, 'objects') with transaction.atomic(): manager.rebuild() class Migration(migrations.Migration): dependencies = [ ('core', '0269_auto_20210714_1303'), ] operations = [ migrations.RunPython(rebuild_tree) ] But I am confused about how to write it reverse function? What exactly to do in it? -
Django 'ascii' codec can't encode characters despite encoding in UTF-8? What am I doing wrong?
I'm still in the process of learning Django. I have a bit of a problem with encoding a cyrillic strings. I have a text input. I append it's value using JS to the URL and then get that value in my view (I know I should probably use a form for that, but that's not the issue). So here's my code (it's not complete, but it shows the main idea I think). JS/HTML var notes = document.getElementById("notes").value; ... window.location.href = 'http://my-site/example?notes='+notes <input type="text" class="notes" name="notes" id="notes"> Django/Python notes= request.GET.get('notes', 0) try: notes = notes.encode('UTF-8') except: pass ... sql = 'INSERT INTO table(notes) VALUES(%s)' % str(notes) The issue is, whenever I type a string in cyrillic I get this error message: 'ascii' codec can't encode characters at position... Also I know that I probably shouldn't pass strings like that to the query, but it's a personal project so... that would do for now. I've been stuck there for a while now. Any suggestions as to what's causing this would be appreciated. -
trying to iterate through 2 lists using destructuring
I am trying to iterate through 2 lists using destructuring .. however, I am getting this error view job_skill_ = request.POST.getlist('job_skill_name[]') job_skill_level = request.POST.getlist('job_skill_level[]') job_pst = JobPost(creater=request.user, title=job_title, job_type=job_type, job_loc=job_loc, cmpny_name=compny, job_description=job_descrip, salary=salary) # job_pst.save() print(job_skill_) print(job_skill_level) for skill_, level in zip(job_skill_, job_skill_level): skil_set = Skillset.objects.get(skill_name=skill_) job_skill_set = Job_Skillset( skill=skil_set, job_post=job_pst, skill_level=level) job_skill_set.save() 'str' object is not callable print(job_skill_level) **for skill_, level in zip(job_skill_, job_skill_level): …** > <-- error is here skil_set = Skillset.objects.get(skill_name=skill_) job_skill_set = Job_Skillset( -
Calculating Percentiles using Django Aggregation
I maintain a Django service that allows online community moderators to review/approve/reject user posts. Right now we measure the average "time to approval" but we need to start measuring the 90th percentile "time to approval" instead. So where we used to say "on average content gets approved in 3.3 hours", we might now say something like "90% of content is approved in 4.2 hours or less". # Models.py class Moderation(models.Model): content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) message_id = models.TextField(blank=True, null=True) class ModerationAction(models.Model): moderation = models.ForeignKey(Moderation) action = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) # stats.py average_time_to_approve_7days = ModerationAction.objects.filter( action__in=moderation_actions, created_at__gte=timezone.now() - timedelta(days=7) ).annotate( time_to_approve=F('created_at') - F('moderation__created_at') ).values( 'action', 'time_to_approve' ).aggregate( Avg('time_to_approve') )['time_to_approve__avg'] # This returns a value like datetime.timedelta(0, 4008, 798824) My goal: I'm seeking a way to get the 90th percentile time rather than the average time. -
django custom action name change according to model name
I have created a custom admin action. I am using that action in more than one listing page. In my admin.py file def custom_action(request, modelAdmin, queryset): #do something here return response custom_action.short_description = 'My custom action for X' class MyXAdmin(admin.ModelAdmin): actions = [custom_action] class MyYAdmin(admin.ModelAdmin): actions = [custom_action] In both of my X and Y listing page it appears "My custom action for x". Is there any way to change the "X" => "Y" for Y listing page. OR How can I achieve to rename the custom_action name for individual listing page in djagno without writing custom method for each model. -
Resize image before submit form
I am trying to resize two images before sending them by ajax using javascript in case the size is too big. The formdata is more than 20 fields. Attached is part of the code. .on('core.form.valid', function (event) { var parameters = new FormData(document.getElementById("formulario")); // The fields are named 'DNI_img' and 'ficha_img'. $.ajax({ url: window.location.pathname, type: 'POST', data: parameters, dataType: 'json', processData: false, contentType: false, }).done(function (data) { // console.log(data); if (!data.hasOwnProperty('error')) { Swal.fire({ icon: 'success', title: '¡Tus datos han sido recibidos!', text: 'Pronto nos comunicaremos contigo.', confirmButtonText: '<a href="#">Ir a inicio</a>', }) return false; } message_error(data.error) }).fail(function (data) { alert("error"); }).always(function (data) { // alert("complete") }); }); Thanks in advance. -
Is it possible to use FastAPI as an alternative to Django Rest Framework with Django?
Hey guys I came to know about FastAPI and its benefits and would like to try use it with my Django project as an alternative to DRF. Is it possible to do that? Can anyone help me with an answer and also some leads if possible? Thanks -
Manage category and subcategory in django in admin panel
I want to display only related sub-categories when selecting a parent category in Django admin. How should I structure the model to achieve this? Or is there any packages available? Code (models.py) class Category(models.Model): name = models.CharField(max_length=200 , null=True) no_of_products = models.IntegerField(blank=True , null =True) image = models.ImageField(null=True , blank = True) class SubCategory(models.Model): main_category = models.ForeignKey('Category' , on_delete= models.SET_NULL , null = True) name = models.CharField(max_length=200 , null=True) no_of_products = models.IntegerField(blank=True , null =True) image = models.ImageField(null=True , blank = True) -
Multiple Models for SearchFilter - Django
Using Django 3.2 with Restframework. Iam trying for search filter and create a API with restframework which would output the searched term with its whole object. I had a little success on that with official doc. But from that I can only search in a single Model and not as globally. I found a blog on how to use multiple Models together? I tried for following from that: views.py class GlobalSearchList(generics.ListAPIView): serializer_class = GlobalSearchSerializer def get_queryset(self): query = self.request.query_params.get('query', None) users = MasterUser.objects.filter(Q(firstname__icontains=query) | Q(lastname__icontains=query) | Q(email__icontains=query) | Q(category__icontains=query)) webinar = MasterWebinar.objects.filter(Q(host__icontains=query) | Q(title__icontains=query)) resource = MasterResource.objects.filter(Q(route_name__icontains=query)) section = ResourceSection.objects.filter(Q(resource_name__icontains=query)) item = SectionItem.objects.filter(Q(item_title__icontains=query)) all_results = list(chain(users,webinar, resource,section,item)) return all_results serializers.py class GlobalSearchSerializer(serializers.ModelSerializer): class Meta: model = MasterUser fields = "__all__" def to_native(self, obj): if isinstance(obj, MasterIndividualMembers): serializer = MasterIndividualMembersSerializer(obj) elif isinstance(obj, MasterUser): serializer = MasterUserSerializer(obj) elif isinstance(obj, MasterWebinar): serializer = MasterWebinarSerializer(obj) elif isinstance(obj, MasterResource): serializer = MasterResourceSerializer(obj) elif isinstance(obj, ResourceSection): serializer = ResourceSectionSerializer(obj) elif isinstance(obj, SectionItem): serializer = SectionItemSerializer(obj) else: raise Exception("Not found in any instance!") return serializer.data Here I stuck at meta class, since it accepts only 1 model. -
getting no such table error when it actually exists in Django?
my views.py def analysis(request): serializer = QuizIDSerializer(data=request.query_params) serializer.is_valid(raise_exception=True) validated_data = serializer.validated_data student = Student.objects.get(user=2) responses = student.response_set.get(quiz_id=validated_data['quiz_id']) quiz = responses.quiz_id questions = quiz.question_set.all().order_by('id') print(questions) return Response(status=status.HTTP_200_OK) here I am getting error as OperationalError at /assessment/analysis/ no such table: assessment_response when i tried to execute line responses = student.response_set.get(quiz_id=validated_data['quiz_id']) my models.py class Quiz(models.Model): name = models.CharField(max_length=31) description = models.CharField(max_length=255, blank=True) classroom = models.ManyToManyField(Classroom, blank=True) instructions = RichTextUploadingField(max_length=10000, blank=True) class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) name = models.CharField(max_length=31, null=True, blank=True) class Option(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) name = models.CharField(max_length=4) option = RichTextField() state = models.PositiveSmallIntegerField(choices=O_STATE, default=0) class Response(models.Model): student_id = models.ForeignKey(Student,verbose_name="Student ID",null=True,on_delete=models.SET_NULL) quiz_id = models.ForeignKey(Quiz,verbose_name="Quiz ID",null=True,on_delete=models.CASCADE) responses = models.ManyToManyField(Option,verbose_name="Responses") my serializers.py from rest_framework import serializers class QuizIDSerializer(serializers.Serializer): quiz_id = serializers.IntegerField() I didn't understand the reason of the error, i have removed unnecessary details from the model, if you feel anything wrong please comment, i have this response table still it is giving error , please help