Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error 10002 - Security header is not valid
I have a question for the above error. I understand this happens when information entered in the .env is wrong. However, I have checked. Deleted, started again. There seem to be a problem that the details entered is not being passover. So in my log it says - PWD: None RETURNURL: http://localhost:8000/en-gb/checkout/paypal/preview/8/ SIGNATURE: None USER: None VERSION: 119 DEBUG 2017-04-27 20:33:12,404 gateway 6804 4513112064 Response with params: ACK: Failure BUILD: 32996991 CORRELATIONID: 1762ae0537774 L_ERRORCODE0: 10002 L_LONGMESSAGE0: Security header is not valid L_SEVERITYCODE0: Error L_SHORTMESSAGE0: Security error Here are me .env #PAYPAL SETTINGS export PAYPAL_API_USERNAME=mypaypalusername.com export PAYPAL_API_PASSWORD=my_password export PAYPAL_API_SIGNATURE=my_signature. in my settings import paypalrestsdk #PAYPAL SETTINGS PAYPAL_API_USERNAME=os.environ.get("PAYPAL_API_USERNAME") PAYPAL_API_PASSWORD=os.environ.get("PAYPAL_API_PASSWORD") PAYPAL_API_SIGNATURE=os.environ.get("PAYPAL_API_SIGNATURE") Any reasons why the above settings is not picking data from my .env and passing it over? I am still in the sandbox testing. Thanking you in advance. -
Force the creation of a new object
Knowing that it is possible to access the name of the customer for a certain loan with In [17]: loan_test = Loan.objects.get(pk=1) In [18]: loan_test.request.customer Out[18]: <CustomerProfile: Randy Senger's customer profile> I would like to force the creation of a loan for a certain customer. Here, we could take in example the customer Randy Senger (with id=207). I am clearly not an expert with Django. I thought I could do such thing with Loan.objects.get_or_create(pk=19).request.customer(pk=1), but clearly it is not working. Could anyone be able to give me a bit of help at this point? -
Django: Celery can't find my app
ModuleNotFoundError: No module named 'myapp' I'm not really understanding what the problem is here. There are no issues with my app, but celery can't seem to find it no matter what I try and change. Here is my directory structure: django / mysite __init__.py celery.py settings.py urls.py wsgi.py / myapp admin.py apps.py models.py tasks.py urls.py views.py manage.py Command: celery -A myapp worker -l info -
Django request.user.id is None
I have a pretty simple problem. I have a class that is extending APIView in order to pass in a Json Response to a URL which will be used as an API. I'm trying to filter data from a model so that I only get data items which belong to the current user. Because of this, I'm trying to access request.user.id to set my filter with. From my views.py, here is a snippet of the code I am using: class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): print(request.user.id) When I go to the url associated with this class, the print statement returns None, as if the user does not exist. However, in the same views.py file I have another method (not inside any class) set up as the following: @login_required def LogDisplay(request): print(request.user.id) However, when I go to the url associated with this method, I get an integer as an output on my console. How can I make it so that my first method has access to the current user as well? -
Issues in the Mysql DB encoding and string matcing
i have a chatbot application with two MySql DBs: db for the django backend. chatbot_brain for the chatbot background knowledge. Basically, when the user start the conversation: the chatbot.py gets the input using model's value_list() stretch for a matching input in chatbot_brain update with the replay using model. This is the code for chatbot.py: # initialize the connection to the database conn = pymysql.connect("**","**","**","chatbot_brain") cursor = conn.cursor() conn.text_factory = str def run_conversation_male(): last_B = chat.objects.values_list('chatbot_response', flat=True).latest('id') H = chat.objects.values_list('user_iput', flat=True).latest('id') New_H= ' '.join(PreProcess_text(H[0])) cursor.execute("SELECT respoce FROM Male_Conversation_Engine WHERE request LIKE %s", (H[0],)) reply = cursor.fetchone() ID = chat.objects.values_list('id', flat=True).latest('id') chat.objects.filter(id=ID).update(chatbot_response= reply[0]) i have two issues: one, is when i try to find the matching string using LIKE query, it produce this EROR message: -- UnicodeEncodeError:'latin-1' codec can't encode character-- I have tried many solutions such as: 1. using (charset='utf8') in the connection but it made the website very slow after i restart the server.it seems to solve the problem but it could find the matching string (and i’m sure that the string is in the DB) 2. cursor.execute("set names 'utf8'") Second, when i try to write the conversation in CSV file i got these symbols "ØŸ ØŸ" Also, i checked … -
json as DB for Django
I am new To Django and just want to know if it is possible to give Django a json file instead of creating DB or models. Bassicaly I have json with info that should appear in front end. and it can be updated frequently. So I just want to know, is it possible to check in somewhere that json - as DB for django. and in views.py just parse that json and create elements? Will that work? Or I should create models for each element from json? And update/migrate each time models/db? I hope I have managed to ask a right question. -
Select a valid choice. That choice is not one of the available choices
Following is my code. models.py class Order(models.Model): profile = models.ForeignKey(Profile) lunch = models.ForeignKey(Lunch, blank=True, null=True) class Lunch(models.Model): title = models.CharField(max_length=120, blank=True, null=True) price = models.DecimalField(max_digits=6, blank=True, null=True, decimal_places=2) views.py @login_required def order_edit(request, id=None): if not request.user.is_authenticated: raise Http404 members = Member.objects.all() order, created = Order.objects.get_or_create(profile=Profile.objects.get(user=request.user)) form = OrderForm(request.POST or None, request.FILES or None, instance=order) if form.is_valid(): instance = form.save(commit=False) instance.save() # messages.success(request, "<a href='#'>Item</a> Saved", extra_tags='html_safe') return HttpResponseRedirect(instance.get_absolute_url()) context = { # "instance": instance, "form":form, 'members': members } return render(request, "profiles/order_form.html", context) forms.py class OrderForm(forms.ModelForm): lunch = forms.ModelChoiceField( label='Lunch', queryset=Lunch.objects.all(), widget=forms.CheckboxSelectMultiple, empty_label=None, required=False, ) class Meta: model = Order fields = [ 'lunch', ] html <form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %} <div class="col-sm-6">{{ form.lunch| as_crispy_field }}</div> I removed the foreignkey and given choices to the model and in in forms used forms.MultiplechoiceField, but still getting the same error. What went wrong, hope somebody can help, Thank you. -
Correct way to install in to virtual ebnvironment (django-import-export package)
I am deploying my site - I have it mostly set up but I notice that when I pip install some of the packages they don't seem to have installed correctly - for instance: django-import-export Package CORRECT WAY - Resulting directory installed locally to C:\Python34\Lib\site-packages w/ no problem: django_import_export-0.5.1.dist-info INCORRECT WAY? - when installed in to virtenv - the resulting directory is django_import_export-0.5.1-py3.4.egg-info Another package - openpyxl did this as well openpyxl-2.4.7-py3.4.egg-info What - if anything - am I doing wrong? Note that other packages installed w/ pip in to the virtenv work just fine (psycopg2 for instance) Thank you in advance... -
Why 2 tracebacks every time I restart celery after upgrading to version 4?
After upgrading a django-celery project to the latest version of both, everytime I restart celery I get the following errors (ultimately celery seems to start correct, but why these 2 tracebacks first every time?) 017-04-27 18:06:28,815: WARNING/MainProcess] consumer: Connection to broker lost. Trying to re-establish the connection... Traceback (most recent call last): File "/home/bob/Desktop/pyco/evo-scrape/venv/local/lib/python2.7/site-packages/celery/worker/consumer/consumer.py", line 318, in start blueprint.start(self) File "/home/bob/Desktop/pyco/evo-scrape/venv/local/lib/python2.7/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/home/bob/Desktop/pyco/evo-scrape/venv/local/lib/python2.7/site-packages/celery/worker/consumer/mingle.py", line 38, in start self.sync(c) File "/home/bob/Desktop/pyco/evo-scrape/venv/local/lib/python2.7/site-packages/celery/worker/consumer/mingle.py", line 42, in sync replies = self.send_hello(c) File "/home/bob/Desktop/pyco/evo-scrape/venv/local/lib/python2.7/site-packages/celery/worker/consumer/mingle.py", line 55, in send_hello replies = inspect.hello(c.hostname, our_revoked._data) or {} File "/home/bob/Desktop/pyco/evo-scrape/venv/local/lib/python2.7/site-packages/celery/app/control.py", line 129, in hello return self._request('hello', from_node=from_node, revoked=revoked) File "/home/bob/Desktop/pyco/evo-scrape/venv/local/lib/python2.7/site-packages/celery/app/control.py", line 81, in _request timeout=self.timeout, reply=True, File "/home/bob/Desktop/pyco/evo-scrape/venv/local/lib/python2.7/site-packages/celery/app/control.py", line 436, in broadcast limit, callback, channel=channel, File "/home/bob/Desktop/pyco/evo-scrape/venv/local/lib/python2.7/site-packages/kombu/pidbox.py", line 315, in _broadcast serializer=serializer) File "/home/bob/Desktop/pyco/evo-scrape/venv/local/lib/python2.7/site-packages/kombu/pidbox.py", line 290, in _publish serializer=serializer, File "/home/bob/Desktop/pyco/evo-scrape/venv/local/lib/python2.7/site-packages/kombu/messaging.py", line 181, in publish exchange_name, declare, File "/home/bob/Desktop/pyco/evo-scrape/venv/local/lib/python2.7/site-packages/kombu/messaging.py", line 203, in _publish mandatory=mandatory, immediate=immediate, File "/home/bob/Desktop/pyco/evo-scrape/venv/local/lib/python2.7/site-packages/amqp/channel.py", line 1748, in _basic_publish (0, exchange, routing_key, mandatory, immediate), msg File "/home/bob/Desktop/pyco/evo-scrape/venv/local/lib/python2.7/site-packages/amqp/abstract_channel.py", line 64, in send_method conn.frame_writer(1, self.channel_id, sig, args, content) File "/home/bob/Desktop/pyco/evo-scrape/venv/local/lib/python2.7/site-packages/amqp/method_framing.py", line 174, in write_frame write(view[:offset]) File "/home/bob/Desktop/pyco/evo-scrape/venv/local/lib/python2.7/site-packages/amqp/transport.py", line 269, in write self._write(s) File "/usr/lib/python2.7/socket.py", line 228, in meth return getattr(self._sock,name)(*args) error: [Errno 104] Connection … -
Django Multiple upload files compressed on one zip
Im trying to generate a Zip file with all the Temporary Uploaded files (Pdb) data [<TemporaryUploadedFile: Screensho.png (image/png)>, <TemporaryUploadedFile: Screenshot2.png (image/png)>, <TemporaryUploadedFile: Petzl.pdf (application/pdf)>] To allow my form upload more that one file im Using from multiupload.fields import MultiFileField MultiFileField I just want to create a zip file with all the uploaded files import zipfile for each_file in data: my_zip = zipfile.ZipFile('Python.zip', 'w') my_zip.write(each_file.read()) *** TypeError: stat() argument 1 must be encoded string without null bytes, not str my_zip.write(each_file) *** TypeError: coercing to Unicode: need string or buffer, TemporaryUploadedFile found my_zip.write(each_file.file) *** TypeError: coercing to Unicode: need string or buffer, instance found STORAGE_FS.save(my_zip) how shall i handle the TemporaryUploadedFile to be as valid entry for the zip? -
Best way to integrate Front-end/Android/iOS with Django app?
I have created a Django app and wanted it to communicate with all platforms like Web/Android/iOS etc. So what is the best way to do it? I am mainly concerned about authenticating users, registering them and logging them in. What should be the best practice? DRF? or normal views which return JSON response? An example/explanation for registering and logging the user in would be really appreciated. -
Schema migration commit changes
I have the following situation: more than one schema migration one data migration It would be simple enough but I encountered a problem with the data migration. It sends a query for a specific ContentType which I need for django-taggit. The problem is that the model I want to query didn't exist until the migration that preceded it. That errors out with an empty result from that query. However, when I run all migrations up to the data migration and then I run the data migration itself, everything works well. I've noticed that a migration process doesn't save changes until all of the migrations are finished which doesn't work for this. One of the solutions I got to was to manually commit/save changes to the database however I haven't been able to find a way to do it. Of course, if there are any other ideas/better solution I'd be happy to hear them. This is the code where the data migration errors out: # ChallengeContest ContentType challenge_contest_ct = ContentType.objects.get(model='challengecontest') As you can see the model challengecontest is the one that was created in a migration preceeding data migration. -
How to describe parameters in DRF Docs
I'm using Django REST Framework v3.6 built-in interactive documentation django_rest_framework.documentation (not django-rest-swagger). Basically, I'm following the official documentation and use this in my URLset configuration: from rest_framework.documentation import include_docs_urls urlpatterns = [ url(r"^", include_docs_urls(title="My API")), ... ] Everything seems to work and I get a nice interactive documentation page, but I have a ViewSet with lookup_field = "slug" and one thing about the generated documentation bothers me: I want to have some useful information it that description, like "an unique permanently-assigned alphanumeric ID" or something among those lines, but can't find any documentation where this data comes from. There is a workaround but I really don't want to define all the schema explicitly. I want to declare my classes with nice docstrings and have docs auto-generated. I've also found an suggestion to put slug -- here goes the description in the docstring but it doesn't seem work - the text just appears with the rest of the Markdown-formatted description. So... I wonder about two things: (A specific question) Where do I fill this path parameter description? (More generic version of the same question) What's the best way to learn how schemas are auto-generated from code? -
python (django) regex limit result not working
The spec is all characters except white-space and capitalized characters. Here is the regex validator on the model: path = models.CharField(max_length=150, help_text="/blog/posts/...", unique=True, validators=[ RegexValidator(regex='(^[a-z0-9-:!@#$%^&*(){}\\?<>,.;\'"`~|/]+){1}', message="Lowercase with no whitespace allowed") ]) Here is the unit test: def test_path_regex(self): with self.assertRaises(ValidationError): post = Post(title="bad regex", path="Super-2Test-2", slug="special") if post.full_clean(): post.save() with self.assertRaises(ValidationError): post = Post(title="bad regex", path="super-2test 2", slug="special") if post.full_clean(): post.save() self.assertEqual(Post.objects.filter(title="bad regex").count(), 0) Result: line 27, in test_path_regex post.save() AssertionError: ValidationError not raised FAILED (failures=1) the reason for this seems to be that the RegexValidator is not flagging text if it can match part of the string and {1} is not helping. As you can see from this link: http://pythex.org/ Please help. Thanks. -
Bootstrap help-block and Django registration form help_text
I am using the django.contrib.auth registration form and trying to get the help text to display consistently for all fields using Bootstrap. I am using the following code in my Django template for the help text as part of a for loop on the form: <p class="help-block">{{ field.help_text }}</p> This works fine apart from the help text for the password field where it displays with the html tags: password field help with tags To prevent this I changed the code above to: <p class="help-block">{{ field.help_text|safe }}</p> But now the help text is not being formatted by Bootstrap, I guess because of the html inside the paragraph block. help-block no longer formatting Is there an obvious step I'm missing or is there another way this can be done? Thanks. -
How to properly extend models while using the django-allauth package
I am relatively new to the developer world as well for django framework. I am currently using the django-allauth library, and here is my issue: When I am trying to provide the view for a model that has a OnetoOnefield to the default User model ( the one used in allauth ), I can't properly save the data from the form to the model, seeming like my model does not get the primary key (supposedly to be retrieving from the OnetoOnefield) from the default User model. -
Declare Django settings to use with mod_wsgi/apache
I have multiple settings files in my Django project (base.py, local.py, production.py). Locally, I'm kicking off the Django dev server via python manage.py runserver --settings=config.settings.local How can I tell mod_wsgi to use the same file? I'm testing this on my local apache instance, but will need to figure out the same thing for my production apache instance. --settings=config.settings.production Current httpd-vhosts.conf: WSGIDaemonProcess secureDash python-path=/Users/user/projects/secureDash_project/secureDash python-home=/Users/user/.venvs/securedash_py3.6 WSGIProcessGroup secureDash WSGIScriptAlias / /Users/user/projects/secureDash_project/config/wsgi.py Error that I see in the apache log: ModuleNotFoundError: No module named 'secureDash.settings' Django 1.11 mod_wsgi-4.5.15 Apache 2.4.18 -
Django - Optimizing bulk inserts on a partitioned database?
I've reached a point where I'm being forced to partition a specific table. I'm using the Architect package to manage this, but with this transition comes the loss of foreign keys and bulk inserts. Since I'm now having to save every record individually, performance has bottomed out to unacceptable levels. Short of using transactions or threads to write multiple entries at once (neither of which I have tested so don't know how well/if they would work), are there any other obvious techniques I could use to increase performance of inserts to compensate for the loss of bulk_create? -
How can I debug "Exception while resolving variable 'exception_type' in template 'unknown'"?
I keep seeing DEBUG Exception while resolving variable 'exception_type' in template 'unknown'. in my django logs, followed by VariableDoesNotExist: Failed lookup for key [exception_type] in followed by what looks like a string representation of a a list of dictionaries containing the request, and my entire settings.py file. I feel like I just don't have enough information to debug this. All I know is there's a variable called exception_type in an unknown template. My code doesn't contain the string 'exception_type' anywhere. How can I debug this? Where should i be looking? -
Secure_ssl_redirect setting for django does nothing on heroku
I am deploying a Django app on heroku and trying to force https on all pages. I use the following settings for that: SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') Now when I visit www.mysite.de it does in fact not redirect me to https. Any ideas what I am missing? -
TemplateDoesNotExist at /books/index.html
I am trying to create my own project with Django version 1.10, but Running the server i get such exception: TemplateDoesNotExist at /books/index.html This is my folder structure: mysite/ books/ migrations template/ books/ index.html __init__.py admin.py apps.py models.py tests.py urls.py views.py mysite/ __init__.py dbsqlite3 settings.py urls.py wsgi.py tamplates/ base_books.html base.html dbsqlite3 manage.py settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'books', ] 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 = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], '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' mysite/books/urls.py : from django.conf.urls import url, include from books import views urlpatterns = [ url(r'^$', views.BooksModelView.as_view(), name='index'), url(r'^books/$', views.BookList.as_view(), name='books_list'), url(r'^author/$', views.AuthorList.as_view(), name='author_list'), url(r'^publisher/$', views.PublisherList.as_view(), name='publisher_list'), url(r'^books/(?P<pk>\d+)/$', views.BookDetail.as_view(), name='detail_list'), url(r'^author/(?P<pk>\d+)/$', views.AuthorDetail.as_view(), name='author_detail'), url(r'^publisher/(?P<pk>\d+)/$', views.PublisherDetail.as_view(), name='publisher_detail'), ] mysite/mysite/urls.py : from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^books/', include('books.urls', namespace="books")), url(r'^admin/', admin.site.urls), ] views.py : from django.views.generic.base import TemplateView from django.views.generic import ListView from django.views.generic import DetailView from books.models import Book, Author, Publisher # TemplateView class BooksModelView(TemplateView): template_name = 'books/index.html' def get_context_data(self, **kwargs): context = super(BooksModelView, self).get_context_data(**kwargs) context['object_list'] = ['Book', 'Author', 'Publisher'] return … -
Executing Django's sqlsequencereset code from within python
Django's sqlsequencereset command returns the SQL commands needed to reset sequences in the database. Is there an easy way to directly execute this returned code from inside python? Currently I'm: Using call_command to run sqlsequencereset Grabbing the output into an in-memory StringIO object (instead of writing to a file on disc) Removing the terminal color codes returned by sqlsequencereset Executing the SQL directly against Django's default database Other management commands automatically run the SQL by default (and only print out the output if you specify the --dry-run option). Am I missing something?! Code: import re import StringIO from django.core.management import call_command from django.db import connection app_name = 'my_app' # Get SQL commands from sqlsequencereset output = StringIO.StringIO() call_command('sqlsequencereset', app_name, stdout=output) sql = output.getvalue() # Remove terminal color codes from sqlsequencereset output ansi_escape = re.compile(r'\x1b[^m]*m') sql = ansi_escape.sub('', sql) with connection.cursor() as cursor: cursor.execute(sql) output.close() -
Django template forloop
Here's a excerpt from a Django template: <div id="list-of-things"> {% for key in things %} {% for thing in thing|get_dict_value:key %} <div id="thing-{{ count }}">{{key}}: {{ thing }}</div> {% endfor %} {% endfor %} </div> things is a dict and get_dict_value:key is simply thing[key]. What's needed in the final page is: <div id="thing-1">A: First thing</div> <div id="thing-2">A: Second thing</div> <div id="thing-3">B: Third thing</div> ... ...which means that I need some way of altering the count variable. Using forloop.counter here causes there to be duplicate values as the counter resets for each time through the outer loop. There doesn't seem to be any way to set a variable in this loop, so is there another means whereby count might be incremented as required? -
What should be in 'TEMPLATE_CONTEXT_PROCESSORS'
Lets say I've following code:(http://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_forms.html) from crispy_forms.helper import FormHelper class ExampleForm(forms.Form): [...] def __init__(self, *args, **kwargs): super(ExampleForm, self).__init__(*args, **kwargs) self.helper = FormHelper() -- from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit class ExampleForm(forms.Form): [...] def __init__(self, *args, **kwargs): super(ExampleForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-exampleForm' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_action = 'submit_survey' self.helper.add_input(Submit('submit', 'Submit')) What should I write in 'TEMPLATE_CONTEXT_PROCESSORS'? I'm getting this error- Failed lookup for key [example_form] -
django-autocomplete-light with gm2m in modals bootstrap: doesn't show all choices
i I'm trying to get autocomplete-light with Gm2m , But autocomplete.GM2MQuerySetSequenceField doesn't shows all choices. View.py class RessourceAutocompleteView(Select2QuerySetSequenceView): def get_queryset(self): employees = Employees.objects.all() freecontracts = Frecontract.objects.filter(IS_ACTIVE=True) freeagencies = Freagencies.objects.filter(IS_ACTIVE=True) freelancers = Freelancers.objects.filter(IS_ACTIVE=True) if self.q: employees = Employees.objects.filter(EMP_FIRST_NAME__icontains=self.q) freecontracts = Frecontract.objects.filter(FIRST_NAME__icontains=self.q, IS_ACTIVE=True) freeagencies = Freagencies.objects.filter(AG_NAME__icontains=self.q, IS_ACTIVE=True) freelancers = Freelancers.objects.filter(FRE_FIRST_NAME__icontains=self.q, IS_ACTIVE=True) # # Aggregate querysets qs = QuerySetSequence(employees, freecontracts, freeagencies, freelancers) # qs = QuerySetSequence(employees) if self.q: # This would apply the filter on all the querysets qs = qs.filter(Q(EMP_FIRST_NAME__icontains=self.q)| Q(FIRST_NAME__icontains=self.q)| Q(AG_NAME__icontains=self.q) | Q(FRE_FIRST_NAME__icontains=self.q )) # This will limit each queryset so that they show an equal number # of results. qs = self.mixup_querysets(qs) return qs Forms.py : class QAMForm(autocomplete.FutureModelForm): def __init__(self, *args, **kwargs): super(QAMForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' }) TRANSLATOR = autocomplete.GM2MQuerySetSequenceField( queryset=autocomplete.QuerySetSequence( Employees.objects.all(), Frecontract.objects.all(), Freagencies.objects.all(), Freelancers.objects.all(), ), required=False, label=_("Traducteur(s)"), widget=autocomplete.QuerySetSequenceSelect2Multiple( 'qm:ressource-autocomplete'), ) PROOFREADER = autocomplete.GM2MQuerySetSequenceField( queryset=autocomplete.QuerySetSequence( # all models Employees.objects.all(), Frecontract.objects.all(), Freagencies.objects.all(), Freelancers.objects.all(), ), required=False, label=_("Relecteur(s)"), widget=autocomplete.QuerySetSequenceSelect2Multiple( 'qm:ressource-autocomplete'), ) PM = forms.ModelMultipleChoiceField(queryset=Employees.objects.filter(TYPE_RESOURCE__TYPE__in = ('PMJ', 'PMS')), required=False, label=_("PM(s)"),) # QA = forms.ModelChoiceField(queryset=Employees.objects.filter(TYPE_RESOURCE__TYPE__in=('PMJ', 'PMS')), # required=False) class Meta: model = Feedback fields = ['PM'] models.py: class Feedback(models.Model): #the fields TRANSLATOR = GM2MField() PROOFREADER = GM2MField() PM = models.CharField(max_length=250, blank=True, null=True) I apply it under modals bootstrap in …