Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django nested serializers - Direct assignment to the reverse side of a related set is prohibited
I want to implement my own create function on my serializer but I'm getting the following error: Internal Server Error: /api/cheatsheets/ Traceback (most recent call last): File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/mixins.py", line 24, in perform_create serializer.save() File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/serializers.py", line 212, in save self.instance = self.create(validated_data) File "/home/christian-sama/Code/cheatsheet-app/api/serializers.py", line 35, in create Section.objects.create(cheatsheet=cheatsheet, **section) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/db/models/query.py", line 669, in create obj = self.model(**kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/db/models/base.py", line 562, in __init__ _setattr(self, prop, value) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 595, in __set__ raise TypeError( TypeError: Direct assignment to the reverse side of a related set is prohibited. Use lines.set() instead. My models.py from django.db import models class Cheatsheet(models.Model): title = models.CharField(max_length=500) description = models.CharField(max_length=500) score = models.IntegerField() … -
How to resolve django filter button not working?
I am trying to implement Django Filtering but I cant seem to make it work. Only an 'Option' button appears the 'filter' button does not. It still does not work. What seems to be the problem here? views.py class MKRealtyListView(generics.ListAPIView): queryset = Realty.objects.all() serializer_class = RealtySerializer filter_backends = [DjangoFilterBackend] filterset_fields = ('type', 'location') #@permission_classes([IsAuthenticated]) @api_view(['GET', 'POST']) def listings(request, format=None): if request.method == 'GET': realty = Realty.objects.all() serializer = RealtySerializer(realty, many=True) return Response(serializer.data) settings.py INSTALLED_APPS = [ 'rest_framework', 'mkrealty', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework.authtoken', 'django_filters' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend',] } urls.py urlpatterns = [ path('admin/', admin.site.urls), path('listings/', views.MKRealtyListView.listings), path('listings/<int:id>', views.listing_detail), path('api-token-auth/', obtain_auth_token, name='api_token_auth'), # <-- And here ] -
How to construct dynamic Q() in Django
I'm trying to filter dynamic value from a form in template to my query in Django project the value can be dynamic, but it would look like this first_query = ['a', 'b', 'c'] second_query = ['d', 'e', 'f'] what i want to achieve is to query something like this SELECT * FROM table WHERE column_1 = 'a' OR column_1 = 'b' OR column_1 = 'c' OR column_2 = 'd' OR column_2 = 'e' OR column_2 = 'f' Here's what i've done first_query = [ Q(column_1__contains=w) for w in first_query ] """ If you print first_query [<Q: (AND: ('column_1__contains', 'a'))>, <Q: (AND: ('column_1__contains', 'b'))>, <Q: (AND: ('column_1__contains', 'c'))>] """ reduce_first_query = reduce(or_, query_first_query) """ (OR: ('column_1', 'a'), ('column_1', 'b'),('column_1', 'c')) """ second_query = [ Q(column_2__contains=w) for w in second_query ] reduce_second_query = reduce(or_, query_second_query) When i try to filter Item from my database it gives me rows more than doubled than what i do directly from the database test_item = Item.objects.filter(reduce_first_query) # Gives 1900 ish rows, should be 900 ish What do i do wrong, is it because of the way i construct Q() ? or there other mistake ? NOTES I'm using Postgresql 14 -
How to address this codec error when fetching an api for image upload in django?
Error: UnicodeDecodeError at /user_image_upload/ 'utf-8' codec can't decode byte 0xcc in position 144: invalid continuation byte Payload: Image (binary) 500 internal server error. VueJS method/data...: data(){ return { profile_image:null } }, async createImage() { let received_image = document.querySelector('#imageInput').files[0] let formData = new FormData // 'image' as in models.py formData.append('image', received_image) fetch('/user_image_upload/',{ method:'POST', credentials: 'include', body: formData }).then(response => response.json()).then((data) => this.profile_image=(data)) console.log(this.profile_image) }, In Django template: {% csrf_token %} <form @submit.prevent=""> {% csrf_token %} <input id ="imageInput" type = "file" accept="image/"> <button @click="createImage()">Upload</button> </form> in models.py class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) image = models.ImageField(upload_to='uploads') def __str__(self): return f'{self.user.username} Profile' in views.py @login_required @csrf_exempt def user_image_upload(request): if request.method=='POST': response = json.loads(request.body) Item.objects.create(user=request.user) return JsonResponse({'new':'updated'}) -
Django - How to change Textarea rows and columns in media query
I am having difficulties trying to understand how to change Textarea sizes so that my webpage is responsive. I currently have it set where the rows are 8 and cols is 60 which is perfect for viewing a webpage on a desktop. However, as i am trying to make my webpage responsive, i can not find a way to change the column value down to 30. I have thought about using css media query for this but can not understand how to change the values as they are currently set in the forms.py file as as shown below. I know users are able to resize the Textarea but i would like it if they can not resize the text area. So my question is if it is possible to make the Textarea responsive? forms.py: class UserSettings(ModeldForm): class Meta: model = Profile fields = ["name", "email", "profile_biography"] widgets = { 'profile_biography': forms.Textarea(attrs={ 'rows': 8, 'cols': 60, 'style':'resize:none'}), } -
What is the purpose of using GraphQL with MVC web frameworks (Laravel, Django, etc.), when currently built-in controllers does not make sense then?
What is the purpose of using GraphQL with MVC web frameworks (Laravel, Django, etc.), when currently built-in MVC framework controllers do not make sense then? Is there any simpler way/framework with just that purpose and is the reason for that just love for Laravel, Django and other MVC frameworks? If there is nothing similar and simpler, could we build something good and open-source just for that purpose, taking into account the increasing popularity of using that architecture and logic with GraphQL? I am open to suggestions and to start such a project. (It would be nice to hear suggestions/opinions from @taylorotwell, @adrian-holovaty, @simon-willison, Jeffrey Way) After a lot of experience with backend and frontend technologies, that question comes to me logically. Thank you :) -
It is impossible to add a non-nullable field 'classid' to classes without specifying a default
from django.db import models class students(models.Model): studentid = models.BigIntegerField(null = False, primary_key = True) lastname = models.TextField() firstname = models.TextField() middlename = models.TextField() addr1 = models.TextField() addr2 = models.TextField() city = models.TextField() stateprovince = models.TextField() country = models.TextField() postalcode = models.TextField() email = models.TextField() class gradevalues(models.Model): grade = models.TextField(null = False, primary_key = True) qgrade = models.DecimalField(blank=True, null=True, max_digits=10, decimal_places=10) class stuclasses(models.Model): classid = models.BigIntegerField(null = False, primary_key = True, ) studentid = models.BigIntegerField(null = False) grade = models.ForeignKey(gradevalues, on_delete = models.CASCADE) class courses(models.Model): courseid = models.TextField(null = False, primary_key = True) coursename = models.TextField() coursedesc = models.TextField() credits = models.BigIntegerField(null = False) deptid = models.TextField() class classes(models.Model): classid = models.BigIntegerField(primary_key = True) courseid = models.ForeignKey(courses, on_delete = models.CASCADE) term = models.TextField() year = models.DecimalField(blank=True, null=True, max_digits=10, decimal_places=10) instructor = models.TextField() classroom = models.TextField() classtime = models.TextField() class stuclasses_students(models.Model): stuclasses_studentid = models.ForeignKey(stuclasses, on_delete = models.CASCADE) students_studentid = models.ForeignKey(students, on_delete = models.CASCADE) class stuclasses_classes(models.Model): stuclasses_classid = models.ForeignKey(stuclasses, on_delete = models.CASCADE) classes_classid = models.ForeignKey(classes, on_delete = models.CASCADE) It is impossible to add a non-nullable field 'classid' to classes without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now … -
Django migrations not applied
I am trying to do the portfolio project and when doing the migration part, I get this: Operations to perform: Apply all migrations: projects Running migrations: No migrations to apply. What am I doing wrong? I am following the exact steps written on the document I tried looking on google and could not find any good answers, please help. -
Authentication credentials were not provided. social django postman api testing
I'm developing a Django 4.1 application, and i'm using the drf-social-oauth2 framework. Here's my config: INSTALLED_APPS = [ ... 'oauth2_provider', 'social_django', 'drf_social_oauth2', ] TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ], 'DEFAUL_ATHENTICATION_CLASSES': [ # drf auth classes 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', # # oauth2 auth classes 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'drf_social_oauth2.authentication.SocialAuthentication', ] } AUTHENTICATION_BACKENDS = ( 'drf_social_oauth2.backends.DjangoOAuth2', 'django.contrib.auth.backends.ModelBackend', ) I generate the Bearer token normally to any user, but, when I try to make a request like to patch some user, i add at the authorization windown at postman type: Bearer, and Token: the valid one i just generated. The header is made by postman, and is ok, but when i test, I still recieving the "detail": "Authentication credentials were not provided." response code: 403 the url is right, and at the API i can patch it normally. Anyone knwos what's happening? thanks I tried changing the user, use a superuser or not, generating new tokens, change the body, nothing worked -
How to add a filter by category option using Django filter
Hai i am trying to add a filter option by category on django using Django filter. But when i am trying to add a filter i got an error saying that Field 'id' expected a number but got 'blogs'. Can anyone please help me to create a filter by category. This is my blog model class blog(models.Model): title = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(max_length=200, unique=True, auto_created=True) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) tags = TaggableManager(blank=True) category = models.ForeignKey('Categorie', null=True, blank=True, on_delete=models.CASCADE) This is my category model class Categorie(models.Model): name = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(max_length=250, unique=True, auto_created=True) This is my filters.py file blog_choice = ( ('new','new'), ('latest','latest'), ('technology','technology'), ('sports','sports'), ) category = django_filters.MultipleChoiceFilter(label='Category', choices=blog_choice, widget=CheckboxSelectMultiple(attrs={'class': 'mr-2 h-[15px] w-5 border-gray-300 inline mb-4 '})) I tried to create a filter function but got error Field 'id' expected a number but got 'new'. -
in my django template my input is reset when I send the search
What do I need to put in the value parameters of my inputs so that this information is forwarded to the fields? You can see what I'm talking about by entering the page and verify that when a search is made all my entries are restarted http://54.166.3.214:8000/results here is my html code in case it was necessary <input id="kword" name="kword" value="" class="input-form search-box" type="search" placeholder="Profesión, palabra clave o empresa" data-ac="//ac.careerjet.net/ns" data-target="#ac-s" data-target2="#s" data-as="1" data-lc="es_MX" data-mhd="10" data-mhm="3" > <input id="location" name="location" value="" class="input-form search-box" type="search" placeholder="Ubicacion" data-ac="//ac.careerjet.net/ns" data-target="#ac-s" data-target2="#s" data-as="1" data-lc="es_MX" data-mhd="10" data-mhm="3" > <select name="type" id="type"> <option value="Todos">Todos</option> <option value="Remoto">Remoto</option> <option value="Presencial">Presencial</option> </select> <select name="sort" id="sort"> <option value="relevance">Relevancia</option> <option value="date">Fecha</option> <option value="salary">Salario</option> </select> -
How to put all my cart items in an XML Django
Does anyone know why it's returning only 1 item? There are 2 items in my cart. Here is the "item_dict" variable: cart_items = CartItem.objects.filter(user=current_user) for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) quantity += cart_item.quantity item_dict = f""" <item> <id>{cart_item.product.id}</id>\r\n <description>{cart_item.product.name}</description>\r\n <quantity>{cart_item.quantity}</quantity>\r\n <amount>{cart_item.product.price}</amount>\r\n </item> """ return HttpResponse(item_dict) In my HttpResponse(item_dict) it is returning me only 1 item Meu objetivo é poder devolver todos os itens do meu carrinho no meu XML I don't know what I'm doing wrong. -
How to render each item of a dictionary in django
I am working on a django project whereby users upload resumes and they are parsed before the results are save in user profile. I have achieved the parsing part and saved the data bu the problem is rendering the data. An example is in the skills field whereby the data is stored as a dictionary and therefore I cannot display them one at a time. Here is my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='default.jpg', upload_to='profile_images') bio = models.TextField() resume = models.FileField('Upload Resumes', upload_to='resumes/', null=True, blank=True,default='resume.docx') name = models.CharField('Name', max_length=255, null=True, blank=True) email = models.CharField('Email', max_length=255, null=True, blank=True) mobile_number = models.CharField('Mobile Number', max_length=255, null=True, blank=True) education = models.CharField('Education', max_length=255, null=True, blank=True) skills = models.CharField('Skills', max_length=1000, null=True, blank=True) company_name = models.CharField('Company Name', max_length=1000, null=True, blank=True) college_name = models.CharField('College Name', max_length=1000, null=True, blank=True) designation = models.CharField('Designation', max_length=1000, null=True, blank=True) experience = models.CharField('Experience', max_length=1000, null=True, blank=True) total_experience = models.CharField('Total Experience (in Years)', max_length=1000, null=True, blank=True) whatsapp = models.URLField(null=True, blank=True) facebook = models.URLField(null=True, blank=True) twitter = models.URLField(null=True, blank=True) linkedin = models.URLField(null=True, blank=True) languages = models.CharField(max_length=1000, null=True, blank=True) profession = models.CharField(max_length=100, null=True, blank=True) nationality = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.user.username # resizing images def save(self, *args, **kwargs): super().save() img = … -
Two versions of the same Django app: 1 for administration, 1 for queries only
I have two Django apps that share a database and also a number of models. App 1 is used to administrate the data via the admin page. App 2 is used only to query the data and present the data. The apps are running on different servers. My current solution is to run the exact same code in models.py on both apps. However, I have not run makemigration/migrate on app2. This solution works but makes me bothered by the fact that I have the same code in two models.py but only have one operational table in the database. What is the correct way of dealing with this situation? -
'str' object has no attribute 'decode' on djangorestframework_simplejwt/backend.py
I am getting such error in my django rest framework project. Local working but live not working 'str' object has no attribute 'decode' I try pip install pyjwt==v1.7.1, pip install PyJWT==v1.7.1 , pip install PyJWT==1.7.1 and the problem persists. Didn't have any solution. The site is live as https. Urls.py from django.contrib import admin from django.urls import path, include from rest_framework_simplejwt import views as jwt_views from django.views.generic import TemplateView from rest_framework.authtoken import views from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='index.html'), name='index'), path('api/customers/',include('customer.api.urls')), path('api/user/',include('account.api.urls')), path('api/user/login', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/user/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] Please help me -
Django modelAdmin create or update exist instance in creation form
I need a creation form in my model admin, so that if a user exists with that phone(email) use it or create a new one because I have an inline form that needs an instance of the user model. In the fact, I have a model that foreign key to the User Model I create an inline form for it, and its shows in my admin for the User model. And when I try to create a new user with a different unique field it's created as well with the inline data for it but when trying to create with field with the same unique its throws an error to me that the user with this data exists but I want in that situation use existing user and add inline data to that -
Pulling images from a hosting company to django project
I have recently put my website into production. I am using a company to host my projects on their servers and everything is working perfectly apart from when I upload images. The uploading its self works and they are uploaded to the base/static/images/images folder correctly. But the website its self when uploading through django admin are trying to pull the images from the public_html/images/images folder. What would I need to change for either the images to be pulled from correct folder or images to be uploaded to correct folder. Below is my settings for my static files. STATIC_URL = 'static/' MEDIA_URL = 'images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') -
Filtering objects based on two attributes being the same
With regards to the below model, how could I filter through existing objects so that I find only objects where 'Name' contains a certain word, for example, "Green" but also where the vendor of the object also contains "Green"? I am of course referring to the value (assuming same type although in this example I am using char and text field). class Hat(models.Model): Name = models.CharField(max_length=255, unique = False) Size = models.IntegerField(choices=list(zip(range(1, 11), range(1, 11))), unique=False) Vendor = models.TextField(max_length=255, unique = False) List = [for Hat in Hat.objects.filter(Name__contain="Green")] -
I need to highlight the check text in color
When I start to check the words, I have what has come in green, and the error is red, and when I have an error, it does not highlight it in red, but only displays my error message. How can I make it highlight the error? view.py @login_required @permission_required("service.add_post") def create_post(req): form = PostForm() if req.method == "POST": form = PostForm(req.POST) if form.is_valid(): form.save() title = form.cleaned_data.get("title") if title != "POST": messages.error(req, f"Something went wrong") return redirect('index') # id = form.cleaned_data.get("pk") messages.success(req, f"Post {title} was created successfully") return redirect('index') return render(req, "create_post.html", {"form":form}) create_post.html {% extends "index.html" %} {% block content %} <h1>Create Post</h1> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-primary">Create New Post</button> {% endblock %} ``` Already changed a lot of things but nothing helped.[](https://i.stack.imgur.com/dbS3i.png) -
what is a python program to interchange first and last element of dictionary?
how may we interchange the positions of first and last element in a dictionary. I tried to use the swap function which did'nt work quite well for me, what can i use to achieve my desired result, please answer. -
Returning JsonResponse from a django rest-framework serializer
My question is how would I return a custom JsonResponse from a rest-framework serializer? I have a view with this code: # Send money to outside of Pearmonie class sendmoney_external(viewsets.ModelViewSet): # Database model queryset = User.objects.all() # Serializer - this performs the actions on the queried database entry serializer_class = SendMoneyExternalSerializer # What field in database model will be used to search lookup_field = 'username' My serializer is something like this: # Serializer for sending money to another Pearmonie user class SendMoneyExternalSerializer(serializers.ModelSerializer): # This is the function that runs for a PUT request def update(self, instance,validated_data): # Verifies the requesting user owns the database account if str(self.context['request'].user) != str(instance.username) and not str(self.context['request'].user) in instance.userprofile.banking_write: raise exceptions.PermissionDenied('You do not have permission to update') account_number = self.context['request'].data['to_account'] amount = self.context['request'].data['amount'] to_bank = self.context['request'].data['to_bank'] # Creates the order in the database from_user = BankingTransaction.objects.create( user = instance, date = timezone.now(), from_account_num = instance.userprofile.account_number, from_account_name = instance.userprofile.company, to_account = self.context['request'].data['to_account'], to_bank = to_bank, amount_transferred = amount, description = self.context['request'].data['description'], trans_reference = self.context['request'].data['trans_reference'], status = self.context['request'].data['status'], ) instance.userprofile.notification_count += 1 instance.userprofile.save() # Creates the notification for the supplier in the database from_notification = Notifications.objects.create( user=instance, date=timezone.now(), read=False, message=f'You have paid N{amount} to account number {account_number} … -
How to fix this django path without this prefix?
I made a simple blog and then i made a new app and copied all codes (changed to new apps) and i made url path. And all of them second app path doesn't work and it wants prefix... Where is my fault? Here is the github repo and also my codes here... https://github.com/eseymenler/firmas Ulus = folder name Ulusal = project name Ulusalb = First app Firma = Second app main project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("", include('ulusalb.urls')), path("firma/", include('firma.urls')), ] When i made this i have an error like this but when i make this from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("", include('ulusalb.urls')), path("1/firma/", include('firma.urls')), ] It works. Why this happen? I want url like this path("firma/", include('firma.urls')) How can i solve this? -
Django JSignature Templated Docs
I am utilizing Django 4.1.3, templated_docs, and Jsignature. I am hoping to be able to place the signature image generated by jsignature directly to the document. I have attempted almost every combination of utilizing Draw_signature, templated_docs {% image %}, and even {{form.media}} {{form.field}} noted in Jsignature. any insight here is helpful. from templated_docs import fill_template from templated_docs.http import FileResponse from django.http import HttpResponseNotFound from invoiceManager.models import Invoice from jsignature.utils import draw_signature def invoice_view(request, **kwargs): pk = kwargs.get('pk', None) if pk: # try: invoice = Invoice.objects.get(pk=pk) information = { 'repairDate': invoice.repair_date, 'claim': invoice.claim_authorization_number, 'customerName': invoice.customer.name, 'customerAddress': invoice.customer.address, 'customerCityStateZip': f'{invoice.customer.city} {invoice.customer.state.abbreviation}, {invoice.customer.zip_code}', 'customerPhone': invoice.customer.phone_number, 'insuranceName': invoice.insurance.name, 'policyNumber': f'policy Number: {invoice.policy_number}', 'VIN': f'VIN: {invoice.vehicle_information.vin}', 'YMM': f'{invoice.vehicle_information.year} {invoice.vehicle_information.make} {invoice.vehicle_information.model}', 'customerSignature': draw_signature(invoice.signature), 'technician': invoice.technician.name, 'location': invoice.business_location.name, 'submissionDate': invoice.invoice_submission_date, 'amount':invoice.invoice_amount, } repairLocations = {f'RL{x}':"Repair Made" for x in invoice.location_of_repairs.all().values_list('id', flat=True).order_by().distinct()} information.update(repairLocations) filename = fill_template( 'docs/base_invoice.odt', information, output_format=".pdf") visible_filename = 'invoice{}'.format(".pdf") return FileResponse(filename, visible_filename) -
How to add dynamically data in form through ajax in javascript or jquery?
i got data from db through ajax and try to add in forms input tags. When i add data in the form dynamically through Ajax. , the webpage got stuck and a black layer coming on the webpage, i could not able to anything tech stack:(Django/javascript/jquery) $.ajax({ url:url, method:"post", data:mydata, dataType:"json", success:function(data) { if(data.status==1) { let is_free=data.value['is_free']; console.log(typeof data.value['is_free']); document.getElementById("id_Lecture_Title").value=(data.value['title']); document.getElementById("lec_desc").value=(data.value['desc']); document.getElementById("free_preview_lec").checked=true; $("#add_lecture_model").modal("show"); } }, error:function(data) { alert("Something went wrong"); } }); enter image description here Help me to solve this problem>> -
How to validate Nested Serializer in Django Rest Framework
I have ReviewRatings and ReviewImages models in which ReviewImages is ForeignKey to ReviewRatings so that an user can upload single or multiple images along with reviews. I have overridden the create method for ReviewRatings in ReviewRatingSerializer and creates ReviewImages in it also. I Have ReviewImagesSerializer also. So My doubt is How do I validate the images am looping through before saving it. Is there anyway to call ReviewImagesSerializer in create method of ReviewRatingSerializer to validate the files? #Serializer.py class ReviewImagesSerializer(ModelSerializer): class Meta: model = ReviewImages fields = ["images"] class ReviewSerializer(ModelSerializer): user = SerializerMethodField() review_images = ReviewImagesSerializer(many=True, required=False) class Meta: model = ReviewRatings fields = [ "user", "rating", "review", "created_at", "updated_at", "review_images", ] def get_user(self, obj): return f"{obj.user.first_name} {obj.user.last_name}" def create(self, validated_data): review_images = self.context["images"] reviews = ReviewRatings.objects.create(**validated_data) for image in review_images: ReviewImages.objects.create(review=reviews, images=image) return reviews