Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get real password from Django rest framework ( JWT token ). For UserListView
I'm new to this topic, I want to implement the output of users and their real passwords for admin access. At the moment I have this code, it displays encrypted passwords. How can I make the password that the user entered during registration appear in the field? Thank you in advance. class UserListView(generics.ListAPIView): queryset = models.User.objects.all() serializer_class = serializers.UsersListSerializer class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(('email address'), unique=True) first_name = models.CharField(('first name'), max_length=30, blank=True) last_name = models.CharField(('last name'), max_length=30, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return str(self.email) def save(self, *args, **kwargs): super(User, self).save(*args, **kwargs) return self @property def token(self): return self._generate_jwt_token() def _generate_jwt_token(self): dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': dt.utcfromtimestamp(dt.timestamp()) }, settings.SECRET_KEY, algorithm='HS256') return token.decode('utf-8') class UserManager(BaseUserManager): def _create_user(self, first_name, last_name, email, password=None, is_active=True, is_staff=False, is_superuser=False): if not first_name: raise ValueError('First name should be set') if not last_name: raise ValueError('Last name should be set') if not email: raise ValueError('Email should be set') user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, is_active=is_active, is_staff=is_staff, is_superuser=is_superuser ) user.set_password(password) user.save(using=self._db) return user def create_user(self, first_name, last_name, email, password=None): user = self._create_user(first_name, last_name, email, password=password, is_staff=True) return … -
how do I make toasts push messages if there's any
So some of the toasts are working fine how it's supposed to except some "class-based toasts" aren't working, like the 'warning toast' and 'info toast'(sometimes). I want them to show up for a certain time and then make them disappear and all of them should work the same. I tried compiling the javascript code in Babel but still doesn't work, no clue what's causing the situation. Thnx for any help! Getting a console error as such "messages.js:4 Uncaught TypeError: Cannot read property 'style' of null at showToast (messages.js:4) at messages.js:17" let margin = 10; const showToast = (type) => { const toast = document.getElementById(`toast-${type}`); toast.style.display = 'block'; toast.style.marginBottom = `${margin}px`; margin += toast.clientHeight + 5; hideToast(toast); } const hideToast = (toast) => { setTimeout(() => { toast.style.display = 'none'; margin -= toast.clientHeight + 5; }, 2000); } showToast('success'); showToast('info'); showToast('warning'); showToast('error'); .success{ display: none; position: fixed; bottom: 0; margin-bottom: 10px; margin-left: 4%; font-family: Arial; padding: 15px; background-color: forestgreen; color: #FFFFFF; border-radius: 10px; text-align: center; z-index: 2; box-shadow: 0 0 20px rgba(0,0,0,0.3); } .info{ display: none; position: fixed; bottom: 0; margin-bottom: 10px; margin-left: 4%; font-family: Arial; padding: 15px; background-color: blue; color: #FFFFFF; border-radius: 10px; text-align: center; z-index: 2; box-shadow: 0 0 … -
Use `throttle_classes` for spyne application for set rate limit
I have used spyne library for my django rest framework application for incoming XML data. Now i want to implement throttle_classes for set rate limit in order to avoid heavy incoming request load on my server. I have tried this code to use permission_class in URL for spyne application, but it is not working. remove authentication and permission for specific url path url( r"^vapi/", (permission_classes([IsAuthenticated])(vapi_view.vapp)).as_view(application=vapi_view.vapp), ), This one is from django view which is working fine. url(r'^test/$', (permission_classes([IsAuthenticated])(algo_program_views.TestView)).as_view()), I have also tried to use that in Service Class as a decorator, which is also not working. class HelloWorldService(Service): @api_view(['POST']) @permission_classes([IsAuthenticated]) @rpc(Unicode, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, name, times): for i in range(times): yield 'Hello, %s' % name -
How to enable Forms in Django Rest Framework's Browsable API on production?
I'd like to set DEBUG = False in Django, while preserving full Django Rest Framework's Browsable API functionality. I'd like to preserve full functionality for whitelisted IP addresses only. This is how it looks like when DEBUG = True is set: DebugTrue Forms are displayed and working (Raw data and HTML form tabs) Extra actions and OPTIONS buttons are working JSON highlighting is active. I'd like to preserve this functionality on production (for whitelisted IP addresses only). As soon as I set DEBUG to False, I lose it. This is how it looks like when DEBUG = False is set: DebugFalse No forms are displayed Extra actions and OPTIONS buttons are not working JSON highlighting isn't active How to force activate these DRF features while leaving Django in DEBUG = False mode? I'd like to have these features enabled for whitelisted IP addresses. How to achieve this? Thank you! -
Django: detect what models was used in query
TL;DR: Need to know what models was used in queries executed in some block of code I have self-made caching system that has ability to automatically drop cache when specific models get saved. The usage is (example in Django Rest framework API viewset): class UsersViewSet(ListModelMixin) model = User queryset = User.objects # Here cache decorator goes @cache_view(models_to_drop_cache=[User, UserProfile, UserPhone]) def list(self, request, *args, **kwargs): # calling the real viewset method return super().list(request, *args, **kwargs) Now when any of models [User, UserProfile, UserPhone] change, cache on that view would be dropped (it's achieved by using signal receiver of model save signal). The problem is: sometimes not all models got written to the list (somebody forgot to) and cache not being dropped when it should. I want to add some debug argument to method cache_view so in debug mode decorator gather information about models that was used in the decorated method and output the list. I've tried to look for model signals but didn't succeeded. It seems like I need to monkey-patch Django's query builder to check for table names in resulting SQL code that got executed. Maybe there is more straightforward method? -
I have a select menu and I want a query action when the user chooses an option value. I am using Django
<div class="row"> <div class="input-field col s2 offset-s1"> <select> <option value="" disabled selected>Options:</option> <option value="1">Display all</option> <option value="2">Sort by data</option> <option value="3">Sort by price</option> </select> </div> </div> How can I write the template code {% code %} and the views functions for making queries which depend by the select menu? -
Use HTML entities in django template
I want to use HTML entities in my Django template. I know that I can do something like this <th>0&ge;a&lt;10</th> and it will work correctly. But I send to my template list with that which looks like list_of_ranges = ['Name', 'Type', 'a<1', '5<a<10' .......] So in a template in for loop, I want to use &ge, &lt, and others for values that contain '>', '>=' and others. I tried to use it in the list before sending it to the template, but it's not working correctly. See below. list_of_ranges = ['Name', 'Type', 'a&lt;<1' .......] and in template fo like this {{list_of_ranges.2}} Result: a&lt;<1 Could you help, how can I resolve it? -
Can a django template call another template in Modal window?
My requirement is to a django template from another django template. the second template would open in a Modal window instead of taking me to a different page. Parent View : Basic Child View : Cancellation Can the child view template be kicked off through a modal? I am new to this so I need a sample code to achieve this. -
What is the best way to store chat Messages in Django for better performance
Currently, I am using default SQLite DB to store messages, as I am using channels... I update the Database at every send and receive a signal from WebSocket. but it would be too expensive when traffic will be large as at every send and receive I interact with Django ORM is there any other efficient way? class Room(models.Model): name = models.CharField(max_length=150) group = models.CharField(max_length=150,null=True) def __str__(self): return self.name class Message(models.Model): room = models.ForeignKey('Room',null=False,blank=False,on_delete=models.CASCADE) sender = models.ForeignKey(User,on_delete=models.CASCADE,null=True) message = models.TextField() def __str__(self): return self.message -
Django model class error when adding a new class into models
I have the following code: models.py from django.db import models class Title(models.Model): title_name = models.CharField(max_length=200) category = models.CharField(max_length= 30) class Tags(models.Model): tag1 = models.CharField(max_length=15) tag2 = models.CharField(max_length=15) tag3 = models.CharField(max_length=15) tag4 = models.CharField(max_length=15) class Videos: primo: str views.py from django.shortcuts import render, HttpResponse from django.http import HttpResponse from .models import Videos def home(request): vid = Videos() vid.primo = 'https://www.youtube.com/' return render(request, 'index.html', {'vid': vid}) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] When I run the server I get: RuntimeError: Model class home.models.Title doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Everything was working before adding class Videos() and just using: def home(request): return render(request, 'index.html') I don't understand what I should specify in the INSTALLED_APPS as I just added a new def to render a video URL inside my HTML. Why I get this error? Thanks! -
showing "Did not find any relations." though I have many tables while working in google app engine
Google App Engine Cloud Shell Terminal: SSL connection() Type "help" for help. postgres=> \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges ---------------+-------------------+----------+------------+------------+----------------------------------------- cloudsqladmin | cloudsqladmin | UTF8 | en_US.UTF8 | en_US.UTF8 | daysdb | cloudsqlsuperuser | UTF8 | en_US.UTF8 | en_US.UTF8 | postgres | cloudsqlsuperuser | UTF8 | en_US.UTF8 | en_US.UTF8 | template0 | cloudsqladmin | UTF8 | en_US.UTF8 | en_US.UTF8 | =c/cloudsqladmin + | | | | | cloudsqladmin=CTc/cloudsqladmin template1 | cloudsqlsuperuser | UTF8 | en_US.UTF8 | en_US.UTF8 | =c/cloudsqlsuperuser + | | | | | cloudsqlsuperuser=CTc/cloudsqlsuperuser (5 rows) postgres=> \c daysdb Password: psql (13.1 (Debian 13.1-1.pgdg100+1), server 12.4) SSL connection() You are now connected to database "daysdb" as user "postgres". daysdb=> \dt Did not find any relations. I don't know where I am mistaking. Is there any method to give permission to view tables or something else... and when I directly run my app using gcloud app deploy command it shows error: LINE 1: ..._header"."mob_img", "days_header"."welcome" FROM "days_hea... which means my tables are not migrated. Please help me! -
How to check if a file is csv or not?
I have a django views function that converts csv into another delimiter format. But, I just want to convert csv file and reject other files. def index(request): csv_form = '' if request.method == 'POST': csv_form = CsvForm(request.POST, request.FILES) if csv_form.is_valid(): csv_file = TextIOWrapper(request.FILES['csv_file'].file, encoding='ascii', errors='replace') #other actions I cannot use the below code because this works with only binary files, but the csv module wants to have text-mode files instead. Any alternatives to proceed with only csv files. if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') -
Is it possible to substitute an image file for a user selected upload in Django?
I have a model that has an image field with the usual create and edit pages in my Django app. However I need a copy function for the user with the functionality to copy the image in addition to some of the other fields. Now it would be possible to copy the image entirely on the server side, however this gets messy with having to delete the image if the user cancels the copy, or if the user decides to replace the copied image with a new upload. So I was wondering if there was a different way, where the image to be copied is substituted in for the usual upload? Almost like as if the image file to be copied is temporarily downloaded to the client before they interact with the copy page. Current model code for reference: import os from uuid import uuid4 @deconstructible class UploadToPathAndRename(object): def __init__(self, path): self.sub_path = path def __call__(self, instance, filename): ext = filename.split('.')[-1] filename = '{}.{}'.format(uuid4().hex, ext) return os.path.join(self.sub_path, filename) class Foo(models.Model): name = models.CharField(db_index=True, max_length=60) image = models.ImageField(upload_to=UploadToPathAndRename( 'default'), blank=True) -
Multiplying an integer and a decimal in a Django model using model expressions
I am a Django and in one of my projects, I made this model: class Piece(models.Model): order = models.ForeignKey(Order,on_delete=models.CASCADE) coil = models.ForeignKey(Cut_Material ,on_delete=models.CASCADE) piece_length = models.DecimalField(max_digits=4, decimal_places=2) prime_pieces = models.IntegerField() reject_pieces = models.IntegerField() def __str__(self): return (str(self.piece_length)) class Meta: ordering = ["-order","piece_length"] I want to be able to multiply piece_length with prime_pieces to get running meters and here is my solution: Piece.objects.annotate(running_meters = (F('reject_pieces') * F('prime_pieces')), output_field=FloatField()) I get this error: TypeError: QuerySet.aggregate() received non-expression(s): <django.db.models.fields.FloatField>. Can anyone help me with a solution, please? -
Django "Table 'myproject.auth_user' doesn't exist"
I have a bunch of tables generated in different apps in my app. Because of some issue I had to drop all the tables and create them from the scratch. one app is related for profile. One I run these commands I get an error as below: python manage.py makemigrations Operations to perform: Apply all migrations: admin, myapp, auth, cities, contenttypes, sessions, users and by this: python manage.py migrate I get: Running migrations: No migrations to apply. After all I don't see the dropped tables between database tables and consciously after run server get errors which "Table 'myproject.auth_user' doesn't exist". I also tried to remove the files in the migrations folder but does not work. Most probably these files are stored somewhere which I don't find!! Do you have any suggestion? -
How to change id field from uuid type to integer in a django model
My model as exists it has the below format: class MyModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) How it is possible to turn id to be of integer type , auto incremented and primary key? As the default behaviour of db when someone does not define at all the id field Deleting id field and running : python manage.py makemigrations python manage.py migrate raises an error of : django.db.utils.ProgrammingError: cannot cast type uuid to integer LINE 1: ...MyModel" ALTER COLUMN "id" TYPE integer USING "id"::integer Deleting the id field as it is and create again the id field as below: id = models.AutoField(primary_key=True, unique=True) and running again (now with two migration files) python manage.py makemigrations python manage.py migrate raises the same error as before. Finally, changing the data type of the id field from uuid to integer directly from the db is not a good option and may cause deployment issues. How can I make this transition and keep my db working properly? -
How to preserve key order in a Django JSONField
I am having a hard time preserving the order of keys in a JSON object stored in a Django JSONField. I have tried using a custom encoder and decoder as per the docs, but the JSON object keeps re-ordeing itself: >>>from models import MyModel >>>my_dict = {"c": 3, "b": 2, "a": 1} >>>my_model = MyModel() >>>my_model.my_field = my_dict >>>my_model.save() >>>my_model.refresh_from_db() >>>my_model.my_field OrderedDict([('a',1), ('b', 2), ('c', 3)]) I would have expected it to return OrderedDict([('c',3), ('b', 2), ('a', 1)]). Here is what I've tried so far: models.py: import collections import json from django.db import models class OrderedEncoder(json.JSONEncoder): def encode(self, o): if isinstance(o, collections.OrderedDict): encoded_objs = [ f"{self.encode(k)}: {self.encode(v)}" for k, v in o.items() ] return f"{{{','.join(encoded_objs)}}}" else: return super().encode(o) class OrderedDecoder(json.JSONDecoder): def __init__(self, *args, **kwargs): default_kwargs = { "object_pairs_hook": collections.OrderedDict } default_kwargs.update(kwargs) super().__init__(*args, **default_kwargs) class MyModel(models.Model): my_field = models.JSONField(encoder=OrderedEncoder, decoder=OrderedDecoder) Any ideas? -
Django - Modifies models field arguments
I am not sure how to make a change in my code. I have 2 models that have the same fields and I want to respect the DRY principle and make just one model with a field "type" and to filter the objects by the type field, the problem is that these models on the category field have diferent categories choices and I'm wondering if I can add a function that will decide depending on the model type which choices to attribute. the models: class Income(models.Model): class IncomeCategory(models.TextChoices): SALARY = 'SLRY', _('Salary') PROFIT = 'PRFT', _('Profit') INTEREST = 'ITRT', _('Interest') DIVIDENT = 'DVDT', _('Divident') RENTAL = 'RNTL', _('Rental') CAPITAL = 'CPTL', _('Capital') ROYALTY = 'RYLT', _('Royalty') GIFT = 'GIFT', _('Gift') OTHERS = 'OTRS', _('Others') user = models.ForeignKey(User, on_delete=models.CASCADE), name = models.ChardField(_('Income Name')max_length=50), amount = models.DecimalField(_('Income Amount'), max_digits=10, decimal_places=3) category = models.CharField(_('Category'), max_length=4, choices=IncomeCategory.choices, default=IncomeCategory.SALARY) recurrent = models.BooleanField(default=False) created_date = models.DateTimeField(_('Created Date')auto_now_add=True) updated_date = models.DateTimeField(_('Updated Date')auto_add=True) def __str__(self): return f'{self.user.username} - {self.name}' class Spending(models.Model): class SpendinCategory(models.TextChoices): UTILITIES = 'UTLT', _('Utilities') RENT = 'RENT', _('Rent') INVOICES = 'INVC', _('Invoices') SHOPPING = 'SHPG', _('Shopping') FOOD = 'FOOD', _('Food') EDUCATION = 'EDCN', _('Education') FUN = 'FUN', _('Fun') INSETMENT = 'INVT', _('Investment') OTHERS = 'OTRS', … -
CoreAPI to OpenAPI schema generation transition (Django REST Framework)
Django REST Framework 3.10 (September 2019) introduced OpenAPI based schema generation instead of CoreAPI, which has been deprecated (see release notes here). I'm creating an API using the current actual 3.12.0 version (13th October 2020). This change introduces regressions: Redundant Operation IDs, A "workaround" is required to get schema using coreapi cli command (see here), Mandatory parameters defined in serializer are not extracted in schema generation, thus I cannot use the coreapi cli command. The last point is the really problematic one. I can easily switch from the OpenAPI to the (deprecated) CoreAPI AutoSchema class changing the url parameter in get_schema_view function and adding this in settings.py: REST_FRAMEWORK = { # [...] 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', } Example Below is an example using both schema classes. models.py: class Operator(models.Model): code = models.IntegerField(unique=True, blank=False, null=False) first_name = models.CharField(max_length=45, unique=False, blank=False, null=False) last_name = models.CharField(max_length=45, unique=False, blank=False, null=False) serializers.py: class OperatorSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Operator fields = ['url', 'id', 'code', 'first_name', 'last_name'] views.py: class OperatorViewSet(viewsets.ModelViewSet): queryset = Operator.objects.all() serializer_class = OperatorSerializer permission_classes = [permissions.IsAuthenticated] Using Core API # No workaround coreapi get http://127.0.0.1:8000/api/openapi # [...] operators: { list([page]) create(code, first_name, last_name) read(id) update(id, code, first_name, last_name) partial_update(id, [code], [first_name], [last_name]) delete(id) } # … -
DJANGO - SWAGGER - Why serielizer was put into format of RESPONSE
Obviously, I am using Django to code, and want to document by drf_yasg lib its actually Swagger but the new version (I supposed so) Everything is fine, excepts that swagger automatically assume my OUTPUT or RESPONSE of my API is the Serielizers. As the image below Here is my Serializers.py class Serielizer_RecalculateDeliveryPromise(serializers.ModelSerializer): service_type = serializers.CharField(max_length = 68, min_length = 6, write_only= True) package_type = serializers.CharField(max_length = 68, min_length = 6, write_only= True) origin_handover_point = serializers.CharField(max_length = 68, min_length = 6, write_only= True) destination_handover_point = serializers.CharField(max_length = 68, min_length = 6, write_only= True) class Meta: model = Input_RecalculateDeliveryPromise fields = ['service_type', 'package_type', 'origin_handover_point', 'destination_handover_point'] Here is my models.py class Input_RecalculateDeliveryPromise(models.Model): service_type = models.CharField(max_length = 255, db_index = True, default = ) package_type = models.CharField(max_length = 255, db_index = True) origin_handover_point = models.CharField(max_length = 255, db_index = True) destination_handover_point = models.CharField(max_length = 255, db_index = True) Here is my views.py class recalculate_delivery_promise(generics.GenericAPIView): serializer_class = Serielizer_RecalculateDeliveryPromise def post(self, request): request_data = json.loads(request.body) serializer = self.serializer_class(data=request_data) serializer.is_valid(raise_exception=True) service_type = request_data["service_type"] package_type = request_data['package_type'] origin_hp = request_data['origin_handover_point'] destination_hp = request_data['destination_handover_point'] #some calculation return JsonResponse({'_price':25000}) #just an example Here is my urls.py in project from django.contrib import admin from django.urls import path, include from rest_framework import … -
Django test | DETAIL: Key (id)=(1) is still referenced from table "validation_loyaltydocumentvalidation"
I work on Python 3.7 and the project migrated recently from Django 1.11 to Django 2.0.9. When i run ./manage.py test I encounter the following error : django.db.utils.IntegrityError: update or delete on table "pizzeria_loyaltydocument" violates foreign key constraint "validation_docum_document1_id_94a0a84b_fk_pizzeria" on table "validation_loyaltydocumentvalidation" DETAIL: Key (id)=(1) is still referenced from table "validation_loyaltydocumentvalidation". It seems that issue come from my test setUp() : class PizzaTestCase(TestCase): def setUp(self): self.customer, self.record, self.best_pizza = create_pizzeria_context() # here documents are created using LoyaltyDocument.objects.create() create_loyalty_documents(self.customer) LoyaltyDocument.objects.filter( customer=self.customer, kind='loyalty' ).delete() self.loyalty_document = ProfileDocument.objects.create( customer=self.customer, kind='loyalty' ) def create_loyalty_documents(customer): loyalty_document = ProfileDocument.objects.create( kind="loyalty", customer=customer, ... As mentioned in the comment, a loyalty document with id = 1 is already created within create_loyalty_documents() and if a comment out that part i get no such error but most of my tests fails as i need that document deleted. Why such error appears as it was not the case while on Django 1.11 ? What am I doing wrong / How to overcome that error ? Thanks -
I want to remove some characters from a string in js
I am making an Website with Django (Python Framework). I am passing string like this : Products you ordered: {"pr7":[4,"Mi Phone 8 GB RAM, 128GB ROM",7000],"pr8":[5,"Usha Mixer Grinder (White)",1244],"pr9":[4,"iBall 10000 MAh power bank (Black)",1455]} from my models.py to views.py to my html template but I don't want to my string to be like this my string is : Products you ordered: {"pr7":[4,"Mi Phone 8 GB RAM, 128GB ROM",7000],"pr8":[5,"Usha Mixer Grinder (White)",1244],"pr9":[4,"iBall 10000 MAh power bank (Black)",1455]} I want my string to be like : Products you ordered: Mi Phone 8 GB RAM 128GB ROM,Usha Mixer Grinder (White),iBall 10000 Mah power bank (Black) -
Django query: Order by the number of the overlapped elements of array with a list variable
I have an ArrayField in my postgresql db table. I would like to order my queryset by the number of the overlapped elements with a fixed list variable. I couldn't find a solution using ORM. Then I apply this raw query stated in https://stackoverflow.com/a/51612751: SELECT i.food_list, x.ct FROM main_recipes i , LATERAL ( SELECT count(*) AS ct FROM unnest(i.food_list) uid WHERE uid = ANY('{water,banana}') ) x ORDER BY x.ct desc; The problem now is that I cannot include this solution to my queryset in ORM: qset = Recipes.objects.annotate(val=RawSQL(""" SELECT x.ct FROM main_recipes i , LATERAL ( SELECT count(*) AS ct FROM unnest(i.food_list) uid WHERE uid = ANY(%s) ) x """, (includeList,))).order_by('val') This gives the error: django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression I much appreciate your any kind of solution ORM or row. -
Django how to get db_column from object_list.values()
I have the following model. class TSample(models.Model): foo1_id = models.DecimalField(max_digits=8, decimal_places=2, db_column='foo1_id__c') foo2_f = models.DateTimeField(null=True) I have used a paginator and read data inside a loop as follows. query = self.model.objects.filter(...).order_by('updated_at') paginator = Paginator(query, self.batch_size) for i in paginator: data = list(i.object_list.values()) encoded_data = json.loads(json.dumps(data, cls=DjangoJSONEncoder)) print(encoded_data) The data I get does not have the db_column I have mentioned in the model. Instead the field name in the model. [{'foo1_id': 1.2, 'foo2_f': '2020-12-07T07:31:25Z'}] Expected data is, [{'foo1_id__c': 1.2, 'foo2_f': '2020-12-07T07:31:25Z'}] How can I get the expected result with the db_column name -
MultiValueDictKeyError in Django Project
View.py if req.method == 'POST': df = DocumentForm.objects.filter(document_id=id) logging.info('LOG: I am here') if df.exists(): for d in df: description = req.POST['{}'.format(d.description, False)] displayName = req.POST['{}'.format(d.displayName, False)] df.update(displayName=displayName, description=description) return redirect('/adboard/upd') HTML File <form class="needs-validation" action="{{id}}" method="POST" enctype="multipart/form-data" novalidate> {% csrf_token %} <div class="row mt-3 mb-3"></div> {% if messages %} <div class="alert alert-danger" role="alert"> {% for message in messages %} {{ message }} {% endfor %} </div> {% endif %} {% for df in data %} <div class="form-group"> <small class="text-muted bold-label m-lower">&#123;{{df.field}}&#125;</small> <label for="validationCustom01">{{df.displayName}}</label> <input type="text" class="form-control" id="validationCustom01" name="{{df.displayName}}" value="{{df.displayName}}" placeholder="Enter Display Name"> <label for="validationCustom01">{{df.description}}</label> <input type="text" class="form-control" id="validationCustom01" name="{{df.description}}" value="{{df.description}}" placeholder="Enter description"> <div class="invalid-feedback"> Please enter required fileds. </div> <!-- <div class="valid-feedback"> Looks good! </div> --> </div> {% endfor %} <button type="submit" class="btn btn-primary btn-red btn-block">SAVE</button> </form> What I am trying to achieve is. Pass a variable form to the user to fill And I get the result. I can't tell what the input id/name would be because it's a variable. But I am finding it difficult getting the value from the view.py file.