Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax request to Django returns 404 not found
I am writing my first project in Django where I now want to make an Ajax request using jQuery to get some data. The problem is that the Ajax request returns: GET http://localhost:8000/ajax/teams_for_issue/?medIssue=MI6 404 (Not Found) I am rather certain that the problem is with the URL, and I have gotten the URLs wrong several times before in this project. My Ajax code looks as follows: var medIssue = _this.issueSelector.val(); $.ajax({ url: '/ajax/teams_for_issue/', data: { 'medIssue': medIssue }, dataType: 'json', success: function(data) { _this.setTeams(data.teams) } }); This is the Django function that I want to send the answer: def teams_for_issue(request): medIssue = request.GET.get("medIssue", none) teams = Team.objects.filter(has_competence=medIssue) data = { "teams":teams } return JsonResponse(data) I have defined the following URL url(r'newpatient/', views.newpatient, name='newpatient'), url(r'ajax/teams_for_issue/', views.teams_for_issue, name='teams_for_issue'), Any help on where I go wrong would be much appriciated :) -
Django Composite Username
Is it possible to use two or more fields configured to be unique together as a username in Django? Is this a dumb idea? Eg; class MyUser(AbstractBaseUser, PermissionsMixin): user_id = models.CharField(max_length=255) backend = models.CharField(max_length=255) username = backend + user_id # ??? class Meta: unique_together = ( ('user_id', 'backend') ) -
django 1.8 admin site css issue while css file loads fine
django 1.8 on a production server: When loading the admin page, it shows the content without rendering the css, similar to the site shown here. There are no errors in chrome developer tools. These 2 css files load fine: <link href="/static/admin/css/base.7cdd754721f8.css" rel="stylesheet" type="text/css"/> <link href="/static/admin/css/dashboard.4898e2e9983d.css" rel="stylesheet" type="text/css"/> Still the admin interface appears unstyled. Relevant settings: STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticroot') STATIC_URL = '/static/' ABS_TEMPLATES_PATH = PROJECT_ROOT + '/templates' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'project_docs/site'), ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media') MEDIA_URL = '/media/' Any suggestions? -
What is the best way to implement multiple types of users in django ?
Let's say we are building a taxi app. I have an accounts app, a driver and rider app. What is the best way to differentiate between those two users(riders/drivers) ? Also, I would like to have two login forms, for each kind of user, and after login, redirect the user to the appropriate django app/module. (rider/driver). Should I use groups and permissions or should I have a Custom User Type which adds a field user_type in which I specify what kind of user it is and based on that I make logic decisions in the templates ? -
Django:Unable to compare the logged in user with the author of the post
I am building a django blogging website .I want to compare the current logged in user with the author of the blog-post and if they are same ,then allow them the edit functionality but my code is not executing the if statement even if they both are same. {% if user.is_authenticated and user.username == post.author %} Models- class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title -
Django built in request library?
I know untill a couple years ago Django did not have one, as there are several questions here regarding this topic but they are all atleast two years old How to send a POST request using django? They mostly recommend to use python-request or urllib My question is, does Django contains this by default now? A module to make POST/GET requests to another server, or is there still need to install external libs? -
Django Static Files - CSS File Won't Load
I am learning Django, and am trying to load a static css file. I have seen the other questions and read the docs, but I am still unable to see the problem. I am using Django 1.11. Here is my urls.py: from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ url(r'^$', views.index), url(r'^admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My settings.py (only the part to do with static files): STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "/static/") STATICFILES_DIRS = ( STATIC_ROOT, ) And the part of my template where I try and load the files: {% load static %} <link rel="stylesheet" type="text/css" href="{% static "css/fonts.css" %}"> <link rel="stylesheet" type="text/css" href="{% static "css/horz-navbar.css" %}"> <link rel="stylesheet" type="text/css" href="{% static "css/homepage.css" %}"> <link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}"> Whenever I load the index.html template, the following error messages are displayed by my console: core.js:5 Uncaught ReferenceError: define is not defined at core.js:5 localhost/:12 GET http://localhost:8000/static/css/homepage.css localhost/:11 GET http://localhost:8000/static/css/horz-navbar.css localhost/:10 GET http://localhost:8000/static/css/fonts.css localhost/:13 GET http://localhost:8000/static/css/style.css So Django doesn't seem to recognize that the files exist, I have checked and made sure that the files exist on my computer, and I'm … -
Django QuerySet aggregate and join
I'm quite new to Django, I'm trying to figure out how to solve this problem. This is my model: class Product(models.Model): code = models.CharField(max_length=50) name = models.CharField(max_length=50) class ProductDetail(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, editable=False) price = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal('999.99')) available = models.BooleanField(default=True) validity_tms = models.DateTimeField(default=timezone.now) Basically, for each Product I want to track price and availability changes. For this reason, many ProductDetail exist for each Product. When needed, I need to get code, name, available and price fields for every product, but only related to the ProductDetail with the maximum validity_tms for each product. This QuerySet contains only a part of the informations I need: ProductDetail.objects.values('product').annotate(max_date=Max('validity_tms')) How can I retrieve price and available fields, too? Is there a way to solve this? Did I make something wrong in the model? -
Query filter for address in django
I have an SQL database that contains a table of places that have the following columns: address, city, zip, state So is there a django package or a way to simply take ANY query a user might input into the search text box and parse the individual parts? like I type an address with a zip code so in the django backend I'd have to parse the address and the zip code. Is there a package that can do this? or Can someone give a general algorithm that might be used with django filters? -
RelatedObjectDoesNotExist User has no Profile
I am new to Django.I am creating a user registration by using the built in Django User model and Usercreation form. I am trying to extend the built-in User Model in Django so I can include an extra field company name.I am encountering this recurring error below.I would really appreciate any help in trying to solve this problem. RelatedObjectDoesNotExist User has no Profile (1)Here is my Model.py of the Profile model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Company_name = models.CharField(max_length=30) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() (2.)Here is my views.py.I am trying to update the profile model each time a new user instance is created.It seems like I have to link the create_user_profile and save_user_profile functions to my view but I am not too sure how to do this. def Register(request): if request.method == 'POST': User_form = RegisterRecruiterForm(request.POST, instance=request.user) Profile_form = ProfileForm(request.POST, instance=request.user.profile) if User_form.is_valid() and Profile_form. is_valid(): User_form.save() Profile_form.save() return HttpResponse('you are now registered') else: User_form = RegisterRecruiterForm(instance=request.user) Profile_form = ProfileForm(instance=request.user.profile) return render(request, 'Register.html', { 'User_form': User_form, 'Profile_form': Profile_form }) 3.Here is my forms.py. class RegisterRecruiterForm(UserCreationForm): email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model … -
Function Based View with While loop
I have an django app running on my raspberry pi What is going on is I run the url for this view, and it loads forever and never shows the page But when I press the button, it plays the sounds, but I want to see the template displaying the message that it is playing. The While loop is not letting the template to load, the rest is working fine. -
how correctly do the query to the model in my case Django
In the below part of the code I try to do query in the filter, that must returned only one row to the variable "appointment_row" or None. But Django swears for my code with the next error message: AttributeError at /appointments/report/1/ 'str' object has no attribute 'regimeCalendar' my models.py file: class Appointments(models.Model): patient = models.ForeignKey(Patient) regime = models.CharField(max_length=250, default='') added_at = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.regime class RegimeCalendar(models.Model): patient = models.ForeignKey(Patient) date = models.DateField(default=datetime.now, unique=True) class Meta: ordering = ['date'] unique_together = ('patient', 'date') class AppointmentCalendar(models.Model): added_at = models.DateTimeField(default=datetime.now, blank=True) appointment = models.ForeignKey(Appointments) regimeCalendar = models.ForeignKey(RegimeCalendar) patient = models.ForeignKey(Patient) doctor_mark = models.BooleanField(default=False) nurse_mark = models.BooleanField(default=False) class Meta: ordering = ['regimeCalendar'] my views.py file: ... patient = Patient.objects.get(pk=self.kwargs['pk']) context = super(AppointmentCalendarListView, self).get_context_data(**kwargs) appointment_calendar = AppointmentCalendar.objects.filter(patient=patient) appointments = Appointments.objects.filter(patient=patient) #1. Get distinct dates from all dates from regimeCalendar and add empty values to filling all row distinct_dates = [] for item in appointment_calendar: add = True for date in distinct_dates: if item.regimeCalendar.date == date.regimeCalendar.date: add = False break if add: distinct_dates.append(item) while len(distinct_dates) < 21: distinct_dates.append("") #2. table = [] doctor_marks = [""]*21 nurse_marks = [""]*21 for appointment in appointments: for date in distinct_dates: appointment_row = AppointmentCalendar.objects.filter(patient=patient, appointment_id=appointment.id, regimeCalendar_id=date.regimeCalendar.id ) if … -
How to set up Django TabularInline so I can edit intermediate table object
I'm using a TabularInline editor to allow editing of a model's relationship to another model. It's a many-to-many thru a map table. Is there a way to get django to put in an icon-link to the map table itself in the rows of the tabularInline? For example, If Machine and Part are mapped together by Machine2Part and I use a tabularInline within the Machine to provide editing of its Parts, I will get pulldown menus that allow me to select Parts which is great, but I also want a link that takes me to an admin form for the Machine2Part object/row that sits behind this relationship because my Machine2Part admin form has field editing that I want to be able to access from this location. class Part (models.Model): name = models.CharField(max_length=45) class Meta: db_table = "part" def __str__ (self): return self.name class Machine (models.Model): name = models.CharField(max_length=45) parts = models.ManyToManyField(Part, through='Machine2Part') class Meta: db_table = "machine" def __str__ (self): return self.name class Machine2Part (models.Model): machine = models.ForeignKey(Machine,db_column='machineId') part = models.ForeignKey(Part,db_column='partId') class Meta: db_table = "machine2part" class Machine2PartInline (admin.TabularInline): # fields = ['name'] model = Machine2Part class MachineAdmin (admin.ModelAdmin): inlines = [Machine2PartInline] admin.site.register(Machine, MachineAdmin) admin.site.register(Part) admin.site.register(Machine2Part) -
How should I test a database-driven Django CMS for 404 errors?
I have designed a basic content management system in Django that uses the database to track Article objects, then displays these Article objects on my website. Each Article uses template tags that I frequently update. Occasionally, I will accidentally break one or more articles on my site when I update a template tag. For example, if I change the required arguments for a template tag referenced by a given article, and forget to update the template tag code within that article, the article will break, resulting in a 404. I would like an easy way to ensure that all of my article pages are still working after I make an update to my template tags. Unfortunately, as far as I know, there's no easy way to test to ensure that all of my articles serve 200 status codes — other than combing through them manually. I've investigated the Django testing framework, but it doesn't seem to be the right solution to my problem. To automatically test all my articles for 404s, I'd need to duplicate the Articles table in my database and load it in as a fixture for my tests — and numerous people have warned me against cloning … -
Django RestFramework returning a precomputed json
Currently I have this: class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ( 'id', 'f0', 'f1', 'f2') And it returns something like this: { "count": 6242, "previous": null, "total_pages": 209, "results": [ { "id": 63915, "f0": "Some stuff" ..... }, { "id": 63916, "f0": "Some other stuff" ..... }.... ] } And this is good, but I noticed that serializing the data is actually quite expensive to do on the fly, so I would like to precompute it. So far I've managed to precompute it and store it in a jsonfield for my model, the problem is my API is now returning {'json_repersentation':{myold_response}} class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('json_representation',) My question is, is it possible to change it so that it simply returns the json contained within json_representation field without the "overhead" of {'json_representation':{id:0, f0:label...}} and instead just simply {id:0, f0:label...} -
Why Django crispy form hidden fields appear?
I have a model: class MyModel(models.Model): normal = models.CharField(null=True, blank=True, max_length=100) other = models.CharField(null=True, blank=True, max_length=100) hidden = models.CharField(null=True, blank=True, max_length=100) If I define a regular form without using exclude, the hidden field shows up on the UI after the submit button in the DOM (and UI): class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ('normal', 'hidden') def __init__(self, *args, **kwargs): super(MyModelForm, self).__init__(*args, **kwargs) self.helper = FormHelper(form=self) self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-10' self.helper.layout = Layout( 'normal', Hidden('hidden', 'hidden initial'), FormActions( Submit('save', 'Save', css_class='save-entry btn-success'), ) ) Now if I flip things around and assemble a basically equivalent form but using exclude, the hidden field doesn't appear (which is what we want). class MyModelForm(forms.ModelForm): class Meta: model = MyModel exclude = ('other',) def __init__(self, *args, **kwargs): super(MyModelForm, self).__init__(*args, **kwargs) self.helper = FormHelper(form=self) self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-10' self.helper.layout = Layout( 'normal', Hidden('hidden', 'hidden initial'), FormActions( Submit('save', 'Save', css_class='save-entry btn-success'), ) ) I cannot wrap my head around why is that happening. -
Django / WagtailCMS - get attribute (eg body text) of child page using get_context
I'm trying to access the body text of a child page in my Django / Wagtail CMS blog. I can return the child page title, but I don't know how to use that to get the rest of the child page attributes. The parent is IndexPage, and the child is IndexListSubPage. My model is: class IndexPage(Page): body = RichTextField(blank=True) feed_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), ImageChooserPanel('feed_image'), ] def get_context(self, request): context = super(IndexPage, self).get_context(request) context['sub_pages'] = self.get_children() return context class IndexListSubPage(Page): body = RichTextField(blank=True) feed_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), ImageChooserPanel('feed_image'), ] My template contains: {% for subpages in sub_pages %} {{ subpages }} {% endfor %} This returns the page title for the child page, but I also want other attributes, like the body text. Any ideas? -
How can I completely alter my Django database schema without losing any data?
I'm making some big changes to the schema of my database, but I don't want to lose any data in the process of migrating to the new schema. Let me provide a specific example. I currently have a class Person(models.Model), and each Person instance has a bunch of data associated with it like a name, age, etc. There are already many Person instances in my database. I now realize that I actually need two types of Person, a Student and a Teacher, and each of those types will have their own unique variables and methods. It seems to me that the best way to accomplish this is by making Person an abstract class and making Student and Teacher extend that class. Some of variables in Person currently only apply to Student, so I want to move those variables into the Student subclass. In general, how could I go about doing this migration without losing any data? I'm fairly new to Django, so I don't really know where to start except that I probably need to write some kind of custom script to be run with python manage.py. -
Django autocomplete from query db
I have problem with autocomplete an input field from db query. If I write something in the input field nothing happens. I didn't receive any errors from django prompt or browser console futhermore if I go to for example 127.0.0.0.1:8000/guess_booknames/?q=San it return back a page with JSON content so the "def guess_booknames" works good. Maybe it's wrong the query.html? models.py: class EbooksDBProfile(models.Model): bookname = models.CharField(max_length=200,blank=False,null=False) urls.py: url(r'^guess_booknames/$', guess_booknames,name='autocomplete book names'), views.py: def guess_booknames(request): if 'q' in request.GET: query = request.GET.get('q','') ebook_list_bookname=[] ebook_dict={} ebook_object=EbooksDBProfile.objects.all().filter(bookname__icontains=query) for p in ebook_object: ebook_list_bookname.append(p.bookname) ebook_dict['options']=ebook_list_bookname data=json.dumps(ebook_dict) return HttpResponse(data, content_type='application/json') return HttpResponse() query.html: <!DOCTYPE html> <html> <head> <script type="text/javascript" src="//code.jquery.com/jquery-3.0.0.min.js"></script> <script type="text/javascript" src="//netsh.pp.ua/upwork-demo/1/js/typeahead.js"></script> </head> <body> <input type="search" name="searched_item" id="searched_item" class="form-control" autocomplete="off" placeholder="Enter book name (eg. Head First Java)" style="max-width: 700px;width: 700px;color: threeddarkshadow;"> <script> $(document).ready(function($) { $('#searched_item').typeahead({ items:12, source: function (query, process) { return $.get('/guess_booknames/', { query: query }, function (data) { return process(data.options); }); }, minLength:3, autoSelect:false, highlighter: function (item) { var regex = new RegExp( '(' + this.query + ')', 'gi' ); return item.replace( regex, "<strong style='color:green;' >$1</strong>" ); }, }); }) </script> </body> </html> -
Django Rest Framework, ModelSerializers and custom fields validation
Using latest version of Django and DRF. I have a rather complex requirement I can't find a solution for. I'll try to simplify it. Let's say I have a model that has two fields. field_a and field_b I have a model serializer for it. I POST a request with its fields. The fields get validated with the model and then against my two functions validate_field_a and validate_field_b. All is well. Now I'dl like my POST request to include a field that is not within the model. let's call it field_c. I have a custom def create(self, validated_data): in my serializer which saves everything to the database. At that point. with regards to field_c I would like to: Custom Validate it. Require that it is mandatory for the whole request to succeed and if it's not, issue a "Field is required" error just like if I forgot to POST one of my required model fields. Have the chance to take field_c and save it onto a totally different unrelated Model's row in the db. I can't seem to get around that. If I add field_c to the fields meta - it throws an exception saying justifiably that field_c is not in … -
How to send a hashed password to DRF and get authenticated
I'm working on authenticating users in Django, and I know that Django keeps all the passwords hashed in the data base, so in order to secure the user credentials, I have to hash the password in my front end (Angular2) before sending it to my back end (Django rest framework). The problem is that I don't know if Django excepts hashed passwords or is he capable of comparing it to the existing one, and if so , can any one pin point me to the right way. any help is appreciated, thanks -
Image Management API using Django Rest Framework (ImproperlyConfigured Error)
I was learning about DRF and went through the tutorial, making a pastebin style snippets app. I wanted to make an Image management app, processing (list and detail) requests such as GET,PATCH,PUT,DELETE etc. I made some changes to process images files rather than text field, and ran the server. But on accessing the API through browser, following error was shown ImproperlyConfigured at /api/photo/ Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Request Method: GET Request URL: http://127.0.0.1:8000/api/photo/ Django Version: 1.10.7 Exception Type: ImproperlyConfigured Exception Value: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Exception Location: /home/dhruv/.virtualenvs/djangodev/lib/python3.5/site-packages/rest_framework/relations.py in to_representation, line 386 Python Executable: /home/dhruv/.virtualenvs/djangodev/bin/python Python Version: 3.5.2 Python Path: ['/home/dhruv/Assignment/ImageManagement', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/dhruv/.virtualenvs/djangodev/lib/python3.5/site-packages'] Server time: Tue, 9 May 2017 13:11:34 +0000 Error during template rendering In template /home/dhruv/.virtualenvs/djangodev/lib/python3.5/site-packages/rest_framework/templates/rest_framework/horizontal/select.html, error at line 15 Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related … -
Django how to add taggit tags to model within template
I have a Django app that has a list of companies, and when the user clicks on a company they are presented with all of the details of that company. Now I'm trying to add a tag feature so any use can add tags to the company which they'll also be able to search on. I've created the form and the template stuff, but now I'm stuck now on how to wire it into the View, specifically updating the Company model with the new tag(s). Forms.py class TagForm(forms.Form): tag = forms.CharField(label='Tag', max_length=100) class Meta: model = Company field = 'tag' Template <div class="add-tag-form"> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default btn-sm">Add</button> </form> </div> View class CompanyDetails(generic.DetailView): model = Company template_name = 'company_details.html' # This was my attempt to work it into the View... def post(self, request, *args, **kwargs): form = TagForm(request.POST) if form.is_valid(): tag = form.save(commit=False) tag.company = Company.objects.get(pk=pk) tag.save() def get_context_data(self, **kwargs): pk = self.kwargs.get('pk') context = super(CompanyDetails, self).get_context_data(**kwargs) context['articles'] = Articles.objects.filter(company_id=pk).order_by('-date') context['transcripts'] = Transcripts.objects.filter(company_id=pk).order_by('-date') context['form'] = TagForm() # Yahoo Finance API data stock_symbol = self.object.stock_symbol data = Share(stock_symbol) stock_open = data.get_open() year_range = data.get_year_range() fifty_day_moving_average = data.get_50day_moving_avg() market_cap = data.get_market_cap() yahoo_finance = … -
Microsoft Azure Django Python setup error Pillow
All sorta new to using Microsoft Azure and needed help deploying a Django App to it. When I push the code from my local repo to Azure it gives me this log. I noticed it says : The headers or library files could not be found for zlib, a required dependency when compiling Pillow from source. Please see the install instructions at https://pillow.readthedocs.io/en/latest/installation.html I did more reading and learnt that Azure cannot install PIL or Pillow from the environment and hence needs to be installed on my system and then uploaded to Azure. I included a file called ".skipPythonDeployment" so that it doesn't erase the environment set on my local system, but then the deployment would fail again. The important part of the Log generated while Pushing the code to Azure is attached below. Detected requirements.txt. You can skip Python specific steps with a .skipPythonDeployment file. Detecting Python runtime from site configuration Detected python-2.7 Deleting incompatible virtual environment. ............................................................ Creating python-2.7 virtual environment. Downloading/unpacking pillow (from -r requirements.txt (line 4)) .... Running setup.py (path:D:\home\site\wwwroot\env\build\pillow\setup.py) egg_info for package pillow Single threaded build for windows warning: no files found matching '.sh' no previously-included directories found matching 'docs_static' warning: no previously-included files found … -
Django: form.field within choicefield
How would one even start to implement something like this with a django form: CHOICES = ( ('a','a',forms.IntegerField()), ('b','b',forms.IntegerField() ) class AForm(forms.Form): choice = forms.CharField(choices=CHOICES) bit of background: trying to convert a ModelMultipleChoiceField into a custom formfield that displays the model and an additional input per object (that is used to select basically quantity) Trying to go through the source of ChoiceField https://docs.djangoproject.com/en/1.11/ref/forms/fields/#choicefield but i can't work out where i even begin to add the new field (and retrieve it after POST!)