Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django responsive rows with images
Suppose you have a bunch of images that you want to display using Django and Bootstrap/MaterializeCSS. The rule goes like this: Mobile: 2 images per row Tablets: 3 images per row Desktop: 4 images per row How would you design a loop that chooses at which point to create a new row (given a device type) and puts images into their corresponding rows? -
Caching a pandas dataframe in Heroku
I use pandas in my Django app running on Heroku using Heroku Postgres. I have a reporting page, where I create a dataframe by reading a number of db tables and performing calculations on it. The resulting dataframe has about 100000 rows and 70 columns. I then run a pivot on the dataframe to summarise the data based on user input. If the user wants to summarise (pivot) the data by another field, I then have to recalculate the entire dataframe which can take up to 10 seconds. To solve this I want to cache the dataframe so that I can quickly run the updated pivot on it and was wondering what my best options are here? Create a temp table in the database to store the results (unsure how to do this with Django - will probably have to drop down to raw sql) Save the results using redis Cache (I think this is the way to go but also unsure how to do this) Save data in a S3 bucket (I know how to do this, but I'm sure there are better ways) Something else? Feather/HDF store -
django rest framework: prefetch an initial data in serializer
I know that django has select_related and prefetch_related that can be used when querying items from database to increase its performance, and it can be used in pair with django rest framework's nested serializer. However, the problem come when I want to use the serializer to create my model for example: class CompanySerializer(serializer.serializers): employee_set = serializers.JSONField() class Meta: model = Company fields = ('id', 'employee_set') def create(self, validated_data): employee_set = validated_data.pop('employee_set') for employee in employee_set: serializer = EmployeeSerializer(data=employee) serializer.is_valid(raise_exception=True) serializer.save() class EmployeeSerializer(serializer.serializers): card = serializers.PrimaryKeyRelatedField(queryset=Card.objects.all()) class Meta: model = Employee fields = ('id', 'name', 'card') def validate(self, obj): if card.employee_set.all().count() > 3: raise serializers.ValidationError({'_error': 'invalid}) return data For example, I want to create a company with multiple employee like: request.POST: { employee_set: [ { name: 'tim', card: 1 }, { name: 'bob', card: 1 }, { name: 'jimmy', card: 2}, ] } then I can use CompanySerializer(request.POST), right? However, when I am saving this serializer, the EmployeeSerializer will iterate over each employee and query employee.card_set, which result in a lot of sql queries. Is there any way to do it similar like prefetch_related? thanks -
How to create django forms custom field
I'm trying to create custom field for arrays of strings for Django Forms but got exception I can't handle. So, according to documentation: Creating custom fields If the built-in Field classes don’t meet your needs, you can easily create custom Field classes. To do this, just create a subclass of django.forms.Field. Its only requirements are that it implement a clean() method and that its init() method accept the core arguments mentioned above (required, label, initial, widget, help_text). I've created class: class ArrayField(forms.Field): def __init__(self, required=False, initial=[], widget=None, help_text='', label=''): self.validators = [check_if_array, check_if_array_contains_str] super().__init__(required=required, initial=initial, widget=widget, help_text=help_text, label=label) def clean(self, value): return super().clean(value) Created form using created class: class MyForm(forms.Form): my_field = forms.ArrayField() And when I'm trying to use it f = MyForm({['str1', 'str2']}) f.is_valid() I've got an exception: File "C:\Dev\env\lib\site-packages\django\forms\forms.py", line 179, in is_valid return self.is_bound and not self.errors File "C:\Dev\env\lib\site-packages\django\forms\forms.py", line 174, in errors self.full_clean() File "C:\Dev\env\lib\site-packages\django\forms\forms.py", line 376, in full_clean self._clean_fields() File "C:\Dev\env\lib\site-packages\django\forms\forms.py", line 394, in _clean_fields value = field.clean(value) File "C:\Dev\env\lib\site-packages\django\forms\fields.py", line 148, in clean value = self.to_python(value) File "C:\Dev\env\lib\site-packages\django\forms\fields.py", line 432, in to_python return super().to_python(value) File "C:\Dev\env\lib\site-packages\django\forms\fields.py", line 379, in to_python value = value.strip() AttributeError: 'int' object has no attribute 'strip' I suppose answer is … -
Template Tag if statement having issues with arguments given
I made a template tag to show the current user if they have any unread notifications in the base template. I think that I need to pass in two arguments - one to establish that we are only showing notifications for the current user (using filter to do this), and the second to return if there are any unread notifications (also using filter for this). However, I am getting an error saying that I can only pass through one argument even though I need two. Here if my template tag: @register.simple_tag(name='notseen') def notseen(): if UserNotification.objects.filter(toUser=User) and UserNotification.objects.filter(read=False).exists(): print("True") return True else: print("False") return False Here is the Traceback: Traceback (most recent call last): File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 215, in _get_response response = response.render() File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/response.py", line 107, in render self.content = self.rendered_content File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/response.py", line 84, in rendered_content content = template.render(context, self._request) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/backends/django.py", line 66, in render return self.template.render(context) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 207, in render return self._render(context) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 957, in render_annotated return … -
invalid block tag on line 11: 'end', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?
i have attached the screenshot of my code, i am not getting what error is actually,tried various things but then also not able to solve it -
Django static files, CSS working but not Javascript
After 4 days of research and readiing every related post in here, still can't make it works, django integrated develppment server (migrate.py runserver) won't use javascript external file, but CSS extrnal files working.. (i don't have "not found" (404) error for the javascript file so i think django found the file but..) i have this in my settings.py # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 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', 'search', ] 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 = 'swaps.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 = 'swaps.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = … -
hashed DB password for DJango
I am working with DJango. When doing the setup, the DB password is displayed in clear text. I saw this below on how to come about that problem: mysql password in django but it seems to move the problem to the environment variable. Is there some way a kind of hashed key can be used instead? TIA -
selection value is lost in mobile devices not in laptop after location.reload()
in a django form i use "modelchoicefields" and querysets. Using javascript and ajax selections change dynamically. this works perfect in laptops however in mobile devices although there is no programatic error selected fields disappear after window.location.reload().. what should be done to make it work in mobile devices as well. note: i made tests through android only... <script> function prosecFunction() { var response = ''; var selected = document.getElementById("id_proje").value; console.log(selected); $.ajax({ url : "demirbas_ariza_listesi/", type : "GET", dataType: "text", data : { 'selected' : selected, }, success: function() { window.location.reload(); }, failure: function() { alert("hata var....veri aktarılamadı..."); } }); /* ajax kapa...*/ } </script> `[above is the laptop view, below is the mobie view` `][1] [1]: https://i.stack.imgur.com/iBxdn.jpg -
Django - How can I prevent access to other users' objects?
Let's assume that I have such URL users/{id}/objects and I am authenticated as a User with ID equals 1. At the moment I can access objects of users with ID equals 2, 3 etc. Does anyone have an idea how can I prevent this? class UserObject(GenericAPIView): permission_classes = [GetPermission] def get(self, request, user_id): try: object = Object.objects.filter(user=user_id) except Object.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = ObjectSerializer(object, many=True) return Response(serializer.data) class GetPermission(permissions.BasePermission): def has_permission(self, request, view): if request.method =='GET' or (request.user and request.user.is_authenticated() and request.user.is_superuser): return True return False -
Unix timestamp to Python DateTime
I am getting the following runtime warning while trying to pass stripe's unix epoch time returned on a webhook to python datetime for my model. Most of the answers focus on using timezone.now() on object creation but I need to parse future dates. Completely getting nowhere with this any pointers would be great! RuntimeWarning: DateTimeField Subscription.current_period_end received a naive datetime (2017-12-14 16:47:03) while time zone support is active. current_period_start = datetime.datetime.utcfromtimestamp(current_period_start).strftime('%Y-%m-%d %H:%M:%S') print(current_period_start) -
POST Request Not sent on button press
Hello I have the following template, which I'm wanting to send a POST request to activate the ajax to save the selections of the multiple check boxes. When I view the console it shows a GET request when the user pushes the button, why is this? <form action=""> <div class = "container"> <div class="jumbotron"> <div class="container"> <h1 class="jumbotron-heading">Available Application List</h1></br> </div> <div class="container"> <div class="row"> <div class="col"> <h3>Financial</h3> <ul> {% for app in fingrouplist %} <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" > {{ app.report_name_sc }}</li> {% endfor %} </ul> </div> <div class="col"> <h3>Care Assure</h3> <div class = "row"> <ul> {% for app in cagrouplist %} <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" > {{ app.report_name_sc }}</li> {% endfor %} </ul> </div> <div class = "row"> <h3>Performance Improvement</h3> <ul> {% for app in pigrouplist %} <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" > {{ app.report_name_sc }}</li> {% endfor %} </ul> </div> <div class = "row"> <h3>Supply Chain</h3> <ul> {% for app in scgrouplist %} <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" > {{ app.report_name_sc }}</li> {% endfor %} </ul> </div> <div class = "row"> <h3>DSS Monitoring</h3> <ul> {% for app in dssgrouplist %} <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" > {{ app.report_name_sc }}</li> {% endfor %} </ul> </div> <div … -
Celery and Rabbit MQ Django
I installed Celery and RabbitMQ with commands: pip install celery and sudo apt-get install rabbitmq And Celery don't work i have an error: Traceback (most recent call last): File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/app/utils.py", line 361, in find_app found = sym.app AttributeError: module 'myshop' has no attribute 'app' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/morilon/dj/shop/bin/celery", line 11, in sys.exit(main()) File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/main.py", line 14, in main _main() File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/celery.py", line 326, in main cmd.execute_from_commandline(argv) File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/celery.py", line 488, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/base.py", line 279, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/base.py", line 481, in setup_app_from_commandline self.app = self.find_app(app) File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/base.py", line 503, in find_app return find_app(app, symbol_by_name=self.symbol_by_name) File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/app/utils.py", line 366, in find_app found = sym.celery AttributeError: module 'myshop' has no attribute 'celery' I don't understand what to do with this? -
TypeError at /image/ expected string or Unicode object, InMemoryUploadedFile found
hi I have build a image processing classifier and In this code I am making an api which takes the input image form key 'test_image' and predicts the class of the image but cv2.imread giving me this error (TypeError at /image/ expected string or Unicode object, InMemoryUploadedFile found) i know that cv2.imread takes only url of the image but i dont know how to resolve this My code def classify_image(request): if request.method == 'POST' and request.FILES['test_image']: test_image = request.FILES['test_image'] test_image = cv2.imread(test_image) test_image = cv2.resize(test_image, (128, 128)) test_image = np.array(test_image) test_image = test_image.astype('float32') test_image /= 255 print(test_image.shape) test_image = np.expand_dims(test_image, axis=0) pred = model.predict_classes(test_image) print(pred) return JsonResponse(pred, safe=False) -
django admin Model edit form - How to filter foreignkeys to only related models
I have an account model in django which has a foreignkey to Payment and a onetoone to Address. In the Account section in the admin, I can edit a specific model and edit the fields payment and address via a select widget. However how can I filter the options so that it only shows related models. (ie not every address or payment from every user, only the ones from that user). The RelatedOnlyFieldListFilter seems to only apply to the model list view. Is there a way to use this in the model edit view? -
Django-wkhtmltopdf stops working after some time
I'm using django-wkhtmltopdf to render some documents and it works pretty well. But after some idle time Apache simply stops returning those PDFs and simply timeouts without any errors I already tried different PDF packages, but always come back to this same problem. The System is Debian 3.2.0-4-amd64 using Apache2, Django version 1.11 and Python 2.7.3. Here is the view.py: if os.name == "nt": path_wkthmltopdf = r"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe" config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf) else: config = pdfkit.configuration() from wkhtmltopdf.views import PDFTemplateResponse class PDFView(DetailView): template='billing/receipt_detail.html' model = Receipt not_download_flag = None context= {'title': '' } #receipt_for_task = ReceiptForTask.objects.get(pk=self.kwargs['pk']) def get(self, request, *args, **kwargs): receipt = self.get_object() #receipt_for_task = receipt.receipt_for_task self.context['object'] = receipt self.context['title'] = "rechnung-"+str(receipt.number)+"-"+str(receipt.client.slug)+".pdf" response=PDFTemplateResponse(request=request, template=self.template, filename ="rechnung-"+str(receipt.number)+"-"+str(receipt.client.slug)+".pdf", context=self.context, show_content_in_browser=self.not_download_flag, cmd_options={'margin-top': 0,} ) return response How can I approach this problem to find out what's wrong? None of the apache logs I could find did show any errors. I know this question is a bit vague, but I'm very grateful for your help. -
Django & ajax like button only works in first item
good morning, I just got a problem with my like button, it's only working on the first item and it does not work on the others This is my views.py @login_required @require_POST def like(request): if request.method == 'POST': user = request.user slug = request.POST.get('slug', None) tweet = get_object_or_404(Tweet, slug=slug) if tweet.likes.filter(id=user.id).exists(): tweet.likes.remove(user) message = 'Your disliked this' else: tweet.likes.add(user) message = 'You liked this' ctx = {'likes_count': tweet.total_likes, 'message':message} return HttpResponse(json.dumps(ctx), content_type='application/json') When I click in the like button on the first item this works fine but, when I click like button in the other items this not works. My models.py class Tweet(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField('Titulo', max_length=100) text = models.CharField(max_length=160) slug = models.SlugField(max_length=180) likes = models.ManyToManyField(User, related_name='likes') created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) @property def total_likes(self): return self.likes.count() and this is my scrip ajax: <script type="text/javascript"> $("#like-button").click(function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: "/like/", data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{csrf_token}}'}, dataType: "json", success: function(response){ alert("This tweet has " + response.likes_count); }, error: function(rs, r){ alert(rs.responseText); } }); }); </script> My html button: <input type="button" id="like-button" name="{{tweet.slug}}" value="Like {{tweet.total_likes}}" class="btn btn-primary"> -
django rest framework write only field usage
I just want to know usage of write_only that is option password1,2 fields below I checked view returns fileds information without password, so i could understand roughly but cannot find what exactly write_onlyoptions usage is. please somebody explain or leave reference document link.. class SignupSerializer(serializers.ModelSerializer): password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) token = serializers.SerializerMethodField() class Meta: model = User fields = ( 'username', 'password1', 'password2', ) this is view class Signup(APIView): def post(self, request): serializer = SignupSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Error: no "view" mailcap rules found for type "application/pdf" pythonanywhere server logs
Am trying to Use lolviz and graphviz to visualize data structures but there is no output this is the error i get in Server log: groupn.pythonanywhere.com.server.log Warning: 2017-11-14 16:32:24 Illegal attribute sides in - ignored 2017-11-14 16:32:24 Warning: 2017-11-14 16:32:24 Illegal attribute sides in - ignored 2017-11-14 16:32:24 in label of node node140165832004944 2017-11-14 16:32:24 Warning: 2017-11-14 16:32:24 Illegal attribute sides in - ignored 2017-11-14 16:32:24 in label of node node140165832024136 2017-11-14 16:32:24 Error: no "view" mailcap rules found for type "application/pdf" 2017-11-14 16:32:24 /usr/bin/xdg-open: 461: /usr/bin/xdg-open: 2017-11-14 16:32:24 links2: not found this is where the function is in my views.py elif 'show' in request.POST: data = callviz(s).view(filename=None, directory=None, cleanup=True) return render(request, 'file/stacks.html', {'form': form, 'data': data}) -
Where should I store a client_secret key in Django?
I have built an Android app with a Django REST backend, using django-rest-social-auth (Oauth2). Everything works fine but I am wondering where/how should I store the client_secret key, used for the first call to convert my user_token (or username/password if logged by credentials) to an access_token that will be used in all the next calls. Indeed, I have read that it cannot be stored within my Android app as it can be decompiled. Thus, I store it on my server and retrieve the right client_secret according to the incoming client_id. But I do not know if it is the classical way to handle it. -
How to create a link with parameter in django
Hi I am trying to create a link with paremeter but I am getting an error (Page not found) template {% for color in palette_dominant_color %} <a href="{% url 'brandcolors:hexcode' color %}" style="text-decoration:none;color:inherit"> {{color}} </a> <br> {% endfor %} urls.py url(r'^hexcode/(?P<color>\w)/$', ThemeView.as_view(), name="hexcode"), views.py class ThemeView(TemplateView): template_name='fabric/theme.html' def get_context_data(self, **kwargs): context = super(ThemeView, self).get_context_data(**kwargs) colors = Color.objects.filter(color=kwargs['color']).all() return context -
ValueError: Variable rnn/basic_rnn_cell/kernel already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope?
Any ideas how can I solve problem shown below? With the information that I found on the web it is associated with problem of reusing tensorflow scope however nothing works. ValueError: Variable rnn/basic_rnn_cell/kernel already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? Originally defined at: File "/code/backend/management/commands/RNN.py", line 370, in predict states_series, current_state = tf.nn.dynamic_rnn(cell=cell, inputs=batchX_placeholder, dtype=tf.float32) File "/code/backend/management/commands/RNN.py", line 499, in Command predict("string") File "/code/backend/management/commands/RNN.py", line 12, in <module> class Command(BaseCommand): I tried for instance something like this with tf.variable_scope('scope'): states_series, current_state = tf.nn.dynamic_rnn(cell=cell, inputs=batchX_placeholder, dtype=tf.float32) and this with tf.variable_scope('scope', reuse = True ): states_series, current_state = tf.nn.dynamic_rnn(cell=cell, inputs=batchX_placeholder, dtype=tf.float32) and this with tf.variable_scope('scope', reuse = tf.AUTO_REUSE ): states_series, current_state = tf.nn.dynamic_rnn(cell=cell, inputs=batchX_placeholder, dtype=tf.float32) Any ideas? -
Django - collecting info per request
I want to collect data in each request (single request can cause several changes), and process the data at the end of the request. So I'm using a singleton class to collect the data, and I'm processing the data in it on 'request_finished' signal. Should it work or should I expect data loss/other issues? singleton class: class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class DataManager(object, metaclass=Singleton): .... using it in other signal: item_created = NotificationManager().ItemCreated(item) NotificationManager().add_event_to_list(item_created) request finished signal: @receiver(request_finished, dispatch_uid="request_finished") def my_request_finished_handler(sender, **kwargs): NotificationManager().process_data() -
How to render bootstrap admin template in django?
I have this admin panel template and I want to use it in my django web application. I know I will have to modify the template using template tags but is that all? What all changes will I have to make. I am fairly new to django and front end development. -
Django: loosing form attribute when changing <select> options in form template
In my Django application, a template which displays the manually the form fields from a Model. In this template I have a few fields which are and the options are set in my forms.py. One of the option is a tuple ('new','New...') and when it is selected a pop up windows appears (Bootstrap Modal) and the user can add an option which is added to the choices of the select. But when the form is submited, I have an error as the form key for this field is missing: KeyError: 'country', and if I print the form, country key is absent: {'genotype': '?', 'complete_genome': False, 'seq_tech': '?', 'isolation_source': 'te', 'mol_type': '?', 'NT_seq': 'TTG', 'source': '?', 'host': 'chicken', 'species': 'A', 'isolate': 'te1', 'sourceLink': '', 'subtyping_ref': '?', 'PK_idSequence': 'test', 'strain': 'te1_strain', 'comment': '', 'subtype': '?'} My forms.py: UNKNOWN_START_LIST = [('?','?')] NEW_END_LIST = [('new','New...')] class SequenceForm(ModelForm): # create the form fields PK_idSequence = CharField(max_length=15, label='Sequence ID') # get the existing country values in the database tmpCountries = sorted(list(set([seq.country for seq in Sequence.objects.all() if seq.country is not None and seq.country != '?']))) countryChoices = UNKNOWN_START_LIST + [(tmpCountry, tmpCountry) for tmpCountry in tmpCountries] + NEW_END_LIST # the countryChoices will be [('?', '?'), ('France', 'France'), ('Germany', …