Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Live Stream a rtsp stream on webpage using ffmpeg
I have a continuous live rtsp stream from my ip cam("rtsp://user:pass@IP_ADDR/PORT"). How can i play this stream on a web page using ffmpeg and websockets(python). -
A function in django view returns a list of dictionary. How can I get value to particular key in its robot test case
Django view function returns: [{u'Name': u'Test Name', u'Description': u'Test', u'Marks': u'10'}] I am Calling the API using RequestsLibrary in Robot and my response seems like a dictionary response but I am unable to fetch value for any particular key. -
Python Heroku App Deployment - not compatible with buildpack
I am trying to deploy a simple "Hello World" Python app in Heroku, but it told me that the deployment is not compatible with buildpack. I've tried to search for the solution in previous similar situation, and did all stuff (e.g. including runtime.txt, requirements.txt etc.) that others can finally solve their problems, but I still have this error message. Would you pls assist to tell why that happens and how I can get it solved? Many thx! What I did:- Created hello_4.py In cmd, go to the respective folder, and run “python hello_4.py” and use browser to go to http://localhost:5000/ Hello world message successfully appears Ctrl+C to stop the localhost $git init saw the .git folder created $git add . $git commit -m "initial commit 4" $pip freeze > requirements.txt Created Procfile in 1 line: web: gunicorn hello_4:app Created runtime.txt in 1 line: python_version = "3.6.3" $heroku create mthd010 --buildpack heroku/python Successful without error message. Refreshed dashboard in Heroku website, and saw that mthd010 app was created $git push heroku master [error message appears] My error message: Image 1 requirements.txt: Image 2 runtime.txt: python_version = "3.6.3" Procfile: web: gunicorn hello_4:app hello_4.py: from flask import Flask app = Flask(__name__) @app.route('/') def … -
.gitignore not ignoring files on current server
I'm trying to import my Bitbucket repo into my Digital Ocean Django server (next to env, static and manage.py. But when I do git add . inside the server directory, and then git status, it still shows the env files there. Any reason why this is happening? Edit: .gitignore env/ /env /bin /lib /media /static /include /reports .DS_Store *.pyc celerybeat-schedule.db __pycache__/ db.sqlite3 settings.py -
Find model instance from table name Django
I've the following table. class TempTable(models.Model): name = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) ... ... class Meta: db_table = 'temp_table' Now suppose I know the table name temp_table. Currently I'm using the following script to get the model instance from table name. from django.db.models import get_app, get_models all_models = get_models() for item in all_models: if item._meta.db_table == 'temp_table': return item Are there any better ways of achieving this..?? -
i want to use year increment after 3 loop in django
in My tag.py @register.assignment_tag def year(): return "2017" In my index.html {% year as years %} {% for Manvi_User in ordering %} <li>{{ Manvi_User.first_name }}</li> {{years}} {{ Manvi_User.dob}} {% if forloop.counter|divisibleby:3 %} {{ years = years+1}} {% endif %} {% endfor %} I want to display starting first 3 name with year 2017 then 3 name with year 2018 and next 3 name should be with year 2019 -
Specifying a namespace in include() without providing an app_name
models.py from django.conf.urls import include, url app_name = "Review" urlpatterns = [ url(r'^books/', include("Review.urls", namespace='reviews')), ] I am providing app_name before my urlpatterns. But it's giving me error while running my code. The errors are given below: File "E:\workspace\python\web\Book_Review_App\Book\urls.py", line 13, in <module> url(r'^books/', include("Review.urls", namespace='reviews')), File "E:\workspace\python\web\Book_Review_App\venv\lib\site-packages\django\urls\conf.py", line 39, in include 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. Please help. -
Display a list of organizations that links to a list of documents belonging to that organization in Django 2.0?
I want my 'index' view to display a list of Organizations. Each organization name should be linked to a Documents view that lists all the Documents uploaded by that Organization. Here's what I have, but I'm lost at this point. urls.py from django.urls import path from website import views urlpatterns = [ path('', views.Index.as_view(), name='index'), path('documents/', views.Documents.as_view(), name='documents'), ] views.py from django.views.generic import ListView from website.models import Organization, Document from django.utils import timezone class Index(ListView): model = Organization template_name = 'website/index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() return context class Documents(ListView): model = Document context_object_name = 'document_list' queryset = Document.objects.all() template_name = 'website/documents.html' index.html - Specifically, how do I create the href's to link to send the organization name to the view? {% extends 'website/base.html' %}{% load static %} {% block title %}Organizations{% endblock %} {% block content %} <h3>Organizations</h3> <hr> {% for organization in object_list %} <a href="{% url 'documents' %}slug={{ organization.name }}">{{ organization.name }}">{{ organization.name }}</a> {% empty %} <p>No Organizations Yet</p> {% endfor %} {% endblock %} documents.html - This is where I want a list of documents, specific to the organization clicked to populate {% extends 'website/base.html' %}{% load static %} {% block … -
Link between Models in Django
I am new to Django. I wanted to know how to link data of the foreign key. Here is the code. class CreateSchool(models.Model): schoolName = models.CharField(primary_key=True, max_length=250) class SchoolDetails(models.Model): createSchool = models.OneToOneField(CreateSchool,to_field='schoolName') principalName = models.CharField(max_length=250) schoolAddress = models.CharField(max_length=500) class kidDetails(models.Model): schoolUID = models.ForeignKey(SchoolDetails,to_field='schoolUID') childName= models.CharField(max_length=245) childUID = models.CharField(max_length=245) my question is when i enter the details of the kid, how to store the kids data with respect to schoolDetails and createschool model from the UI. For example, I need to store kid A in 1 school and i want to store kid 2 in 2 school. How to achieve this. I am completely beginner. Any help would be great. -
Django Python - TemplateDoesNotExist at /blog/
I'm using Django version 1.11.7 and I get the error saying TemplateDoesNotExist. I've been getting this error message when I try to load http://127.0.0.1:8000/blog/. Here is my settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.8.6. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 't$6p8^=z+%8_zm+qb%s8&!!sh@j%)lg4byd@nc8(s5#ozoz&-l' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'taggit', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N … -
Django .annotate with When
I am trying to do a query and get a sum of values based on a conditions. I need all the 'shares" when the 'action' == '+' I have to group by the issues. qs = Trades.objects.all ().filter ( id = id ) .annotate ( d_shrs = Sum ( When ( action = '+', then = 'shares' ) ) ).order_by ( 'issue' ) where am I going wrong? Thanks. -
django views.py avoid duplicate code in views
hello I have crate a simple blog using DJANGO with three class in views.py views.py def blog(request): posts=blog.objects.filter(createddate__lte=timezone.now()).order_by('-createddate') if request.method == "POST": name = request.POST.get('name') message = request.POST.get('message') contact.objects.create(name=name message=message) return render(request, 'base.html'{'posts':posts}) def blog_details(request,slug): posts=blog..objects.filter(createddate__lte=timezone.now()).order_by('-createddate') pos=get_object_or_404(app_descripts, slug_title=slug) if request.method == "POST": name = request.POST.get('name') message = request.POST.get('message') contact.objects.create(name=name message=message) return render(request, 'blog_details.html'{'posts':posts,'pos':pos}) def about(request): posts=blog..filter(createddate__lte=timezone.now()).order_by('-createddate') if request.method == "POST": name = request.POST.get('name') message = request.POST.get('message') contact.objects.create(name=name message=message) return render(request, 'about.html'{'posts':posts}) in the html I use this way because I have some code: {% extends 'blog/base.html' %} {% block content %} ....................... {% endblock %} In the base.html out of block content I have a simple contaim where I have code for all post ( posts=blog..filter(createddate__lte=timezone.now()).order_by('-createddate') ). but to view the tthat posts in all pages(blog,blog_details,about) must write this code ( posts=blog..filter(createddate__lte=timezone.now()).order_by('-createddate')) in all views to work fine. that happen and for my html contact form because is out of content. how can avoid to execute some code in all views ? -
Django Queryset One to Many list output
I am trying to make the following magic happen: I'm grabbing a HUGE queryset via values, making it into a list, then consuming it by a page. BUT, I want to consume the manys in the one to many relationship (via a parent model) they have with another model, and have them as a list in the list. Is this even a thing? So say I have: # models.py class Game(Odd): type = models.ForeignKey(Type, on_delete=models.PROTECT, null=True, default=1) book = models.ForeignKey(Bookmaker, on_delete=models.PROTECT, null=True, default=23) amount = models.DecimalField(max_digits=10, decimal_places=2, null=True) class TipFromHuman(TimestampModel): tipper = models.ForeignKey(Human, on_delete=models.CASCADE, null=True) odds = models.ForeignKey(Odd, on_delete=models.CASCADE, null=True) tip_against = models.NullBooleanField(default=False) and in a script I'm running: # snippet qs = Game.objects.all().values('id', 'type__name', 'book__name', 'TipFromHuman__tipper__name').distinct() qsList = list(qs) return qs And in the template I can do: {% for q in qsList %} Type {{ q.type__name }} with {{ q.book__name }} from {{ q.TipFromHuman__tipper__name }} {% endfor %} and have it output as: Type Alpha with Green Eggs and Ham from Dr. Seuss, Potatoes, and Green Eggs where there are three associated TipFromHuman records with the tipper names "Dr. Seuss", "Potatoes", and "Green Eggs" Currently, instead of teh desired behavior, I get three different entries in the list … -
Google OAuth with Django
I am following How to sign in with the Google+ API using Django? to use Google Sign In for my Django app. I am on the step that says Add the SOCIAL_AUTH_GOOGLE_OAUTH2_KEY and SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET settings with the client key and secret you created earlier. I am wary of adding these directly to settings.py because they will then be committed to my git repo. How can I make these values available in my app without exposing them unnecessarily? I think environment variables are common for this purpose. I also see that I can download a JSON file from my Google Developer Console. -
Django-tables2 breaking a table after 25 rows for ads
In django-tables2, I have a table loading 50 rows per page but I would like to break the table at every 25 rows into its own table with its own headers so I can insert a script tag to load ads in between and then continue the row counter from the last table. How can I do this using django-tables2? views.py: from .tables import TrackTable def profile_list(request): track_list = Track.objects.all() table = TrackTable(track_list) RequestConfig(request, paginate={"per_page": 50}).configure(table) context = { "track_list": track_list, "table": table, } return render(request, "profile_detail.html", context) profile_detail.html <div id="div-ads"></div> <script data-cfasync='false' type="text/javascript"> /* ad js code */ </script> <div class="row"> <div class="col-xs-12"> {% if track_list %} {% render_table table "django_tables2/bootstrap.html" %} {% else %} <p>No records found</p> {% endif %} </div> bootstrap.html {% load querystring from django_tables2 %} {% load trans blocktrans from i18n %} {% load bootstrap3 %} {% if table.page %} <div class="table-responsive"> {% endif %} {% block table %} <table{% if table.attrs %} {{ table.attrs.as_html }}{% endif %}> {% block table.thead %} <thead> <tr> {% for column in table.columns %} {% if column.orderable %} <th {{ column.attrs.th.as_html }}><a href="{% querystring table.prefixed_order_by_field=column.order_by_alias.next %}">{{ column.header }}</a></th> {% else %} <th {{ column.attrs.th.as_html }}>{{ column.header }}</th> {% endif … -
Django api call in view unable to save for foreign key userId
I am trying to save the data from api call to an api using view. Everything else works but however, the foreign key to user model userId give me this error : ValueError: Cannot assign "4": "BookAppt.patientId" must be a "MyUser" instance. I don't know what is the problem as i did say same post with the same value to that BookAppt table API and it works normally. But when saving using the API call, it gave me this error. And also, is there a way to take the date(datefield) and time(timefield) from Appointment table and save it into scheduleTime(datetimefield) ? Here is my code: Do note that im combining all the code so that is it easier for you guys to see. Appointments is in django project 2 and BookAppt is in django project 1. model class Appointments (models.Model): patientId = models.ForeignKey(MyUser, on_delete=models.CASCADE) clinicId = models.CharField(max_length=10) date = models.DateField() time = models.TimeField() created = models.DateTimeField(auto_now_add=True) ticketNo = models.IntegerField() STATUS_CHOICES = ( ("Booked", "Booked"), ("Done", "Done"), ("Cancelled", "Cancelled"), ) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default="Booked") class BookAppt(models.Model): clinicId = models.CharField(max_length=20) patientId = models.ForeignKey(MyUser, on_delete=models.CASCADE) scheduleTime = models.DateTimeField() ticketNo = models.CharField(max_length=5) status = models.CharField(max_length=20) serializer class AppointmentsSerializer(serializers.ModelSerializer): valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M … -
Django ModelForm not Saving to Database
I am new to Django. I am trying to save a form to Database. It doesn't show any error but just won't save it to the DB. Any help would be much appreciated! Here is my code: models.py class Estate(models.Model): type = models.CharField(max_length=100) net_area = models.CharField(max_length=10) total_area = models.CharField(max_length=10) price = models.CharField(max_length=10) cep = models.CharField(max_length=8) state = models.CharField(max_length=30) city = models.CharField(max_length=30) neighborhood = models.CharField(max_length=30) street = models.CharField(max_length=250) number = models.CharField(max_length=10) complement = models.CharField(max_length=100) rooms = models.CharField(max_length=3) suits = models.CharField(max_length=3) parking_spots = models.CharField(max_length=3) bathrooms = models.CharField(max_length=3) description = models.CharField(max_length=1000) logo = models.FileField() def get_absolute_url(self): return reverse('register:create2') def __str__(self): return self.type + ' ' + self.neighborhood views.py class CreateView1 (TemplateView): template_name = 'register/estate_form1.html' def get(self, request): form1 = AddForm() return render(request, self.template_name, {'form1': form1}) def post(self, request): form1 = AddForm(request.POST) text = None if form1.is_valid(): text = form1.cleaned_data() form1.save() args = {'form1': form1, 'text':text} return render(request, self.template_name, args) forms.py class AddForm(forms.ModelForm): class Meta: model = Estate fields = ('type','net_area','total -
How do I get the user's email after signing up with Django All Auth?
I have a django project that uses django all auth for signing up users. After the user enters username, email and password, a confirmatiion emal is sent and it redirects to a page displaying that they should check their inbox for the link. I want in that page, before clicking the link, to display the email that the user has used to sign up. -
Why my form doesn't return all the errors?
My form.py: class PostForm(forms.ModelForm): title_it = forms.CharField(label='Titolo (it)', widget=forms.TextInput()) title_en = forms.CharField(label='Title (en)', widget=forms.TextInput()) text_it = forms.CharField(label='Testo (it)', widget=forms.Textarea(attrs={'rows':"20", 'cols':"100"})) text_en = forms.CharField(label='Text (en)', widget=forms.Textarea(attrs={'rows':"20", 'cols':"100"})) views = forms.IntegerField(widget=forms.HiddenInput(), initial=1) class Meta: model = Post fields = ('title_it', 'title_en', 'text_it', 'text_en', 'tags', 'views') My models.py: class Post(models.Model): title = MultilingualCharField(_('titolo'), max_length=64) text = MultilingualTextField(_('testo')) ... MultilingualCharField and MultilingualCharField are about the same: class MultilingualCharField(models.CharField): def __init__(self, verbose_name=None, **kwargs): self._blank = kwargs.get("blank", False) self._editable = kwargs.get("editable", True) #super(MultilingualCharField, self).__init__(verbose_name, **kwargs) super().__init__(verbose_name, **kwargs) def contribute_to_class(self, cls, name, virtual_only=False): # generate language specific fields dynamically if not cls._meta.abstract: for lang_code, lang_name in settings.LANGUAGES: if lang_code == settings.LANGUAGE_CODE: _blank = self._blank else: _blank = True rel_to = None if hasattr(self, 'rel'): rel_to = self.rel.to if self.rel else None elif hasattr(self, 'remote_field'): rel_to = self.remote_field.model if self.remote_field else None localized_field = models.CharField(string_concat( self.verbose_name, " (%s)" % lang_code), name=self.name, primary_key=self.primary_key, max_length=self.max_length, unique=self.unique, blank=_blank, null=False, # we ignore the null argument! db_index=self.db_index, #rel=self.rel,#AttributeError con django 2.0 rel=rel_to, default=self.default or "", editable=self._editable, serialize=self.serialize, choices=self.choices, help_text=self.help_text, db_column=None, db_tablespace=self.db_tablespace ) localized_field.contribute_to_class(cls, "%s_%s" % (name, lang_code),) def translated_value(self): language = get_language() val = self.__dict__["%s_%s" % (name, language)] if not val: val = self.__dict__["%s_%s" % (name, settings.LANGUAGE_CODE)] return val setattr(cls, name, property(translated_value)) … -
Unable to import Django model from the other app during migration roll-back
I'm creating a data-migration for the new_app with the possibility to roll it back. # This is `new_app` migration class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.RunPython(import_data, reverse_code=delete_data) ] This migration adds some data to the model defined in other app: my_other_app. To import the model where I want to update or delete records I use apps.get_model() method. # This is `new_app` migration def import_data(apps, schema_editor): model = apps.get_model('my_other_app', 'MyModel') It works like charm when I apply migrations. But when I run try to roll back the migration with the :~> manage.py migrate new_app zero I get exception: LookupError: No installed app with label 'my_other_app'. Model import in roll back code: # This is `new_app` migration def delete_data(apps, schema_editor): schema_model = apps.get_model('my_other_app', 'MyModel') The code for model import is identical, but why it doesn't work during migration roll back? For now I have a workaround with straight model import during roll-back. Don't know if it may cause troubles in future. -
Django REST Framework: nested serializer not properly validating data
I'm new to DRF (and Django) and trying to create a nested serializer which is able to validate the following request data: { "code": "12345", "city": { "name": "atlanta", "state": "Georgia" }, "subregion": { "name": "otp north" } } To simplify things for the client, I'd like this single request to create multiple records in the database: A City (if a matching one doesn't already exist) A Subregion (if a matching one doesn't already exist) A CodeLog which references a city and (optionally) a subregion Models: class City(models.Model): name = models.CharField(max_length=75, unique=True) state = models.CharField(max_length=50, blank=True) class Subregion(models.Model): city = models.ForeignKey(City) name = models.CharField(max_length=75) class CodeLog(models.Model): code = models.CharField(max_length=10) city = models.ForeignKey(City) subregion = models.ForeignKey(Subregion, blank=True, null=True) Serializers: class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields = ('name', 'state') class SubregionSerializer(serializers.ModelSerializer): class Meta: model = Subregion fields = ('name',) class CodeLogSerializer(serializers.ModelSerializer): city = CitySerializer() subregion = SubregionSerializer(required=False) class Meta: model = CodeLog fields = ('code', 'city', 'subregion') # This is where I'm having troubles create(self, validated_data): city_data = validated_data.pop('city', None) subregion_data = validated_data.pop('subregion', None) if city_data: city = City.objects.get_or_create(**city_data)[0] subregion = None if subregion_data: subregion = Subregion.objects.get_or_create(**subregion_data)[0] code_log = CodeLog( code=validated_data.get('code'), city=city, subregion=subregion ) code_log.save() return code_log View: class CodeLogList(APIView): … -
Bitrix API on Django
Are there any Bitrix API implementations for the Django REST Framework, do I need several examples, or is the concept itself? How is Bitrix DRF authorization? -
Queryset with values filtered from another queryset
If I have a queryset qs1 like this: <QuerySet [{u'name': u'John', u'birthdate': u'1980-01-01'}, {u'name': u'Larry', u'birthdate': u'1976-12-28'}, .....']} I need to use all values associated with key 'name' from qs1 to query another model and get qs2 like this: <QuerySet [{u'student_name': u'John', u'grade': u'A'}, {u'student_name': u'Larry', u'grade': u'B'}, .....']} After this, I have to combine qs1 and qs2 so the final_qs like this: [{u'name': u'John',u'birthdate': u'1980-01-01', u'grade': u'A'}, {u'student_name': u'Larry', u'birthdate': u'1976-12-28', u'grade': u'B'}, .....']} How would I achieve this? I have code like this: qs1 = Person.objects.values('name', 'birthdate') for t in qs1: qs2 = Grades.objects.filter(student_name=t['name']) .values('student_name', 'grade') My qs1 looks OK. However, my qs2 becomes this: <QuerySet [{u'student_name': u'John', u'grade': u'A'}]> <QuerySet [{u'student_name': u'Larry', u'grade': u'B'}]> Because of qs2, I am not able use zip(qs1, qs2) to construct final_qs the way I want. -
Django Push Notification with Android App
I am working on an Android project where I am using DJANGO as my backend. There are 2 kinds of android app I needed to create.Suppose they are App1 and App2. Now I am sending message from App1 to App2 and vice versa and i also need real time update in both the app for which i am using django push notification.But I am not getting really good examples on how to implement this django as a backend in Firebase cloud messaging between both of my android apps.I am really new to this .Please help me I am really stuck in this from quite a few days and I dont what to do. -
Update field in rendered Django Form
I'm having a hard time figuring out how to update a Field in Django Form while editing the Form. In my form I have a ModelChoiceField and ChoiceField: first is a list of Car manufacturers, second is a list of models available for this manufacturer. Obviously I don't want to fill second field with models for every manufacturer but only for one selected in first ModelChoiceField. Here's my example Form: class PostForm(forms.ModelForm): make = forms.ModelChoiceField(queryset=Manufacturer.objects.all()) model = forms.ChoiceField() ... In my template after I render PostForm I disable model field with jQuery and wait for user to select some value in make field. And then use AJAX to request values for model field (in this sample code I only return single item): $('#id_make').change(function () { $.ajax({ url: '{% url 'get_models' %}', data: {'make': $('#id_make :selected').text()}, dataType: 'json', success: function (data) { $('#id_model').append($('<option>', { value: 1, text: data.model})).removeAttr('disabled'); } }); }) With this done I do see updated options in <select> element for model ChoiceField, but after I select new value in model ChoiceField and submit form I receive: Select a valid choice. 1 is not one of the available choices." '1' is id of the element that I appended to …