Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get db utilization of a mysql query
Is there any way/command to get DB utilization of a query i.e.., how much memory of DB it used, how much time it took to execute.. and all. so, that I can plan and further optimize the query I tried to google it but I can only find ways to get CPU utilization (application level memory usage) but didn't find anything related to DB utilization I'm using Mysql DB and Django -
How can I set JWT at the Frontend with bootstrap html not with react whilst the API is created with Django?
Recently I am studying and building API with Django. I successfully set up the API of authentication system with Django API. I am curious to know that is there any solution to add this JWT with frontend whilst the frontend only with bootstrap designed login form. I don't want to use react or anything like that. Only through Django views is it possible to do? It will be really helpful if there is any way to do. Or if it's required only js I will love to accept but I just want to call the templates login.html file not want to add any react or nodejs. I searched online but everywhere either react or nodejs. Here I am adding the features I am using of JWT in my code #settings.py from datetime import timedelta # for JWT REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', # 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ # 'rest_framework.authentication.SessionAuthentication', # 'rest_framework.authentication.TokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=360), 'REFRESH_TOKEN_LIFETIME': timedelta(days=90), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', # 'SIGNING_KEY': settings.SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': … -
Django annotate with Subquery, OuterRef and group by parent in table
I want to get summary data from Items to categories(Ctg) Has 3 inherit`s models: class Ctg(models.Model): tt = models.Charfield() parent = models.ForeignKey('self') # inherit categories sort = models.IntegerField() class Common(models.Model): ctg = models.ForeignKey(Ctg) # independent of ctg in Items recd = models.DateField() class Items(models.Model): common = models.ForeignKey(Common) ctg = models.ForeignKey(Ctg) coin = models.DecimalField() Filter data by month/years/ctg then summary 'coin's. items_recd = Items.objects.filter(common__recd__year=2022, common__recd__month=1) items_qs = items_recd.filter(ctg=OuterRef('pk')).values('ctg').annotate(total=Sum('coin')).values('total') items_qs_parent = items_recd.filter(ctg__parent=OuterRef('pk')).values('ctg__parent').annotate(tota=Sum('coin')).values('total') Create subqueries with condition, if has parent in Ctg this row will be summary childrens. I`ll got here items_qs_parent, but items_qs is None total = Subquery(items_qs.values('total')) if F('parent') is None else Subquery(items_qs_parent.values('total')) Data of table objs = Ctg.objects.order_by('sort').annotate(total=total, tax=F('total') * 0.2).values('tt', 'total', 'parent', 'tax) -
django orm how to optimize query?
class Category(MPTTModel): name = models.CharField(max_length=500, verbose_name="Название категории") external_id = models.CharField(max_length=9, default='', verbose_name="Внешний ключ") parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class Course(models.Model): name = models.CharField(max_length=500, verbose_name="Название курса") category = models.ForeignKey('Category', on_delete=models.PROTECT, null=True, blank=True, related_name="get_courses") category_list = Category.objects.filter(external_id='00000001').get_descendants(include_self=True) list_category_course = [] for category in category_list: courses = [course.name for course in category.get_courses.all()] list_category_course.append({'category': category, 'courses': courses}) how to optimize query? -
TroubleShooting: Related Field got invalid lookup - icountain
class Job_type(models.model): created_by = UserForeignKey(auto_user_add=True, verbose_name="The user that is automatically assigned", related_name="Job_type_created_by") and in admin.py @admin.register(Job_type) class Job_type_Admin(admin.ModelAdmin): list_display = ('id','job_type','is_deleted','is_active','created_by', 'created_on','last_modified_by','last_modified_on') list_display_links = ['id','job_type','created_by'] list_filter = ('job_type','created_by') search_fields= ('id','job_type','created_by','created_on', 'last_modified_by','last_modified_on') list_per_page = 20 please help me ,i want created by in search field but it is throwing error as Related Field got invalid lookup - icountain -
DRF-How to update single field in create method of model serializer
I want to create all the field except image field.then, I want to update image from that field. How to do this in create method??? serializers.py def create(self, validated_data): loc_id = validated_data.pop("location")["id"] currency_id = validated_data.pop("base_currency")["id"] try: loc_obj = get_object_or_404(Location, id=loc_id) validated_data["location"] = loc_obj currency_object = get_object_or_404(Currency, id=currency_id) validated_data["base_currency"] = currency_object image_data = validated_data.pop('logo_filename') organization = Organization.objects.create(**validated_data) return organization except Exception as e: raise serializers.ValidationError(e) its my create method how can i update logo_filename field??? -
Login URL redirecting issue
When I log into my web application, it doesn't redirect to the custom redirect page created instead it redirects to the default accounts/profile url in Django. Below are my codes : Views.py def student_dashboard(request): if request.user.is_authenticated and request.user.is_student: render(request,'student/s_dashboard.html') elif request.user.is_authenticated and request.user.is_client: return redirect('client_dashboard') elif request.user.is_authenticated and request.user.is_supervisor: return redirect('supervisor_dashboard') else: return redirect('signin') def supervisor_dashboard(request): if request.user.is_authenticated and request.user.is_student: return render(request,'student/s_dashboard.html') elif request.user.is_authenticated and request.user.is_client: return redirect('client_dashboard') elif request.user.is_authenticated and request.user.is_supervisor: return redirect('supervisor_dashboard') else: return redirect('signin') def client_dashboard(request): if request.user.is_authenticated and request.user.is_student: return render(request,'student/s_dashboard.html') elif request.user.is_authenticated and request.user.is_client: return redirect('client_dashboard') elif request.user.is_authenticated and request.user.is_supervisor: return redirect('supervisor_dashboard') else: return redirect('signin') def signin(request): if request.user.is_authenticated: if request.user.is_student: return redirect('student_dashboard') if request.user.is_cleint: return redirect('client_dashboard') if request.user.is_supervisor: return redirect('supervisor_dashboard') if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username =username, password = password) print(user) if user is not None: login(request,user) if user.is_authenticated and user.is_student: return redirect('student_dashboard') #Go to student home elif user.is_authenticated and user.is_client: return redirect('client_dashboard') #Go to teacher home elif user.is_authenticated and user.is_supervisor: return redirect('supervisor_dashboard') else: form = AuthenticationForm() return render(request,'registration/login.html',{'form':form}) else: form = AuthenticationForm() return render(request, 'registration/login.html', {'form':form}) urls.py from django.contrib import admin from django.urls import path, include from CPRS_admin.views import * from CPRS_admin.HOD_views import * urlpatterns … -
Django and uploading Media files to AWS S3 for users in app to view
this might be a vague question but I am developing an app where users can upload files (mainly videos and pictures). Users can create groups and upload their images to the group and anyone in the group can view these files. I have the AWS S3 configured and working however, Aws recommends to keep the bucket Private. if the bucket is private, is the only way to allow access for users to view content (maybe uploaded by friends VIA pre-signed urls?) is it necessary to even make the bucket private. I see tutorials and they usually have the bucket settings to public. this means that any person that has a hold of the url can access an image. Lets say user 1 uploads to group xyz. only members of xyz should be able to access that image. implementing unique identifiers for images will make it tough for someone to get access to that image but not impossible. would this be the better approach or having django generate signed URLS everytime a user wants to view a certain image? I feel like this is overkill for a photosharing app. are there any other ways to add security? -
'Geometry SRID (0) does not match column SRID (4326)' error when adding a point in a Django web-app
I have this Django webapp that allows adding a point via Django's OSMGeoAdmin. The database is Postgresql with Postgis installed. When I add a point and save it, it results to this error mysite/app/models.py from django.contrib.gis.db import models class shop(models.Model): name = models.CharField(max_length=100) type = models.CharField(max_length=50, default='') location = models.PointField() address = models.CharField(max_length=100) city = models.CharField(max_length=50) mysite/mysite/settings.py INSTALLED_APPS = [ 'website', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'app', ] DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'djangodb', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', } } C:\Users\imper\miniconda3\envs\django\Lib\site-packages\django\db\backends\utils.py _execute() method def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: # params default might be backend specific. return self.cursor.execute(sql) else: return self.cursor.execute(sql, params) The app's table in my djangodb Postgis database -
What will be the problems with Django app for image processing when deploying?
I am new bee to Django. Never deployed any projects to server. Always worked in localhost. I made Django app, with simple functionalities like: User can add images (CRUD) User can download all the uploaded images with a frame(PNG Frame are already stored, basically I am just masking(merging 2 images) it on user's image will pillow library) I saw many videos on how to deploy your project on server and I already bought domain and VPS(basic one which has 1CPU core, 1GB ram and 20GB SSD) hosting on godaddy. What I am afraid of? Is this server enough for my project(ram and 1cpu core)? Let's say if 100 users request at same time(for image and my code will merge 2 image and serve back) is my server enough to handle all this? I am using Postgresql database. Is postgresql good for such project? I am sorry if this is duplicate question, I honestly don't know what to search for? I am using nginx and Django rest framework for some basic features. -
Django form.is_valid() returning false
I am trying to update an instance from Author table, But form.is_valid returning false always. I have added enctype="multipart/form-data" in the template form, In the views im getting files also, but form is not validating. Am I missing anything? This is views section. def update(request,something,id): something=str(something).lower() if something=='author': author=Author_model.objects.get(id=id) if request.method=='GET': return render(request,'update_author.html',{'author':author}) else: form = Author_form(request.POST, request.FILES,instance=author) print('form.is_valid()',form.is_valid()) if form.is_valid(): image_path = author.image_document.path if os.path.exists(image_path): os.remove(image_path) form.save() return redirect('http://127.0.0.1:8000/bookdb/author/') This is a template. <form action="" method="post" enctype="multipart/form-data"> <center> <h2>Update Author</h2><hr> <table> <tr> <td>Solutation </td> <td>: <select name="" id=""> <option value="{{author.solutaion}}">{{author.solutaion}}</option> <option value="Mr">Mr</option> <option value="Ms">Ms</option> <option value="Dr">Dr</option> </select></td> </tr> <tr><td >Name </td> <td>: <input type="text" value="{{author.name}}"></td></tr> <tr> <td>Email </td> <td>: <input type="email" value="{{author.email}}"></td> </tr> <tr> <td>Headshot {{author.headshot}}</td> <td><img src="{{author.headshot.url}}" alt="Image not found" width="100" height="60"></td> <td>: <input type="file"></td> </tr> </table><br> <button type="submit">Submit</button> </center> {%csrf_token%} </form> -
How can I have my previous code through rollback on Heroku?
I have a problem with my app when I uploaded it on heroku, I used the rollback to go back to a previous version without errors and it seems to be fine when I give it open app. However, the code in pycharm shows the same errors, and if I commit, I get the errors of the latest version as if the code does not have the previous version, can I do something to recover that code? -
Is there a way in Django to create and populate a column to the database with a string's length value?
I have a class/model in my models.py that can receive a textField. I want to add a column in my database that corresponds to the length of this textField. What is the best way of doing that? -
How do I make the edit and cancel link appear only if its the logged in user is the one who created the object? Django
The edit and delete function works fine but I cant make it specific that it only appears to the person that created that object? {% for job in jobs %} <tr> <td>{{ job.job }}</td> <td>{{ job.location }}</td> <td><a href="/jobs/{{ job.id }}/view">View</a> <a href="/main">Add</a> <a href="/jobs/{{ job.id }}/edit">Edit</a> <a href="/jobs/{{ job.id }}/delete">Cancel</a> </td> </tr> {% endfor %} -
Django Form submit in foor loop
I tried many things, now I have to ask you. The user has multiple Buttons. My goal is to count every click on a specific button. The specific button is the Field (Field Model). How the models look: class Field(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) description = models.CharField(max_length=255) title = models.CharField(max_length=255) url = models.CharField(max_length=255) ... class Hits(models.Model): field = models.OneToOneField( Field, default=None, null=True, on_delete=models.CASCADE) hits = models.IntegerField(default=0) \\HTML Template {% for i in request.user.field_set.all %} {% if request.user == i.user %} <form method="POST"> {{ hits_form }} {% csrf_token %} <div class="full-w-button"> <p class="preview-description">{{ i.description }}</p> <button onClick="javascript:window.open('{{i.url}}', '_blank');" type="submit" class="link-box"> <p class="text-bold-medium">{{ i.title }}</p> </button> </div> </form> {% endif %} {%endfor %} The hits_form is supposted to be a hidden input for counting the click. My problems are: -when user clicks button, counter for specific Field += 1 -having a form for each Field, currently one form is probably saving the counter for all fields, so i am looping with forms but every form is the same \\views.py In the Views File, the important parts is the hits_form, the other form works fine if request.method == 'POST': hits_form = #here i am stuck form = FieldForm(request.POST, instance=Field(user=request.user)) … -
How to force graphs to stay inside a bootstrap container/card (html, css, plotly, bootstrap, django)?
I'm making a django-based web app that has bootstrap cards with some graphs inside of them. I'm using bootstrap so both the graphs and the cards are responsive; however at some screen sizes, the graphs extend beyond the size of the cards. Is there a way to force everything in a card (or some other container) to say inside the container? Partial html code. Can post the graph code if helpful - it is written in python + plotly. I'm not sure if the problem is with the graphing or with the html/script. I'm also working on posting an image, but the upload is failing :). <div class="container"> <h2 class="pb-2 border-bottom mt-4">Scores for {{ user.username }} </h2> <div class="row mb-4 mt-4"> <div class="col-lg-6"> <div class="card"> <div class="card-body"> <h5 class="card-titler">Result</h5> <p style="color:gray;"> {{last_test_date | safe}}</p> {{score | safe}} <!-- <div class="chart" id="bargraph1", style="height: 150px">--> <div class="chart" id="bargraph1"> <script> var graphs = {{plot1 | safe}} </script> </div> <a href="#" class="card-link text-end p-2">Learn More</a> </div> </div> <div class="col-lg-6"> <div class="card"> <div class="card-body"> <h5 class="card-title">Results Over Time</h5> <br> <!--<div class="chart" id="bargraph2", style="height: 225px">--> <div class="chart" id="bargraph2"> <script> var graphs = {{plot2 | safe}} </script> </div> </div> </div> </div> </div> -
Handle Django MIgrations
I'm working on a Django project with Postgres database using Docker. We are facing some issues in with our migrations, I did not add Django migrations inside .gitignore because I want everyone to have the same database fields and same migrations as well, but every time when someone changes the models or add a new model and push the code with migrations so migrations re not applying in our database as it should be, every time we faced this issue that sometimes ABC key doesn't exist or ABC table doesn't exist, so how can I overcome from it. Dockerfile: EXPOSE 8000 COPY ./core/ /app/ COPY ./scripts /scripts RUN pip install --upgrade pip COPY requirements.txt /app/ RUN pip install -r requirements.txt && \ adduser --disabled-password --no-create-home app && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/media && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts USER app CMD ["/scripts/run.sh"] run.sh #!/bin/sh set -e ls -la /vol/ ls -la /vol/web whoami python manage.py collectstatic --noinput python manage.py makemigrations python manage.py migrate uwsgi --socket :9000 --workers 4 --master --enable-threads --module myApp.wsgi docker-compose.yml version: "3.8" services: db: container_name: db image: "postgres" restart: always volumes: … -
TypeError: unsupported type for timedelta seconds component: NoneType
File "C:\Users\rafae\Projects\Django and React Tuto\music_controller\spotify\util.py", line 22, in update_or_create_user_tokens expires_in = datetime.now() + timedelta(seconds=expires_in) TypeError: unsupported type for timedelta seconds component: NoneType Hey guys, getting this error when redirecting from spotify api and going back to my local server. Above is the error message and the location. Below is the code inside models.py, determing the value of "expires_in": class SpotifyToken(models.Model): ... expires_in = models.DateTimeField() ... Thanks in advance! -
convert 'django.contrib.gis.geos.point.Point' object into coordinates in Django
I heve a model Location where I have such fields as: location_id, city, address, point. I using 'django.contrib.gis.geos.point.Point'. In my database in a column named point HEX point representation is laying. It is looks like: 0101000020E6100000644ADA43B1FF374026EE6767872E2A40. It is a fake location. The question is: how can I I get just coordinates like: (23.9987986 13.0908768)???? Now I can get only Point object like SRID=4326;POINT (23.9987986 13.0908768) using for cycle. Can any one help??? -
Run telegram bot with uWSGI
I have a Django app running on nginx+uWSGI. Inside my Django app there is a Telegram bot (python-telegram-bot). It is a Long Polling bot, not a Webhook one. Django part is completely ok, I managed to configure uWSGI and nginx. Bot is ok as well, while I run it with: python bot.py But I want to run it with uWSGI (emperor mode) and I can't find any tutorials on how to make it work. Here is my bot code (a small part. It actually has a dozen of commands and uses Django models): import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") import django django.setup() from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update from telegram.ext import ( Updater, CommandHandler, CallbackContext, PicklePersistence, ) from app.secrets import tg_token def start(update: Update, context: CallbackContext) -> None: update.message.reply_text('hi') def main() -> None: persistence = PicklePersistence( filename='arbitrarycallbackdatabot.pickle', store_callback_data=True) # Create the Updater and pass it your bot's token. updater = Updater(tg_token, persistence=persistence, arbitrary_callback_data=True) updater.dispatcher.add_handler(CommandHandler('start', start)) # Start the Bot updater.start_polling() # Run updater.idle() if __name__ == '__main__': main() Any ideas on how to configure uWSGI to run my Django app and bot.py at the same time? -
I cant update an object in Django?
Ive created a Django application where you add jobs and Im fully able to add new jobs but I can update them for some reason? The update feature isn't working and I don't know why?? <form action='/update_job/{{job.id}}' method="POST"> <ul> {% for message in messages %} <li>{{message}}</li> {% endfor %} </ul> {% csrf_token %} Title: <input type='text' value="{{job.job}}" name='job'> Description: <input type='text' value="{{job.description}}" name='description'> Location: <input type='text' value="{{job.location}}" name='location'> <input type='submit'> </form> def update_job(request, job_id): errors = Job.objects.job_validator(request.POST, job_id) if job.creator.id != request.session['user_id']: messages.error(request, "This isn't yours to edit!") if len(errors): for key, value in errors.items(): messages.error(request, value) return redirect(f'/edit_job/{job_id}') job = Job.objects.get(id=job_id) job.job = request.POST['job'] job.description = request.POST['description'] job.location = request.POST['location'] job.save() return redirect('/main') Page not found (404) Request Method: POST Request URL: http://localhost:8000/update_job/2 Using the URLconf defined in Python_Exam.urls, Django tried these URL patterns, in this order: register login logout main job_link job/create jobs/<int:job_id>/view jobs/<int:job_id>/delete jobs/<int:job_id>/edit jobs/<int:job_id>/update_job The current path, update_job/2, didn't match any of these. -
How to remove duplicates from the database table, alter the model with unique=True and makemigrations?
class CommonInfo(models.Model): name = models.CharField(max_length = 100) age = models.PositiveIntegerField() class Meta: abstract=True ordering=['name'] class Student(CommonInfo): home_group =models.CharField(max_length=5) class Meta(CommonInfo.Meta): db_table='student_info' Blockquote I have a similar database model with existing data. I want to add a uique=True on the field name. Is there any way I could remove the existing duplicate data before I alter the field name as unique? -
Exporting field data in many to many relationships using django-input-output only shows primary key
I am trying to export the data from my database from the django admin page using the django-import-export package. When I export a model, I also want to show the data in a particular field for every object in a many to many relationship. It looks something like this: models.py class Item(models.Model): part_number = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=250, blank=True) def __str__(self): return self.part_number class Bin(models.Model): name = models.CharField(max_length=50, unique=True) items = models.ManyToManyField(Item, blank=True) def __str__(self): return self.name admin.py class ItemResource(ModelResource): class Meta: model = Item fields = ('part_number', 'description') @admin.register(Item) class ItemAdmin(ImportExportModelAdmin): save_as = True resource_class = ItemResource class BinResource(ModelResource): class Meta: model = Bin fields = ('name', 'item__part_number') @admin.register(Item) class ItemAdmin(ImportExportModelAdmin): save_as = True resource_class = BinResource The way I would expect this to work is that if I export Items, I will get a document that has all the part numbers in one column and the description in another. This works just fine. However, I would also expect that when I export Bins, one column would show all the names, and another column would display a list of all the part numbers of the items that are associated with the bin. What I actually get is a … -
TypeError: __init__() got an unexpected keyword argument 'bot_id' when i pass a variable from views to form
I need to pass a variable from views to form to limit the selection of objects in the ModelChoiceField depending on the bot_id Tell me how to do it right, in the current implementation, the code gives an error TypeError: init() got an unexpected keyword argument 'bot_id'. My code: views.py def edit_question(request, bot_id, question_id): bot = get_object_or_404(SettingsBot, id=bot_id) question = get_object_or_404(Questions, id=question_id) QuestionInlineFormSet = inlineformset_factory(Questions, RelationQuestion, exclude=('bot',), fk_name='base', form=SubQuestionForm) if request.method == "POST": form = QuestionsForm(data=request.POST, instance=question) formset = QuestionInlineFormSet(request.POST, request.FILES, bot_id=bot_id, instance=question) if formset.is_valid(): formset.save() return redirect(question.get_absolute_url()) else: form = QuestionsForm(instance=question) formset = QuestionInlineFormSet(bot_id=bot_id, instance=question) return render(request, 'FAQ/edit_questions.html', {'question': question, 'bot': bot, 'form': form, 'formset': formset}) forms.py class SubQuestionForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.bot_id = kwargs.pop('bot_id', None) super(SubQuestionForm, self).__init__(*args, **kwargs) self.fields['sub'] = forms.ModelChoiceField(Questions.objects.filter(bot=self.bot_id)) class Meta: model = RelationQuestion fields = ['sub'] models.py class Questions(models.Model): question = models.CharField(max_length=30, verbose_name="Вопрос") answer = models.TextField(default="No text", verbose_name="Ответ на вопрос") id = models.BigAutoField(primary_key=True) bot = models.ForeignKey("SettingsBot", related_name="Бот", on_delete=models.CASCADE, verbose_name="Бот") general = models.BooleanField(default=False, verbose_name="Отображать на стартовой странице") created = models.DateTimeField(auto_now_add=True, verbose_name="Создан") updated = models.DateTimeField(auto_now=True, db_index=True, verbose_name="Изменен") class Meta: verbose_name = "Вопрос" verbose_name_plural = "Вопросы" ordering = ('-id',) def get_absolute_url(self): return reverse('FAQ:edit_questions', kwargs={'question_id': str(self.id), 'bot_id': str(self.bot)}) def __str__(self): return self.question def data(self): return [self.question, self.answer, self.id, … -
Automatically submit a value on click to a form using Javascript/Java in a Django form
I am working on a web app using Django/Python/Javascript/Java. The focal point is a map of the USA. A user should be able to click on a region and the value of that region should automatically query a database and return certain information. Currently, my code produces a const called regionName and the value of regionName is passed automatically as input to the search bar; however, from here a user needs to manually click the 'search' button to submit the form and query the database. As below: onRegionClick: function(event, code){ console.log('event', event, 'code', code); const regionName = map.getRegionName(code); console.log('regionName', regionName); $("#selection").val(regionName); }, }); What I am trying to do with the code is to automatically submit the value of regionName after it is passed to the search bar. Efforts thus far have been similar to the code below. $("#selection") - the form $("#q") - the name of the button $("#selection").on('change', function(){ if ($("#selection").val() === regionName ) { $("#q").click(); } }); This is not producing any errors, but it's not producing any results either. I've tried various substitutes along similar lines such as: .on('input'.. instead of 'change' .submit() instead of .click() I've also have an .autocomplete() method I'm using. I'm not …