Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting error when updating a simple one to one relationship field in Django-rest-framework
I'm new to Django and have some basic knowledge of python. I'm trying to create and simple relationship between two models i.e user and profile. I have defined Django's user model and my profile model is ```python class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='defaultProfileImg.png', upload_to='_profile_img') first_name = models.CharField(max_length=60, blank=True) last_name = models.CharField(max_length=60, blank=True) description = models.CharField(max_length=60, blank=True) mobile = models.CharField(max_length=60, blank=True) current_location = models.CharField(max_length=60, blank=True) profile serializer is class ProfileSerializer(serializers.ModelSerializer): user_id = serializers.IntegerField(source='user.id') class Meta: model = Profile fields= ('user','image', 'first_name', 'last_name', 'description','mobile', 'current_location', 'user_id') def update(self, instance, validated_data): user_data = validated_data.pop('user') user = UserRegistration.create(UserSerializer(), validated_data=user_data) created, profile = Profile.objects.update_or_create(user=user, subject_major=validated_data.pop('subject_major')) return profile and my view is class ProfileViewSet(APIView): # to find if isAuthenticate then authentication_classes = (TokenAuthentication,) permission_classes = [permissions.IsAuthenticated] def get(self, request): serializer = ProfileSerializer(request.user.profile) return Response({ 'profile': serializer.data }) def put(self, request, pk, format=None): # update user profile saved_article = get_object_or_404(User.objects.all(), pk=pk) serializer = ProfileSerializer(data=request.data) print('request.data', request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) I'm getting the following error {"user": \["Incorrect type. Expected pk value, received dict."\]} -
Python pickle load very slow on python 3.7 for Django nested relations, taking almost 8ms
Why is pythons pickle.load so slow for nested Django objects? I need to retreive 1800 pickled objects from cache and load them. The objects consist of a Django model instance with a 2 layers deep related object (created using 'select_related' on the queryset and then getting the required model instance). There are only a few fields (approx 5) in each layer, making the total fields about 30. Still to pickle load all 1800 objects takes almost 1.3 seconds. If I create a cached_object in the database to store it there instead of in memory, and load it from the database, it takes only 13ms for all 1800 objects, because now it doesn't need to use pickle.load, but creates the related objects 'new' from the database. Is there any particular reason that pickle.load is so slow? I was storing the objects is memory cache for performance concerns, but it only made it worse. -
Automatically create Django Profile when creating user using signals.py
I have an issue in signals.py. Parameter 'sender' value is not used. and Parameter 'kwargs' value is not used.. In my previous project, this was working fine, But in this project User(AbstractUser) model was introduced in models.py then this issue began. SIGNALS.PY from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile, MedicalInfo @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() Models.py class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_public = models.BooleanField(default=False) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) VIEWS.PY @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('public:profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, } return render(request, 'all_users/public/profile.html', context) -
How to show name in foreign key?
In Models: class ShopCategory(models.Model): category = models.CharField(max_length=100) class Meta: db_table = "tbl_ShopCategory" class Shop(models.Model): id_shop = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200) slug = models.SlugField(max_length=250, blank=True, null=True) cover_img = models.CharField(max_length=250, blank=True) category = models.ForeignKey(ShopCategory, on_delete=models.CASCADE) avgscore = models.FloatField(default=0) I want to show the Category name? ........................................................... -
Got the ValueError when trying to print one of the fields in return string function __str__()
When I try to print(or to use in return string) one of the fields, I get the following ValueError: invalid literal for int() with base 10: 'topic_id' Here is my model class: from django.db import models from django.conf import settings from languageTests.signals import topic_viewed_signal from django.contrib.contenttypes.models import ContentType User = settings.AUTH_USER_MODEL Topic = settings.TOPIC_MODEL class TopicProgress(models.Model): user = models.ForeignKey(User, on_delete='CASCADE') # user instance instance.id topic = models.ForeignKey(Topic, on_delete='CASCADE') finished = models.BooleanField(default=False) started = models.BooleanField(default=False) class Meta: unique_together = ('topic', 'user',) def __str__(self): print("topic=<{}>".format(self.topic)) return "{}-{}".format(self.user,self.topic) Also this is the topic class: class Topic(models.Model): LEVELS = ( ('b', 'Beginner'), ('i', 'Intermediate'), ('e', 'Expert'), ) level = models.CharField( max_length=1, choices=LEVELS, blank=True, default='b', help_text='Tests level', ) title = models.CharField(max_length=200, help_text='Enter a Test Name (e.g. Test #1)') objects = TopicManager() def return_level_str(self): dict_levels=dict(self.LEVELS) return dict_levels[self.level] def __str__(self): return self.title def get_absolute_url(self): return reverse('topic', args=[self.id]) I have tried to debug and figured out that "id" appears as string in C:\Users\A\Anaconda3\lib\site-packages\django\db\models\query.py in get args (<Q: (AND: ('id', 'topic_id'))>,) kwargs {} self <QuerySet [<Topic: sel>, <Topic: Past Perfect>]> I have also tried to print other fields "finished" ,"started" , "user" and they all worked perfectly. Can someone shed light on this for me ? here is the … -
socket.gaierror: [Errno 10047] getaddrinfo failed
I searched a lot but didn't find a proper solution. Seems like nobody had this problem before. Note my socket.gaierror is [Errno 10047] which means "Address family not supported by protocol family" The error I'm getting is when I try to integrate SMTP in my project so I can send mails. File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\smtplib.py", line 336, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\smtplib.py", line 307, in _get_socket self.source_address) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\socket.py", line 705, in create_connection for res in getaddrinfo(host, port, 1, SOCK_STREAM): File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\socket.py", line 748, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 10047] getaddrinfo failed SERVER_EMAIL = 'abc@example.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = 'password_here' EMAIL_HOST_USER = SERVER_EMAIL EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER And when I use the send_mail() function in my view. I get this socket error. This error goes away if I change my email backend to "django.core.mail.backends.console.EmailBackend". -
When I collectstatic I also get rest_framework in static files
I have a django project with rest_framework in installed apps. When I run python manage.py collectstatic I get a rest_framework folder in my project/static/ directory. This rest_framework folder has many files including bootstrap.min.css , font-awesome-4.0.3.css etc. Is it a good practice to have all this in my static folder, or should I be filtering rest_framework when doing python manage.py collectstatic -
Django login does not show anything
I have sign in, sign up and log out in my home page. Sign up works fine but login does not work. when i run the server it works but does not show anything, any errors or anything in login page that prompts the user to enter username and password. views.py def userLogin(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username = username, password = password) if user is not None: login(request, user) return redirect('home') else: error = True return render(request, 'login.html', {'error': error}) return render(request, 'login.html',) login.html {% extends 'base.html' %} {% block content %} <h2>Sign in</h2> <form> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign in</button> </form> {% endblock %} urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^home/$', Home, name = 'home'), url(r'^product_upload', InsertProduct, name = 'product_upload'), url(r'^success', success, name = 'success'), path('productlist/', ShowProducts, name = 'productlist'), path('<int:product_id>/', product_detail, name='product_detail'), url(r'^signup/$', signup, name='signup'), url(r'^login/$', userLogin, name='login'), url(r'^logout/$', userLogout, name='logout'), ] You can see images below: Sign Up image Sign In image -
DJANGO CHECK CONSTRAINTS: SystemCheckError: (models.E032) constraint name 'age_gte_18' is not unique amongst models
I'm trying to connect Django with PostgreSQL, so far everything was going good, I created a model for female clients from django.db import models from django.db.models import CheckConstraint, Q class fml_tbl(models.Model): fml_id = models.CharField(primary_key = True, max_length = 10) first_name = models.CharField(max_length = 20, null = False) last_name = models.CharField(max_length = 20) age = models.PositiveIntegerField(unique = True) qualification = models.CharField(max_length = 50) profession = models.CharField(max_length = 50) officer = models.ForeignKey("officer", on_delete=models.CASCADE, null = False) class Meta: constraints = [ models.CheckConstraint(check=Q(age__gte=18), name='age_gte_18') ] I added a check constraint for checking the age of the client, when I migrate, I get the error... django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (models.E032) constraint name 'age_gte_18' is not unique amongst models: client.fml_tbl, client.ml_tbl. System check identified 1 issue (0 silenced). there is also a male clients table same as this one, i'm just trying to practice django model constraints because postgresql also uses constraints, but i can't understand what to do here. I'm using Django 3.0 and Python 3.7 I searched for different answers on stackoverflow and other places but i can't find anything, I used the django documentation and this site for understanding constraints but so far this is all what … -
Django UpdateView with ImageField
Form validation isn't passing for some reason when i try to update a image on my model. I've also tried updating it without using PIL library, still doesn't work. class UpdateProfile(UpdateView): template_name = 'dashboard/edit-profile.html' form_class = UserForm success_url = None def get_object(self, queryset=None): return User.objects.get(username=self.kwargs['username']) def form_valid(self, form): self.instance = form.save(commit=False) user = self.get_object() user.full_name = self.instance.full_name user.username = self.instance.username user.email = self.instance.email user.description = self.instance.description im = Image.new(self.instance.main_image) user.profile_image = im user.ig = self.instance.ig user.fb = self.instance.fb user.pinterest = self.instance.pinterest user.twitter = self.instance.twitter user.save() return render(self.request, self.template_name, self.get_context_data()) Model Image attribute profile_image = models.ImageField(upload_to=save_profile_image, default='/static/img/blog/avatars/user-01.jpg') def save_profile_image(instance, filename): if instance: return '{}/{}'.format(instance.id, filename) form data from html. <form action="" class="tm-edit-product-form" method="post" enctype="multipart/form-data"> <div class="custom-file mt-3 mb-3"> <input id="fileInput" type="file" name="main_image" style="display: none" accept="image/*"/> {{ form.profile_image }} </div> </form> Anyway, the POST request comes throgh but the object isn't updated. The problem resides in the ImageField. Why the hell isn't it working as it should? -
Django Static files cached
My site is in production and whenever I modify my static files it doesn't reflect changes as it seems to be cached somewhere, though I can see the see changes when fresh from network tab in "inspect". My question is how can I force Django to do it automatically for me on my user's system -
Django related model not updating related object in admin
I have 2 models that look like this: models.py class Client(models.Model): deal = models.ManyToManyField('Deal', related_name="clients") class Deal(models.Model): client = models.ManyToManyField(Client, related_name="deals") Then in the admin, I have inlined the related models to make it easy to make changes regardless of the object type you have open. admin.py class ClientInline(admin.TabularInline): model = Deal.client.through class ClientAdmin(admin.ModelAdmin): inlines = [DealInline] class DealInline(admin.TabularInline): model = Client.deal.through class DealAdmin(admin.ModelAdmin): inlines = [ClientInline] However, if you add a Client to a Deal and then open the Client detail page, the corresponding deal does not appear. Is there something I'm not connecting? -
How to trigger Python script from HTML input?
I'm struggling with one part of building a website. I'm using Vue for the front end and Python for the backend. These are the steps I need to take: Take a text input in a HTML text box: <div class="search-wrapper"> <input type="text" v-model="search" placeholder="Enter Stock Ticker"/> </div> Run a python script that uses that text to run a Tweepy API search: t = tweetObj.tweetObject({{ html input here }}) tweet_string = t.get_created_at() Do a bunch of sentiment analysis (which is already done) Fill in a bunch of charts on a website (which I already have a template for) What I don't understand is whether or not I need to use Django or Flask for the Python IO. Is this necessary to take the inputs or can I get by with just simple HTTP request modules? I do understand running everything in one server, but the front end part is very new to me and I'm confused. Would appreciate some guidance on this. -
RDS and Django virtual enviornment connection issue on AWS
I am an experienced software engineer but I am new to AWS and cloud services. I have a Django app that relies on MySQL that I wish to host on Elastic Beanstalk (EB). I recently have created a new app/environment on EB and an empty Django project that works fine both on localhost and from my AWS domain. I just created a MySQL RDS instance and was able to connect to it via MySQL Workbench and the fresh Django application in the virtual environment. I have migrated all the basic tables that are prepackaged just fine and can access them on localhost. However, when I deploy the Django app from my virtual environment, Django is no longer able to connect to the RDS instance showing the following "settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Request Method: GET." Error is pictured here: https://imgur.com/a/LZZrgQG Here is my DB configuration in settings.py: if 'aakspdrcvlie60.ckoc8jkc3t2e.us-west-2.rds.amazonaws.com' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['ebdb'], 'USER': os.environ['USERNAME'], 'PASSWORD': os.environ['PASSWORD'], 'HOST': os.environ['aakspdrcvlie60.ckoc8jkc3t2e.us-west-2.rds.amazonaws.com'], 'PORT': os.environ['3306'], } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ebdb', 'USER': 'USERNAME', 'PASSWORD': 'PASSWORD', 'HOST': 'aakspdrcvlie60.ckoc8jkc3t2e.us-west-2.rds.amazonaws.com', 'PORT': '3306', } } … -
Django REST framework error - name is not defined
I have a Django 2.2 that has two apps - status and updates: django_api | status | api | updates In django_api/urls.py: from django.contrib import admin from django.urls import include, path from updates.views import ( json_example_view, JsonCBV, JsonCBV2, SerializedListView, SerializedDetailView ) from status.api.views import StatusListSearchAPIView urlpatterns = [ path('admin/', admin.site.urls), path('api/status/', status.api.urls), path('api/updates/', updates.api.urls), In django_api/status/api/views.py: from rest_framework import generics from rest_framework.views import APIView from rest_framework.response import Response from .serializers import StatusSerializer from status.models import Status class StatusListSearchAPIView(APIView): permission_classes = [] authentication_classes = [] def get(self, request, format = None): qs = Status.objects.all() serializer = StatusSeralizer(qs, many = True) return Response(serializer.data) def post(self, request, format=None): qs = Status.objects.all() serializer = StatusSeralizer(qs, many = True) return Response(serializer.data) class StatusAPIView(generics.ListAPIView): permission_classes = [] authentication_classes = [] queryset = Status.objects.all() serializer_class = StatusSeralizer def get_queryset(self): qs = Status.objects.all() query = self.request.GET.get('q') if query is not None: qs = qs.filter(content_icontains = query) return qs In django_api/status/api/serializers.py: from rest_framework import serializers from django import forms from status.models import Status class StatusSerializer(serializers.ModelSerializer): class Meta: model = Status fields = [ 'user', 'content', 'image'] def validate_content(self, value): if len(value) > 10000: raise serializers.ValidationError("This is way too long.") return value def validate(self, data): content = data.get("content", None) if … -
Not sure I understand dependancy between 2 django models
I am struggling to understand django models relationship. I have this arborescence: A train have cars, and those cars are divided into parts. Then those parts all contains different references. Like, for exemple, all the trains have the 6 cars, and the cars 6 parts. Each part have x reference to be associated. I would like to use all of them in a template later on, where the user can select the train, the car and the part he worked on, then generate a table from his selections with only the references associated to the parts he selected. It should update the train and the car (I'm trying to update a stock of elements for a company) I dont really understand which model field give to each of them. After checking the doc, Ive done something like this but i am not convinced: class Train(Car): train = models.CharField(max_length=200) id = models.CharField(primary_key='True', max_length=100) selected = models.BooleanField() class Meta: abstract = True class Car(Part): car = models.CharField(max_length=200) id = models.CharField(primary_key='True', max_length=100) selected = models.BooleanField() class Meta: abstract = True class Part(Reference): part = models.CharField(max_length=200) id = models.CharField(primary_key='True', max_length=100) selected = models.BooleanField() class Meta: abstract = True class Reference(models.Model): reference = models.CharField(max_length=200) id … -
Progress Bar Upload to S3 Django
I would like to show an upload progress bar for S3 uploads from a Django site. Currently without the progress bar being manipulated by JQuery, the uploads are working direct to S3. Once I try to implement the progress bar using JQuery, the upload form still functions as far accepting input and the file, but will not communicate the file to S3. Here is the upload view: from .forms import UploadForm def upload(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('upload') else: form = UploadForm() context = { 'form': form } return render(request, 'content/upload.html', context) Here is the HTML: {% extends "about/base.html" %} {% load crispy_forms_tags %} {% block content %} {% block navbar %}{% endblock %} <div class="site-section mb-5"> <div class="container"> <div class="form-register"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <legend>Upload Content</legend> <div class="form-group"> {{ form | crispy }} </div> <button class="btn btn-outline-info" type="submit">Upload</button> </form> <div class="progress"> <div id="progressBar" class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"> 0% </div> </div> </div> </div> {% endblock %} Here is the JQuery: $(document).ready(function() { $('form').on('submit', function(event) { event.preventDefault(); var formData = new FormData($('form')[0]); $.ajax({ xhr : function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { … -
How to install gdal package on django project with pip
I want to install GDAl package to django project in linux shared host i get the ssh access but i can't use apt command so i want to install GDAl with virtualenv and i get this error : [ERROR 2] No such file or directory: 'gdal-config': 'gdal-config' ERROR: Command errored out with exit status 1: python setup.py egg-info Check the logs for full command output. -
Does Django use built in variable names for Templates?
I'm learning Django and have done some tutorials. Does Django have built in variables that are accessible to any template in any app, or are these defined somewhere in code? For example, I have an app called users. In the models.py of users/models.py, I have this code: from django.contrib.auth.models import User In urls.py I have this: path('profile/', user_views.profile, name='profile') In users/views.py I do have a function called profile, but no where in that function am I passing a variable that allows for the use of obtaining a person's first name, however, in my template profile.html I can get the first person's name by using: {{ user.first_name }} Why is this? I was under the impression that we had to pass specific variables as dictionaries. -
Elasticsearch Indexing in Django Celery Task
I’m building a Django web application to store documents and their associated metadata. The bulk of the metadata will be stored in the underlying MySQL database, with the OCR’d document text indexed in Elasticsearch to enable full-text search. I’ve incorporated django-elasticsearch-dsl to connect and synchronize my data models, as I’m also indexing (and thus, double-storing) a few other fields found in my models. I had considered using Haystack, but it lacks support for the latest Elasticsearch versions. When a document is uploaded via the applications’s admin interface, a post_save signal automatically triggers a Celery asynchronous background task to perform the OCR and will ultimately index the extracted text into Elasticsearch. Seeing as how I don’t have a full-text field defined in my model (and hope to avoid doing so as I don’t want to store or search against CLOB’s in the database), I’m seeking the best practice for updating my Elasticsearch documents from my tasks.py file. There doesn’t seem to be a way to do so using django-elasticseach-dsl (but maybe I’m wrong?) and so I’m wondering if I should either: Try to interface with Elasticsearch via REST using the sister django-elasticsearch-dsl-drf package. More loosely integrate my application with Elasticsearch by … -
Unable to get 'get absolute url' to work (Python - Django)
Once a user had logged into my site he could write a post and update it. Then I was making progress in adding functionality which allowed people to make comments. I was at the stage where I could add comments from the back end and they would be accurately displayed on the front end. Now when I try and update posts I get an error message. I assume it is because there is a foreign key linking the comments class to the post class. I tried Googling the problem and looking on StackOverflow but I wasn't entirely convinced the material I was reading was remotely related to my problem. I am struggling to fix the issue because I barely even understand / know what the issue is. def save(self, *args, **kwargs): self.url= slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) -
How to apply python package localization file available in the package repository?
I've came across this issue a couple of times. I'm using a python package (e.g django-rest-framework-simplejwt) and it has the locale file I want in its Github repository. Now, even though I have LANGUAGE_CODE = "pt-BR" set in my django settings file, it won't load the right language. I've noticed that there's no locale folder inside my venv/lib/site-packages/rest_framework_simplejwt/. How do I install the available localization file from a repository in scenarios where installing the package skips the desired locales? -
Django POST query: Pass tuple or list in a param
I am trying to pass a tuple in a DJANGO POST query. But it is taking the value type as string. Like this: ('id','country_name') I found various links but none on how to pass a list/tuple in params. -
Django "Illegal mix of collations" for MySQL utf8mb4 table
I have reviewed other questions related to this topic, such as django python collation error However, the solutions say to encode the table using a utf8 charset. That is not a viable solution for our modern Django app running on a utf8mb4-encoded database. In my case, I need to enforce a charset or collation in the Django generated query, or in the DB itself, when utf-8 characters are being passed in (from a call to model.objects.get_or_create(), I believe with an emoji character being passed in one of the kwargs fields.) I'm getting this error: django.db.utils.OperationalError: (1267, "Illegal mix of collations (utf8mb4_unicode_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='") Any advice welcome. Thanks! -
Set the value of the Django 2 Admin Autocomplete widget using jQuery
I'm trying to add some custom logic with jQuery to a django admin view. I want to change the value of some select fields on my tabular inline fields when the value the "formula" Select Input Change. I've tried the following code, but the django admin autocomplete values does not change. rowNumber = 0 var ingredientInput = $('#id_formulaexplosioningredient_set-' + rowNumber + '-ingredient'); // console.log('aaa', ingredient, rowNumber, ingredientInput, ); console.log('select', ingredientInput.select2()); console.log('djangoAdminSelect2', ingredientInput.djangoAdminSelect2()); ingredientInput.djangoAdminSelect2().val(ingredient.ingredient.id.toString()).trigger('change'); ingredientInput.select2().val(ingredient.ingredient.id.toString()).trigger('change'); ingredientInput.val(ingredient.ingredient.id.toString()).trigger('change'); As you can see I tried 3 ways, with the val() of the element. The val() of the select2 plugin and the val() of the djangoAmindSelect2() plugin. Can anyone help me out and show me what I'm doing wrong? Thank you!