Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
KeyError in pandas dataframe
in the below code my problem is , when word (which s given by user) is searched when is not in the my table column, pop up message appears and says user doesn't exist , but my if searched is not working, does any body have an idea where i'm doing it wrong, please let me know , i'm working in django, pandas def products(request): if request.method == "POST": df = pd.read_csv("media_cdn/media/user_change_history.csv",header=None) searched = request.POST['searched'] context = {} if searched in df.index: data = df.loc[df[0] == searched] #if data in df.index: data = data.transpose() data = data.to_html(classes='table-wrapper') context = {'d': data} else: messages.info(request, 'Username is incorrect') return render(request, 'blog/products.html', context) else: return render(request, 'blog/products.html') in the above code my problem is , when word (should represent a cell in user ID column) (which s given by user) is searched when is not in the my table column, pop up message appears and says user doesn't exist , but my if searched is not working, does any body have an idea where i'm doing it wrong, please let me know , i'm working in Django, pandas -
How to setup elasticsearch with mongodb, mysql and python flask and django?
I am new to Elasticsearch and have no idea about setting up Elasticsearch with MongoDB and python. I am working on a project which is dependent on 2 microservices. First microservice runs on Django which uses MySQL as database and the other microservice runs on flask which uses MongoDB as database. Now I want to setup Elasticsearch with these 2 microservice so that I can make efficient and fast searches in my project. If anyone has any idea about setting up Elasticsearch with MongoDB, MySQL and python, then kindly help me. -
Why my random picture is not getting uploaded in the media path i provided in the model [duplicate]
i want to upload random pictures from a static named folder to my database. These are my files. Please suggest a way. I am stuck here forever. views.py class VerifyOTPView(APIView): permission_classes = (AllowAny,) serializer_class = VerifyOTPSerializer def post(self, request): serializer = VerifyOTPSerializer(data=request.data) mobile = request.data['mobile'] otp_sent = request.data['otp'] #print('one_time_password', one_time) if mobile and otp_sent: old = Profile.objects.filter(mobile = mobile) if old is not None: old = old.first() otp = old.otp if str(otp) == str(otp_sent): serializer = self.serializer_class(data=request.data) mobile = request.data['mobile'] if serializer.is_valid(raise_exception=True): instance = serializer.save() content = {'mobile': instance.mobile, 'otp': instance.otp, 'name':instance.name, 'username':instance.username, 'logo':instance.logo, 'profile_id': instance.profile_id } return Response(content, status=status.HTTP_201_CREATED) else: return Response({ 'status' : False, 'detail' : 'OTP incorrect, please try again' }) serializers.py class VerifyOTPSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['mobile','otp'] def create(self,validated_data): instance = self.Meta.model(**validated_data) mywords = "123456789" res = "expert@" + str(''.join(random.choices(mywords,k = 6))) path = os.path.join(BASE_DIR, 'static') dir_list = os.listdir(path) random_logo = random.choice(dir_list) instance = self.Meta.model.objects.update_or_create(**validated_data, defaults = dict( username = res, name = instance.mobile, logo = random_logo, profile_id = res))[0] instance.save() return instance models.py class Profile(models.Model): mobile = models.CharField(max_length=20) otp = models.CharField(max_length=6) name = models.CharField(max_length=200) username = models.CharField(max_length=200) logo = models.ImageField(upload_to ='profile/', blank=True,null = True) profile_id = models.CharField(max_length=200) settings.py ` STATIC_URL = … -
Need to link my existing view to the admin using admin plus module in a table type view
admin.py def my_view(request): pass admin.site.register_view('timelogreport', view=my_view, name='TimeLog Report') views.py def dictfetchall(cursor): "Return all rows from a cursor as a dict" columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ] @api_view(['GET']) def job(self): cursor = connection.cursor() with open('C:\\Users\\gobs4\\stage\\Project-Management-Tools\\query.sql','r') as inserts: query = inserts.read() cursor.execute(query) return Response(dictfetchall(cursor)) I have used the django admin plus module for creating a view in admin page, But i dont know how to link the above views.py to the admin register view. Can you please help me to do that and i need to show it as table view and not as a json view in the admin, is that possible? -
Changing Request header definition and forwarding to application server
I apologize if my terminology is incorrect. I'm trying to change the name of an incoming header without changing the frontend connection configuration because I have a current server that uses the current value and a new server that has to use a different value on the same physical machine and same IP. Currently getting from front end RequestHeader set X-Y_Z %{SSL_CLIENT_S_DN_CN}e <---- with an underscore in the definition On the new application, using python / django, django framework apparently doesn't accept any headers with an underscore in them. It strips them completely. In apache logs, it shows up and the information is being passed, but not to the application. I set up a reverse proxy with apache in front of the application and tested it out with a dash instead of underscore, and everything works fine. In django, the default for remote user authentication is remote_user everywhere so instead of using X-SSL-Client-CN, I just used Remote-User and that worked. Client authentication from CAC is coming across fine. Is there some method to rewrite the header definition using the reverse proxy in front of the apache server with the application or, within the server if possible? Basically, I want to … -
Django allauth emailverification
I use allauth and want to send a verfication email. ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.ionos.com' EMAIL_HOST_USER = 'info@mydomain.com' EMAIL_HOST_PASSWORD = 'secretpassword' EMAIL_PORT = 587 I use Ionos, the error which shown in browser: SMTPAuthenticationError at /accounts/signup/ (535, b'Authentication credentials invalid') Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 4.0.1 Exception Type: SMTPAuthenticationError Exception Value: (535, b'Authentication credentials invalid') The credentials are correct, maybe there's an error with the passwordencoding, or I'm doing it completly wrong. Do I need any smtp client in the django backend? -
File/data recovery
Very specific question. I was storing a copy of my data in the system folder of a package. Made it easier to run from system.file(). Unfortunately, I accidentally reinstalled the package, and my personal files were "deleted" when R reinstalled the package. They vanished after reinstalled. I searched for the files in my system, but only the shortcut of where they used to be are found. Are the copies of my data actually deleted? If not, how can I recover them? -
NoReverseMatch at /auth/password/reset/
I am using dj-rest-auth package to do auth related functions, installed the package and added to installed apps and included it in main url as follows path('auth/', include('dj_rest_auth.urls')), it works for login, logout etc, but when I do password reset it throws the error http://127.0.0.1:8000/auth/password/reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name -
Call property from one model class to another model class
I'm new to Django. My goal is to send the value of a method belonging to a model class by default in the other model class. class Booking(models.Model): room_number_id = models.ForeignKey(Room,on_delete=models.DO_NOTHING) customer_id = models.ManyToManyField(Customer) check_in = models.DateTimeField(auto_now_add=True) check_out = models.DateTimeField(auto_now_add=False,auto_now=False,auto_created=False, null=True) status = models.BooleanField(default=False) @property def calculate_day(self): day = self.check_out - self.check_in return str(day.days) @property def total_price(self): day = self.check_out - self.check_in price = self.room_number_id.room_type_id.room_cost return price\*day.days class Payment(models.Model): booking_id = models.ForeignKey(Booking,on_delete=models.DO_NOTHING) ACCEPT_CHOICES = ( ('Cash','Cash'), ('Credit','Cash'), ) payment_type = models.CharField(max_length=1,choices=ACCEPT_CHOICES) total_price = models.IntegerField(default=Booking.total_price()) payment_detail = models.TextField() In short, I want to make the value of the total_price method of the Booking model the default value of the price in the Payment model. Apart from that, if you have different advice and suggestions, I'm waiting for a reply. -
How to integrate Django Project with Kafka
I know there is python library of kafka for python: confluent-kafka. But How can I integrate Web (Django) application with kafka? I found django-logpipe library. But I am not sure Its production ready or not -
Pass a list of start_urls as parameter from Django to Scrapyd
I'm working in a little scraping platform using Django and Scrapy (scrapyd as API). Default spider is working as expected, and using ScrapyAPI (python-scrapyd-api) I'm passing a URL from Django and scrap data, I'm even saving results as JSON to a postgres instance. This is for a SINGLE URL pass as parameter. When trying to pass a list of URLs, scrapy just takes the first URL from a list. I don't know if it's something about how Python or ScrapyAPI is treating or processing this arguments. # views.py # This is how I pass parameters from Django task = scrapyd.schedule( project=scrapy_project, spider=scrapy_spider, settings=scrapy_settings, url=urls ) # default_spider.py def __init__(self, *args, **kwargs): super(SpiderMercadoLibre, self).__init__(*args, **kwargs) self.domain = kwargs.get('domain') self.start_urls = [self.url] # list(kwargs.get('url'))<--Doesn't work self.allowed_domains = [self.domain] # Setup to tell Scrapy to make calls from same URLs def start_requests(self): ... for url in self.start_urls: yield scrapy.Request(url, callback=self.parse, meta={'original_url': url}, dont_filter=True) Of course I can make some changes to my model so I can save every result iterating from the list of URLs and scheduling each URL using ScrapydAPI, but I'm wondering if this is a limitation of scrapyd itself or am I missing something about Python mechanics. This is how … -
Django admin - custom admin pages for specific users
In my main url router I have two separate urls, one for each admin page that I set up in my admin file: /adminmain/ URL goes to the default admin panel (admin.site.urls) with many different models registered. But I want the second URL /adminonly/ to only go to users where is_admin = True in their user profIle. So far my admin.py file below isn't achieving this. If I log in as a superuser then both urls will show all of the models registered to that admin page. But if I login as a non-superuser who IS an admin (is_admin = True) I just get a message: You don't have permission to view or edit anything. on BOTH pages. I want that user to see the models registered for the /adminonly/ page. My admin.py: from django.contrib.admin import ModelAdmin, site, AdminSite from .models import Post class PostAdmin(ModelAdmin): list_display = ( 'id', 'slug', 'title', 'author', 'publish_date' ) def has_view_permission(self, request, obj=None): if request.user.is_admin: return True def has_add_permission(self, request): if request.user.is_admin: return True def has_change_permission(self, request, obj=None): if request.user.is_admin: return True def has_delete_permission(self, request, obj=None): if request.user.is_admin: return True class PostsAdmin2(AdminSite): site_header = 'Posts Admin' def has_permission(self, request): return request.user.is_admin posts_site2 = PostsAdmin2(name='PostsAdmin') #default … -
intermittent 502 Bad Gateway nginx/1.18.0 (Ubuntu)
My django app has ben running for about 3 months now. I intermittently get a 502 Bad Gateway error message on any page, I will even get this error the Django admin page, so I don't think its my code. Most of the time the page loads fine, or if I just reload it will load. can someone help me understand where I'm making a mistake The output from sudo tail -20 /var/log/nginx/error.log yields: 2022/03/29 16:12:56 [error] 720#720: *8182 upstream prematurely closed connection while reading response header from upstream, client: 165.225.38.84, server: _, request: "GET /backyard/ HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/backyard/", host: "104.131.165.99", referrer: "http://104.131.165.99/backyard/" 2022/03/29 16:19:44 [error] 720#720: *8188 upstream prematurely closed connection while reading response header from upstream, client: 165.225.38.84, server: _, request: "GET /garage/ HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/garage/", host: "104.131.165.99", referrer: "http://104.131.165.99/garage/" 2022/03/29 16:26:29 [error] 720#720: *8194 upstream prematurely closed connection while reading response header from upstream, client: 165.225.38.84, server: _, request: "GET /garage/ HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/garage/", host: "104.131.165.99", referrer: "http://104.131.165.99/garage/" 2022/03/29 16:36:30 [error] 720#720: *8205 upstream prematurely closed connection while reading response header from upstream, client: 165.225.38.84, server: _, request: "GET /garage/ HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/garage/", host: "104.131.165.99", referrer: "http://104.131.165.99/garage/" 2022/03/29 16:42:58 [error] 720#720: *8209 upstream prematurely closed connection while … -
How can I get my image to display using django?
I cannot get my images to display on my webpage while using Django. All I see is the images 'alt' text displayed, and a broken image icon next to it. I'm able to successfully upload the image as originally intended. I'm using an Ubuntu AWS instance with Apache installed on it for my server. I also have Pillow installed for displaying images. I'm also able to successfully load my CSS, so I know that it probably isn't an issue with my static directories or settings. This is my settings.py file: import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-)zp1^v$1v9%@3e*rz4yp0o964-^!8@ruff4$((b5vcv6*h@d-x' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['ec2-3-14-217-157.us-east-2.compute.amazonaws.com', '3.14.217.157'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'product.apps.ProductConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'productapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', … -
Using djnago-import-export import of blank TextField
Imagine I have Data stored in my Dabase. A Model contains a Django-TextField with blank=True but without null=True according to Djnago-convention. The Data was created via the admin-menu. Empty Text-Fields are stored as empty string which works just fine. But import trough django-import-export throws violates not-null constraint DETAIL: Failing row contains. Is this a problem of djnago-import-export? -
Filter queryset by year between two date fields
I have a start_date and an end_date fields in my model. The user shall be able to filter records by selecting a year value, so that records that span over multiple years should be shown if the year selected is included. For example: Selected year: 2019 start_date end_date 2017-03-12 2021-09-03 2019-12-12 2020-06-05 I can do this query by raw SQL like that: SELECT * FROM `orders` WHERE '2019' BETWEEN YEAR(`start_date`) AND YEAR(`end_date`); How can I do this using Django ORM and avoid raw SQL queries? Because I am already using the ORM in multiple filters and only remaining this bit. -
Django M2M queryset with multiple instances and Q
I have the following oversimplified models: class Surgerytype(models.Model): title = models.CharField(max_length=255, null=True, blank=True) class Content(models.Model): surgery = models.ManyToManyField(Surgerytype, null=True, blank=True) I have a lot of Content instances, which themselves have a lot of Surgerytypes related to them. You can think of Surgerytypes as tags. I have this query: content = Content.objects.all() # surgeries is an array of Surgerytype instances titles query = content.filter(Q(surgery__title__in=surgeries) When I ajax send to my backend a tag (i.e. a Surgerytype instance title), all good the query returns all the instances of Content that include this tag. Now, the problem is that if I select two tags, the queryset returns nothing instead of all Content instances that include these 2 tags and possibly more tags. I have found on SO how to do this for 1 M2M model in the Content model but it is quite dirty and not scalable at all (there are 3 other M2M/filters to add in the real Content model). Any ideas? Found many questions related to the subject but it doesn't seem to have a definitive, scalable answer. Many thanks to you all -
Django template link with Django include
is it possible to open a html link form in a Django html include? So, I don't want the link in the html to open in the browser address bar so that it can be seen. So I was wondering if you can somehow open it in the same template. But that didn't work for me, because the default data for the form is not taken. As example: in my .html file I have a URL <li role="presentation"><a href="{% url 'create_exposition' blog.id %}">create new blog</a></li> {% include "zed/create_exposition.html" with ...%} This link in urls.py re_path(r'^(?P<blog_id>[0-9]+)/create_exposition/$', views.create_exposition, name='create_exposition'), and in the views.py def create_exposition(request, blog_id): form = ExpositionForm(request.POST or None) blog= get_object_or_404(Blog, pk=blog_id) if form.is_valid(): blogs_expositions = blog.exposition_set.all() for s in blogs_expositions: if s.identifikationsnummer == form.cleaned_data.get("idnumber"): context = { 'blog': blog, 'form': form, 'error_message': 'You already added that exposition', } return render(request, 'zed/create_exposition.html', context) exposition = form.save(commit=False) exposition.blog= blog exposition.save() return render(request, 'zed/blog_detail.html', {'blog': blog}) context = { 'blog': blog, 'form': form, } return render(request, 'zed/create_exposition.html', context) Yes, I know it is still the old away and no genericview. I am already retooling piece by piece. -
How can Django Admin change "history" logs be used to also store copy of data?
Django Admin change "history" logs As you know Django Admin's sidebar shows a list of APP > MODELS. When you click on a MODEL, the focus area displays a list of RECORDS. Click on a RECORD, then the focus area shows a single RECORD as a form which you can change. Here, in the upper right hand corner of the change form, is a gray pill-shaped button labeled "HISTORY" with entries like: Dec. 9, 2021, 4:38 p.m. me Changed Table price headers. Feb. 26, 2022, 2:06 p.m. me Changed Table date headers. What I need is a copy of the record data before each change. Later, I need to query the Django database and--in this example--get the version of the record prior to the Feb 26 change. How can Django Admin change "history" logs be used to also store copy of data? Not for every Django Model The rest of the Models & Records in Django Admin should behave normally. I only have a few Models where I need history log and data. Not to be confused with model history When discussing this with other Django developers I have to explain the history I need is for the record's data, … -
CSS not showing in deployment for django
I'm trying to get my CSS to show on my Django app in deployment. My project is being hosted on an Ubuntu instance, using AWS. I'm using Apache to run my project on the instance. However, the CSS won't display in the browser. When I launch it from my IDE (PyCharm), the CSS will display on localhost perfectly. How can I fix this? I've looked all over for answers and so far nothing has worked. I've cleared my browsers cache, and tried on different browsers as well and the CSS still will not show. settings.py: """ Django settings for productapp project. Generated by 'django-admin startproject' using Django 4.0.3. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-+0-wtmj)^gt@#cn8)0=l(30#3s2df)&vi6f*yx10zrsnh+)s+6' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['ec2-3-14-217-157.us-east-2.compute.amazonaws.com', '3.14.217.157'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
Disable swagger in django projectt
I have set up drf-yasg swagger and now I'm wondering what's the best way to disable swagger, because they should not be exposed after going live. -
Modify instance before it's saved on import
I'm setting up an import process for a model which has a ForeignKey relationship, and I've got an extra field on the model where I'd like to store the provided value if it's an invalid ID of the related table. The ID's in question here are UUIDs, so there's a good chance that someone along the line will provide some invalid data. class Result(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) passport = models.ForeignKey( to='results.Passport', null=True, blank=True, on_delete=models.SET_NULL ) invalid_passport = models.CharField( max_length=255, blank=True, null=True, help_text=_("An invalid passport number") ) The import file will contain a passport column for the UUID of the related object, but I'd like to save the provided value to invalid_passport if it doesn't match any Passport instances. My resource looks like this; class ResultResource(resources.ModelResource): """ Integrate django-import-export with the Result model """ passport = fields.Field( column_name='passport', attribute='passport', widget=ForeignKeyWidget(Passport, 'id') ) class Meta: instance_loader_class = CachedInstanceLoader model = Result fields = ( 'id', 'passport', 'invalid_passport' ) def init_instance(self, row=None): """ Initializes a new Django model. """ instance = self._meta.model() if not instance.passport: instance.invalid_passport = row['passport'] return instance def before_save_instance(self, instance, using_transactions, dry_run): """ Sets the verified flags where there is a passport match. """ if instance.passport: … -
How to cache object in django template and update if it was changed?
I have a simple Django app with a single view for displaying the product list: from time import sleep <other imports> class ProductListView(ListView): model = Product paginate_by = 50 allow_empty = True def get(self, *args, **kwargs): sleep(2) return super().get(*args, **kwargs) And the template: <div class="container"> {% for product in page_obj %} <div class="col-3 my-2"> <product details> </div> {% endfor %} </div> I use sleep(2) to emulate the slow uploading of a huge amount of objects from the database. Now I need to implement the next workflow: template from this view should be cached. So the first page upload should take >2 sec, the next one <2sec, uploaded from the cache. change Product item in the database (via admin page for example) page on refresh is loaded from cache, but product info should be updated to the newest I'm, researching the Django caching mechanism, but I'm not sure which one should I try. So is it possible in Django to implement this workflow? -
One To Many Connection
So I have two models Field and Sensor which have a OneToMany connection. Im creating a page where I have all the fields and whenever i click on one i get its respective sensors. I've made 4 test sensors (3 of them are on Field1, 1 on Field2) but its printing first one to first field and 2nd one to 2nd field maybe because of the pk parameter. Any clue how to fix that ? class Field(models.Model): friendly_name = models.CharField(max_length=24, blank=True) soil_type = models.CharField(max_length=24, choices=SOIL_TYPES, blank=True) cultivation = models.CharField(max_length=128, choices=CULTIVATIONS, blank=True) class TreeSensor(models.Model): field = models.ForeignKey(Field, on_delete=models.CASCADE) datetime = models.DateTimeField(blank=True, null=True, default=None) sensor_name = models.CharField(max_length=200, blank=True) longitude = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) latitude = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) View : def detail(request, field_id): try: sensor = models.TreeSensor.objects.get(pk=field_id) except models.TreeSensor.DoesNotExist: raise Http404("No sensors for this field") return render(request, 'dashboard/detail.html', {'sensor': sensor}) html: <h1> {{ field.friendly_name}}</h1> {% for sensor in field.treesensor_set.all %} {{treesensor.sensor_name}} {%endfor%} -
How to instantiate model with init function in modelforms?
I have a program that uploads a csv of data in order to map values in the csv to other values. In order to do this, the user must select which columns in the csv they need to create the mapping, so that no extraneous information is on the mapping page. To do this I created a dynamic Django by overriding the init function in my ModelForm. The problem is that even though I'm able to dynamically show the column values, when the user tries to select the values and save them to the model, it fails, because the Model choices don't align with the dynamic checkbox values. So I've overridden the Model's init function to populate the model's choices. My problem is I'm not sure how to instantiate the model in the ModelForm to call the init function. model class ColumnMapping(models.Model): CHOICES =[('row_1', 'A'), ('row_2', 'B'), ('row_3', 'C')] company = models.ForeignKey(RawData, on_delete=models.CASCADE) columnNames = MultiSelectField(max_length=100, choices=CHOICES) def __init__(self, *args, **kwargs): self.choices = kwargs.pop('choices') super(ColumnMapping, self).__init__(*args, **kwargs) self._meta.get_field.choices = self.choices form - I think something needs to happen here in the Meta class, but since the model = ColumnMapping line doesn't instantiate the model (I don't think), I don't think …