Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i enable the agent instance to be available in my agent update form when the agent is connected to the user through a one to one field
models.py class Auto(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE) def __str__(self): return self.user.username class User(AbstractUser): pass # To categorize users either as an organisor or as an agent is_organisor = models.BooleanField(default=True) is_agent = models.BooleanField(default=False) agent_details = models.TextField(null = True, blank=True) class Agent(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE) organisation = models.ForeignKey("Auto", on_delete=models.CASCADE) def __str__(self): return self.user.username views.py class Agent_update(ManualLoginRequiredMixin, generic.UpdateView): template_name = 'agent-update.html' form_class = AgentUpdateForm queryset = Agent.objects.all() context_object_name = 'agents' def get_success_url(self): return reverse('reverse url') agent-update.html <form method="post"> {% csrf_token %} {{form|crispy}} <button>Update Agent</button> </form> After running the server the form works but dosen't display the instance of the particular agent being updated. I feel it is because the Agent model is connected to the User model. Any help would be appreciated -
django_celery_beat task one_off=True does not start
django_celery_beat task one_off=True не стартует Я создаю объект задачи celery_beat, но она не срабатывает по времени ClockedSchedule models.py clocked, _ = ClockedSchedule.objects.get_or_create( clocked_time=datetime.utcnow() + timedelta(minutes=1) ) PeriodicTask.objects.create( clocked=clocked, one_off=True, name=f'CERTIFICATE SMS TASK {self.id}', task='apps.discounts.tasks.send_certificate_message', args=json.dumps([self.id]), start_time=datetime.utcnow() + timedelta(minutes=1), expires=datetime.utcnow() + timedelta(days=1) ) tasks.py @app.task(bind=True) def send_certificate_message(self, certificate_id) -> None: """ Task is not running """ ... Help, what does it take to run a celery_beat task once by ClockedSchedule? -
How to search inside string and modify
Python newbie here. A script I am using has a method s_lower(value) to lowercase every text posted by user. Also there are some special syntax such as [spec sometexthere]. I want to not lowercase if the text has a special syntax (in this case [spec ...] but lowercase all other text. For example, THIS IS A TEXT [spec CAPITAL] EXAMPLE This should be rendered as this is a text [spec CAPITAL] example Unfortunately, I wasn't be able to see/write logs (maybe because of docker), so I am kind of blind but hopefully this code block below will give you some hint to guide me WEBURL = r"(?:(?:(?:(?:https?):)\/\/)(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[?") # actually much more longer def s_lower(value): url_nc = re.compile(f"({WEBURL})") # Links should not be lowered if url_nc.search(value): substrings = url_nc.split(value) for idx, substr in enumerate(substrings): if not url_nc.match(substr): substrings[idx] = i18n_lower(substr) return "".join(substrings) return value.lower() I want something like if the value has "[spec" then find the index number of "[" and "]", then do not lowercase the text between those parantheses but lowercase all other text. -
Please is there anything i'm doing wrongly, filtered base on datetime, empty QuerySet
i got an empty QuerySet<[]>, i'd like to confirm if my models filtered are working before proceeding but seems the queryset from SubscribeEmailModel filtered from topic__startdate coming out as empty query here is my models.py class Lesson(models.Model): name = models.CharField(max_length=234) startdate = models.DateField(auto_now=True) class SubscribeEmailModel(models.Model): topic = models.ForeignKey(Lesson) please here is my views.py class AutoSendNotification(ListView): subscriber =SubscribeEmailModel.objects.filter(topic__startdate=datetime.datetime.today(), sent_mail=False) print(subscriber) model = SubscribeEmailModel context_object_name = 'subscriber' template_name = 'superadmin/email/auto-send.html' -
Dockerizing Django with PostgreSQL. FATAL: password authentication failed for user "postgres"
I am trying to dockerize my Django application with its PostgreSQL database. I have the following config files: docker-compose.yml version: '3' services: web: container_name: web build: context: . dockerfile: Dockerfile env_file: - csgo.env environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - '8000:8000' volumes: - .:/code depends_on: - postgres_db postgres_db: container_name: postgres_db image: postgres:13 env_file: - csgo.env environment: - POSTGRES_DB='postgres' - POSTGRES_NAME='postgres' - POSTGRES_USER='postgres' - POSTGRES_PASSWORD='postgres' - POSTGRES_HOST='postgres_db' - POSTGRES_PORT='5432' ports: - '5432:5432' csgo.env POSTGRES_DB='postgres' POSTGRES_NAME='postgres' POSTGRES_USER='postgres' POSTGRES_PASSWORD='postgres' POSTGRES_HOST='postgres_db' POSTGRES_PORT='5432' settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'postgres_db', 'PORT': '5432', } } I get the most typical error: web | File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect web | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web | django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" web | What is the problem? What did I miss? Why this error occurs, if everything appear working fine? Note: I know this kind of question is popular on the Internet. But no one of them has answer to my question. Because my question is probably about mistake I have made (or a type) which I can't figure out for a whole day. Please help! -
How to render json data in Python Django App
I am new to Python . I am trying to create a webapp from Django which will read data from Excel file and then it will show that data on webpage in a form of dropdown . This is the structure of my web app which is I am creating I have also created a python script which is parsing the excel data and returning the json data import pandas import json # Read excel document excel_data_df = pandas.read_excel('Test-Data.xlsx', sheet_name='Sheet1') # Convert excel to string # (define orientation of document in this case from up to down) thisisjson = excel_data_df.to_json(orient='records') # Print out the result print('Excel Sheet to JSON:\n', thisisjson) thisisjson_dict = json.loads(thisisjson) with open('data.json', 'w') as json_file: json.dump(thisisjson_dict, json_file) This is output of this script [{"Name":"Jan","Month":1},{"Name":"Feb","Month":2},{"Name":"March","Month":3},{"Name":"April","Month":4},{"Name":"May","Month":5},{"Name":"June","Month":6},{"Name":"July","Month":7},{"Name":"August","Month":8},{"Name":"Sep","Month":9},{"Name":"October","Month":10},{"Name":"November","Month":11},{"Name":"December","Month":12}] Now where I am stuck is how we can integrate this in my webapp and how we can use this Json data to create a dropdown list on my webpage. -
Best practice to use django db connection in network call
I have two Django projects with DRF and have some Rest API's I want to use db connection of one Django project to another so i need to pass db connection/credentials over api network. I know we can get connection object using following from django.db import connections db_conn = connections['default'] and what am thinking is 1- to pass above db_conn in an api call as parameter to second project api but when am getting on other side its showing as string not as db connection object. 2- Another option is to pass credentials and create connection using sql alchemy in second project. So what is the best approach in above two scenarios?. Also it would be great if you can answer how to pass db connection object in api params as object not string -
How to apply a filter for each row of the same queryset on Django
I have the a model Product which has a relation with itself using the key "parent". This way, to get the parent of a product i just do product.parent and if i want the children of a product i do product.product_set.all(). What i want to do is to do an annotate on a queryset of parent products and sum the stock of each product with the stock of its children. Something similar to this: qs = Product.objects.filter(is_parent=True) qs = qs.annotate(stock_sum=Sum(Product.objects.filter(parent_id=F('id')).values_list['stock'])) Is this possible? Will it result in many queries or django know a way of handling this with a few joins? -
How do I get signals.py executed in this django environment?
I'm trying to run the following signals.py from .models import Sale from django.db.models.signals import m2m_changed from django.dispatch import receiver print("running") @receiver(m2m_changed, sender=Sale.positions.through) def calculate_total_price(sender, instance, action, **kwargs): print('action', action) print("running2") total_price = 0 print("running3") if action == 'post_add' or action == 'post_remove': print("running4") for item in instance.get_positions(): total_price += item.price print("running5") instance.total_price = total_price instance.save() apps.py already signals in VSCode that signals is not used from django.apps import AppConfig class SalesConfig(AppConfig): #default_auto_field = 'django.db.models.BigAutoField' name = 'sales' def ready(self): import sales.signals and then the init.py file default_app_config = 'sales.apps.SalesConfig' For completeness I'll add the models.py from django.db import models from products.models import Product from customers.models import Customer from profiles.models import Profile from django.utils import timezone from .utils import generate_code # Create your models here. class Position(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() price = models.FloatField(blank=True) created = models.DateTimeField(blank=True) def save(self, *args, **kwargs): self.price = self.product.price * self.quantity return super().save(*args, **kwargs) def __str__(self): return f"id: {self.id}, product: {self.product.name}, quantity: {self.quantity}" class Sale(models.Model): transaction_id = models.CharField(max_length=12, blank=True) positions = models.ManyToManyField(Position) total_price = models.FloatField(blank=True, null=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) salesman = models.ForeignKey(Profile, on_delete=models.CASCADE) created = models.DateTimeField(blank=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return f"Sales for the amount of ${self.total_price}" def save(self, *args, **kwargs): … -
Django Query across multiple models
So I am looking for some help (and hopefully and explanation) of how I access data across my multiple models because this one has left me completely snookered. I have a system for the sale of events (events model) now these events have multiple products(products model) and variable prices dependant on when you book (prices model), this part is working fine. Where I am struggling is there are also bundles of products (bundles table) which contain multiple products, and I need to get their attached prices. Now I have a list of bundles attached to the products being viewed but am struggling to query the ORM and get a full record - <Products (multiple)> - . I'm not completely new at this but it has left my completely stumped so any help would be greatly received. I have attached a sketch of the DB to help visualise. Thanks -
django.db.utils.OperationalError: no such table: django_site_id_seq
I got this error when running command python manage.py test for testing purpose. I tried after delete my pycache and migration files then run the python manage.py makemigrations and python manage.py migrate again as well. But still got the same error... Here is my test.py from rest_framework.test import APITestCase from django.urls import reverse from rest_framework import status # Create your tests here. class UserTest(APITestCase): def setUp(self): register_url = reverse('user:register') data = { "username":"Tester", "email":"tester@gmail.com", "password":"tester123", "mobile_number":"03322917356" } self.client.post(register_url, data, format='json') def test_user_can_register(self): register_url = reverse('user:register') data = { "username":"Tester1", "email":"tester1@gmail.com", "password":"tester123", "mobile_number":"03322911356" } response = self.clent.post(register_url , data , format='json') self.assertEqual(response.status_code ,status.HTTP_201_CREATED) -
OnSubmit function not working for an input type= 'submit'
I am making a quiz app using django and it's my first ever work using django Everything else is working fine instead of one thing which is whenever i press the button to submit the answer, page simply reloads. Here's my html code: <section> <div id = "results"></div> <form name = "quizForm" onsubmit = "return submitAnswers(answers = [{% for q in questions%}'{{ q.answer }}',{% endfor %}])"> {% for q in questions %} <h3> {{ q.id }}. {{ q.question }}</h3> .......... {% endfor %} <input type = "submit" value = "Submit Answer"> </form> <br><br> </section> Here's the js code relevance to the button: function submitAnswers(answers) { var total = answers.length; var score = 0; var choice = [] //dynamic method to get selected option for (var i = 1; i <= total; i++) { choice[i] = document.forms["quizForm"]["q" + i].value; } //dynamic method 1 for checking answer for (i = 1; i <= total; i++) { if (choice[i] == answers[i - 1]) { score++; } } //Display Result var results = document.getElementById('results'); results.innerHTML = "<h3>You scored <span>" + score + "</span> out of <span>" + total + "</span></h3>" alert("You scored " + score + " out of " + total); return false; … -
How to connect to Django Dramatiq Pg
I am using this package to connect with dramatiq queue on an EC2 instance. Although, I am able to connect to RDS with the same username/password using SSH Tunnel but it gives an authentication error when I try to connect with dramatiq pg. I am making a connection string as postgres://username:password@db-rds-link/db-name -
Multiple StreamBuilder using same data source
Directly connecting to websocket using Streambuilder works seamlessly but I tried to make the stream part of the provider so that I can access the stream data in multiple widgets without encountering the "Bad State: Stream has already been listened to". Is this a best way of handling multistreaming of data, if not what are my options? Websocket server is part of Django Code for provider is mentioned below late final WebSocketChannel _fpdSockets; Map _webSocketMessages = {}; Map get webSocketMessages { return _webSocketMessages; } WebSocketStreamProvider() : _fpdSockets = IOWebSocketChannel.connect( Uri.parse('ws://127.0.0.1:8000/ws/socket-server/'), ); Stream<Map<String, dynamic>> get dataStream => _fpdSockets.stream .asBroadcastStream() .map<Map<String, dynamic>>((value) => (jsonDecode(value))); void sendDataToServer(dataToServer) { print("Sending Data"); _fpdSockets.sink.add( jsonEncode(dataToServer), ); } void closeConnection() { _fpdSockets.sink.close(); } handleMessages(data) { print(data); _webSocketMessages = data; // notifyListeners(); } } -
ModuleNotFoundError: No module named 'students.urls.py'; 'students.urls' is not a package
i am just a beginner in python learning from tutorials i can't just run the server, i followed the same steps mentioned in that tutorial but its showing me this error, i searched for some possible answers on stack overflow but couldn't find any answer that could resolve my issue, hopeless what to do with this, my directory structure is as in python console in pycharm its showing me this error Error:Cannot run program "C:\Users\Dell\PycharmProjects\webProject\venv\Scripts\python.exe" (in directory "C:\Users\Dell\Desktop\mydjangoproject"): CreateProcess error=2, The system cannot find the file specified in pycharm terminal its showing me this error > res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\Dell\Desktop\mydjangoproject\mydjangoproject\urls.py", line 7, in <module> path('mydjangoproject', include('students.urls.py')), File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\conf.py", line 38, in include urlconf_module = import_module(urlconf_module) … -
Box SDK client as_user request requires higher privileges than provided by the access token
I have this code in my Django project: # implememtation module_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) # get current directory box_config_path = os.path.join(module_dir, 'py_scripts/transactapi_funded_trades/config.json') # the config json downloaded config = JWTAuth.from_settings_file(box_config_path) #creating a config via the json file client = Client(config) #creating a client via config user_to_impersonate = client.user(user_id='8********6') #iget main user user_client = client.as_user(user_to_impersonate) #impersonate main user The above code is what I use to transfer the user from the service account created by Box to the main account user with ID 8********6. No error is thrown so far, but when I try to implement the actual logic to retrieve the files, I get this: [2022-09-13 02:50:26,146: INFO/MainProcess] GET https://api.box.com/2.0/folders/0/items {'headers': {'As-User': '8********6', 'Authorization': '---LMHE', 'User-Agent': 'box-python-sdk-3.3.0', 'X-Box-UA': 'agent=box-python-sdk/3.3.0; env=python/3.10.4'}, 'params': {'offset': 0}} [2022-09-13 02:50:26,578: WARNING/MainProcess] "GET https://api.box.com/2.0/folders/0/items?offset=0" 403 0 {'Date': 'Mon, 12 Sep 2022 18:50:26 GMT', 'Transfer-Encoding': 'chunked', 'x-envoy-upstream-service-time': '100', 'www-authenticate': 'Bearer realm="Service", error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token."', 'box-request-id': '07cba17694f7ea32f0c2cd42790bce39e', 'strict-transport-security': 'max-age=31536000', 'Via': '1.1 google', 'Alt-Svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"'} b'' [2022-09-13 02:50:26,587: WARNING/MainProcess] Message: None Status: 403 Code: None Request ID: None Headers: {'Date': 'Mon, 12 Sep 2022 18:50:26 GMT', 'Transfer-Encoding': 'chunked', 'x-envoy-upstream-service-time': '100', 'www-authenticate': 'Bearer realm="Service", error="insufficient_scope", … -
Django Filtering Objects
I have here some issue with the Product.objects def say_hello(request): queryset = Product.objects.filter(collection__id=1) return render(request, ‘hello.html’, {‘name’: ‘Mosh’, ‘products’: list(queryset)}) I get the Error: Unresolved attribute reference ‘objects’ for class ‘Product’.:6 It returns no list on: http://127.0.0.1:8000/playground/hello/ Does somebody know what can be the issue? -
my python anywhere website is not loading all my statics
hello i have uploaded my Django project to Pythonanywhere but not all my statics are loading for example some images are missing it is not because i didnt load my staticfiles correctly if that is the case my site wouldnt load css but it does -
Adding custom_password field to UserSerializer without registering it to User model in Django REST API
I need a way to add the confirm_password field in the data my CreateUserView returns without creating it explicitly in my user model. I tried doing the following but it raised TypeError at /user/create/ User() got unexpected keyword arguments: 'confirm_password'. How can I solve this issue? Thank you for all the response Here is my code: serializer.py class CreateUserSerializer(serializers.ModelSerializer): confirm_password = serializers.CharField( max_length=100, write_only=True, required=False ) class Meta: model = User fields = [ "id", "email", "password", "confirm_password", "first_name", "last_name", ] extra_kwargs = {"password": {"write_only": True}, "id": {"read_only": True}} def create(self, validated_data): return User.objects.create_user(**trim_spaces_from_data(validated_data)) views.py class CreateUserView(CreateAPIView): permission_classes = [permissions.AllowAny] serializer_class = CreateUserSerializer def create(self, request, *args, **kwargs): queryset = User.objects.filter(email=request.data["email"]) if queryset.exists(): raise CustomUserException("Provided email address is already in use") if not "confirm_password" in request.data.keys(): raise CustomUserException("Confirm password field is required") if not request.data["password"] == request.data["confirm_password"]: raise CustomUserException("Passwords does not match") serializer = CreateUserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(status=200, data=serializer.data) -
Django python - how do add new record every time I update the screen? instead it updates the existing record.?
How do add new record every time I update the screen? instead it updates the existing record.? -
Django - Redis distributed lock
Django 4.0.6 Django-redis 5.2.0 Is usage like this: with caches["redis"].lock("bob", ttl=900, timeout=300, retry_delay=15): dostuff supposed to work on a ElastiCache cluster in cluster mode from k8s pods? Seems like I'm getting multiple instances getting into the locked area. -
How to make a query across multiple models in Django
I'm using Django and I want to know how to get objects through 3 models These are my models class Participant(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) is_leader = models.BooleanField(default=False) team = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, related_name="participants") application_date = models.DateField(auto_now_add=True, null=True) resolution_date = models.DateField(null=True, blank=True) accepted = models.BooleanField(default=False) class Team(models.Model): name = models.TextField(default="") is_public = models.BooleanField(default=False) institution = models.ForeignKey(Institution, on_delete=models.CASCADE, null=True, related_name='teams') campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, null=True, related_name='teams') class Campaign(models.Model): name = models.TextField(default="") description = models.TextField(default="") initial_date = models.DateTimeField(auto_now_add=False, null=True, blank=True) end_date = models.DateTimeField(auto_now_add=False, null=True, blank=True) qr_step_enabled = models.BooleanField(default=True) image_resolution = models.IntegerField(default=800) sponsor = models.ForeignKey(Sponsor, on_delete=models.CASCADE, null=True, related_name='campaigns') I have the user through a request, and I want to get all campaigns of that user. I tried doing it with for loops but I want to do it with queries this is what I had: user = request.user participants = user.participant_set.all() for participant in participants: participant.team.campaign.name is there a way to make a query through these models and for all participants? A user can have many participants, and each participant has a Team, each team has a campaign -
Error when trying to Serialize a ManyToMany relationship (Django with DRF)
I'm getting an error when I try to serialize a many-to-many relationship The error description that is shown to me in the console is this: AttributeError: Got AttributeError when attempting to get a value for field product on serializer Ped_ProDetail. The serializer field might be named incorrectly and not match any attribute or key on the Product instance. Original exception text was: 'Product' object has no attribute 'product'. The models involved in the relationship are written like this: class Produto(models.Model): valor_unitario = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) nome = models.CharField(max_length=75) descricao = models.TextField() genero = models.CharField(max_length=10, default="Indefinido") qtd_estoque = models.IntegerField() cor = models.ForeignKey(Cor, on_delete=models.PROTECT, related_name="produtos") tamanho = models.ForeignKey( Tamanho, on_delete=models.PROTECT, related_name="produtos" ) marca = models.ForeignKey(Marca, on_delete=models.PROTECT, related_name="produtos") class Pedido(models.Model): endereco_entrega = models.ForeignKey( Endereco, on_delete=models.PROTECT, null=True, related_name="pedidos" ) forma_pagamento = models.ForeignKey( Forma_Pagamento, on_delete=models.PROTECT, null=True, related_name="pedidos" ) usuario_dono = models.ForeignKey( get_user_model(), on_delete=models.PROTECT, related_name="pedidos" ) data_entrega = models.DateField() data_pedido = models.DateField(default=date.today) finalizado = models.BooleanField(default=False) qtd_parcela = models.IntegerField() valor_parcela = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) preco_total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) itens = models.ManyToManyField(Produto, related_name="pedidos", through="Ped_Pro") class Ped_Pro(models.Model): produto = models.ForeignKey( Produto, on_delete=models.PROTECT, related_name="ped_pros" ) pedido = models.ForeignKey( Pedido, on_delete=models.PROTECT, related_name="ped_pros" ) qtd_produto = models.IntegerField(default=1) data_entrada = models.DateTimeField(default=datetime.now) The serializers: class ProdutoSerializer(ModelSerializer): class Meta: model = Produto fields = … -
How to autofill form based on the selected 'id' using javascript or ajax in django
I am new ,i want to autofill form when i select vehicle id from template .hre is my models . class Fuel(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) previous_km = models.IntegerField(blank=False, null=False) progressive_km = models.IntegerField(blank=False, null=False) when i select vehicle then corresponding vehicle previous_km automatically filled in form. here a write simple javascript code manually but i want to take from database. <script> let usersData = [ { id: 1, email: "u1@gmail.com", fname: "fname-1", lname: "lname-1", previous_km : 1000, }, { id: 2, email: "u2@gmail.com", fname: "fname-2", lname: "lname-2", previous_km : 2000, }, ]; document.getElementById('vehicle').onchange = (e) => { let selectedUser = usersData.find(userdata => userdata.id == e.target.value); console.log(selectedUser); document.getElementById('previous_km').value = selectedUser.previous_km; }; -
didnot insert email on field in django rest framework
i insert email field on API but cannot insert. the code is here below if user.group == 'passenger': #request to all drivers passenger_trip = Trip.objects.filter(passenger=user) #display only id and status field of trip model and passenger email passenger_trip = passenger_trip.values('id', 'status', 'created', 'updated', 'pick_up_address', 'drop_off_address', 'price', 'passenger__email') return passenger_trip and response of API on thundredclient is below:- [ { "id": "412f04aa-3b34-4ee4-a07f-e464cff148c3", "created": "2022-09-12T12:27:31.542074Z", "updated": "2022-09-12T12:27:31.542091Z", "pick_up_address": "pokhar", "drop_off_address": "kathmand", "price": "20", "status": "REQUESTED" }, { "id": "6629e234-a723-4e5c-a44d-e272e7b3a124", "created": "2022-09-12T13:04:22.309149Z", "updated": "2022-09-12T13:04:22.309166Z", "pick_up_address": "pokhar", "drop_off_address": "kathmand", "price": "20", "status": "REQUESTED" }