Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update progress bar while making a Django Rest api request?
My django rest app accepts request to scrape multiple pages for prices & compare them (which takes time ~5 seconds) then returns a list of the prices from each page as a json object. I want to update the user with the current operation, for example if I scrape 3 pages I want to update the interface like this : Searching 1/3 Searching 2/3 Searching 3/3 How can I do this? I am using Angular 2 for my front end but this shouldn't make a big difference as it's a backend issue. -
ImportError: The _imagingft C module is not installed . ( Misago )
I get this error while creating superuser Misago the forum. (Ubuntu 16.04). Enter password: Repeat password: Traceback (most recent call last): File "manage.py", line 23, in execute_from_command_line(sys.argv) File "/var/www/html/Misago/venv/local/lib/python2.7/site-packages/Django-1.10.6-py2.7.egg/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/var/www/html/Misago/venv/local/lib/python2.7/site-packages/Django-1.10.6-py2.7.egg/django/core/management/init.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/www/html/Misago/venv/local/lib/python2.7/site-packages/Django-1.10.6-py2.7.egg/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/var/www/html/Misago/venv/local/lib/python2.7/site-packages/Misago-0.6a4-py2.7.egg/misago/users/management/commands/createsuperuser.py", line 72, in execute return super(Command, self).execute(*args, **options) File "/var/www/html/Misago/venv/local/lib/python2.7/site-packages/Django-1.10.6-py2.7.egg/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/var/www/html/Misago/venv/local/lib/python2.7/site-packages/Misago-0.6a4-py2.7.egg/misago/users/management/commands/createsuperuser.py", line 150, in handle self.create_superuser(username, email, password, verbosity) File "/var/www/html/Misago/venv/local/lib/python2.7/site-packages/Misago-0.6a4-py2.7.egg/misago/users/management/commands/createsuperuser.py", line 165, in create_superuser username, email, password, set_default_avatar=True File "/var/www/html/Misago/venv/local/lib/python2.7/site-packages/Django-1.10.6-py2.7.egg/django/utils/decorators.py", line 185, in inner return func(*args, **kwargs) File "/var/www/html/Misago/venv/local/lib/python2.7/site-packages/Misago-0.6a4-py2.7.egg/misago/users/models/user.py", line 105, in create_superuser set_default_avatar=set_default_avatar, File "/var/www/html/Misago/venv/local/lib/python2.7/site-packages/Django-1.10.6-py2.7.egg/django/utils/decorators.py", line 185, in inner return func(*args, **kwargs) File "/var/www/html/Misago/venv/local/lib/python2.7/site-packages/Misago-0.6a4-py2.7.egg/misago/users/models/user.py", line 77, in create_user user, settings.default_avatar, settings.default_gravatar_fallback File "/var/www/html/Misago/venv/local/lib/python2.7/site-packages/Misago-0.6a4-py2.7.egg/misago/users/avatars/init.py", line 21, in set_default_avatar dynamic.set_avatar(user) File "/var/www/html/Misago/venv/local/lib/python2.7/site-packages/Misago-0.6a4-py2.7.egg/misago/users/avatars/dynamic.py", line 24, in set_avatar image = drawer_function(user) File "/var/www/html/Misago/venv/local/lib/python2.7/site-packages/Misago-0.6a4-py2.7.egg/misago/users/avatars/dynamic.py", line 34, in draw_default image = draw_avatar_flavour(user, image) File "/var/www/html/Misago/venv/local/lib/python2.7/site-packages/Misago-0.6a4-py2.7.egg/misago/users/avatars/dynamic.py", line 59, in draw_avatar_flavour font = ImageFont.truetype(FONT_FILE, size=size) File "/var/www/html/Misago/venv/lib/python2.7/site-packages/Pillow-3.4.2-py2.7-linux-x86_64.egg/PIL/ImageFont.py", line 239, in truetype File "/var/www/html/Misago/venv/lib/python2.7/site-packages/Pillow-3.4.2-py2.7-linux-x86_64.egg/PIL/ImageFont.py", line 128, in init File "/var/www/html/Misago/venv/lib/python2.7/site-packages/Pillow-3.4.2-py2.7-linux-x86_64.egg/PIL/ImageFont.py", line 37, in getattr ImportError: The _imagingft C module is not installed -
Django - Cannot assign "'dortmund'": "Administrator.asoc_name" must be a "Association" instance
I try to save the id from Association table into Administrator table. Is there something i'm missing? Still a newbie so appreciate your help, folks! admin\models.py class Administrator(AbstractUser): ... asoc_name = models.CharField(max_length=100) class Meta: db_table = 'Administrator' member\models.py from pl.admin.models import Administrator class Association(models.Model): asocnumber = models.AutoField(primary_key=True) asoc_name = models.CharField(max_length=100) user = models.ForeignKey(Administrator) member_no = models.ForeignKey(Member) class Meta: db_table = 'Association' forms.py class SignUpForm(forms.ModelForm): ... association_choices = [(i['asoc_name'], i['asoc_name']) for i in Association.objects.values('asoc_name')] asoc_name = forms.ChoiceField(choices=association_choices, widget=forms.Select(attrs={'class': 'form-control'}), required=True) ... def save(self, commit=True): instance = super(SignUpForm, self).save(commit=False) asoc = self.cleaned_data['association'] instance.association = Association.objects.get(pk=asoc) instance.save(commit) return instance class Meta: model = Administrator fields = [..., 'asoc_name', ...] views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if not form.is_valid(): return render(request, 'admin/signup.html', {'form': form}) else: ... asoc_name = form.cleaned_data.get('asoc_name') ... Administrator.objects.create_user(... asoc_name=asoc_name, ...) user = authenticate(... asoc_name=asoc_name, ...) return redirect('/') else: return render(request, 'admin/signup.html', {'form': SignUpForm()}) -
How to filter on 2 attributes at once with Django ORM
I have the following models: class Parent(models.Model): item = models.ManyToManyField(Item, through=ItemInvolved) class ItemInvolved(models.Model): parent = models.ForeignKey(Parent, related_name='item_involvement') kind = models.PositiveIntegerField() I want to retrieve all Parents for which an Item has pk=20 and its ItemInvolved has kind=10. -
get_absolute_url with multiple foreign key
Hello Django Pros out there! Is it possible to get the pk of a model, which is not the direct foreign key of the model? But the foreignkey of the foreign key model? My Models: class Patient(models.Model): patientID = models.CharField(max_length=200, unique=True, help_text='Insert PatientID') class Examination(models.Model): number_of_examination = models.IntegerField(choices=EXA_Choices) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) date_of_examination = models.DateField(auto_now=False, auto_now_add=False, help_text='YYYY-MM-DD') class AbsoluteValue(models.Model): examination = models.ForeignKey(Examination, on_delete=models.CASCADE) attr1 = models.BooleanField(default=False) attr2 = models.BooleanField(default=False) attr3 = models.BooleanField(default=False) and I want to define the get_absolute_url of the AbsoluteValue class. It should redirect to the Patient detail page. Due to this it needs the pk of the Patient class. My try: def get_absolute_url(self): return reverse('member:detail', kwargs={'pk': self.examination__patient_id}) The error says that there is no URL to redirect to. So my query is not working, or I should not query in this function. -
Upload a relatively big excel in Django and improve the write speed (Postgresql)
I am uploading a 4000 row excel in Django (I'm using django-excel as an external plugin), which is taking around 17 seconds. This sounds very low in comparison to a normal POSTGRESQL write qps (queries per second) expected to be about 600-700.To maintain data integrity and to add a specific column, I need to do entry of one row at a time. Following is the code I am using currently. def import_student(request): this_tenant=request.user.tenant if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) batch_selected=Batch.objects.for_tenant(this_tenant).get(id=1) def choice_func(row): choice_func.counter+=1 data=student_validate(row, this_tenant, choice_func.counter, batch_selected) return data choice_func.counter=0 if form.is_valid(): with transaction.atomic(): try: request.FILES['file'].save_to_database( model=Student, initializer=choice_func, mapdict=['first_name', 'last_name', 'dob','gender','blood_group', 'contact', 'email_id', \ 'local_id','address_line_1','address_line_2','state','pincode','batch','key', 'slug', 'tenant','user']) # messages.success(request, 'Students data uploaded successfully.') return redirect('student:student_list') except: transaction.rollback() return HttpResponse("Failed") else: return HttpResponseBadRequest() else: form = UploadFileForm() return render(request,'upload_form.html',{'form': form}) And the student validate function is as follows: def student_validate(row, this_tenant, counter, batch): data="st" # tenant=this_tenant today=dt.date.today() today_string=today.strftime('%y%m%d') next_student_number='{0:03d}'.format(counter) last_student=Student.objects.filter(tenant=this_tenant).\ filter(key__contains=today_string).order_by('key').last() if last_student: last_student_number=int(last_student.key[8:]) next_student_number='{0:03d}'.format(last_student_number + counter) key=data+str(today_string)+str(next_student_number) toslug=str(this_tenant)+" " +str(key) slug=slugify(toslug) item=None row.append(key) row.append(slug) row.append(this_tenant) row[12]=batch if (row[0] == None or row[0] == "" or row[1] == None or row[1] == "") : transaction.rollback() return HttpResponse("There is error in uploaded excel") if (row[3] != "M" and row[3] != … -
Serialize Many to Many with extra field
I'm new to Django and would like to know how to approach the serialization of Many to Many relations with extra fields. I have custom query sets and I still can figure out how to proceed to serialize the queryset and send it to the angular front end. Thanks -
django models/admin issue - admin displays table twice
We moved a django model from one app to another ("PollRunForJira" was moved from "reports" to "jira_fat"). All the code seems clean from the old model and the django_migrations DB table is clean from the old model too. Still the django admin display the 2 models: The new model is functional (we can drill into it in the admin", while the old one appears but we cannot drill into it. How is it possible to get rid of the old model display in the admin? Where does Django gets the information from if it doesn't appear in the code/DB. Thanks -
Django ForeignKey' object has no attribute 'model'
I have two models(eisfiles and AuthPermissionAdd) and and am trying to add one to many relationship, as shown in the below code. But for some reason i am getting " ForeignKey' object has no attribute 'model'. Please help me where I am doing wrong. class eisfiles(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) htmlname = models.CharField(max_length=100) jarid = models.CharField(max_length=100) class AuthPermissionAdd(models.Model): user_id = models.CharField(max_length=500) eisfiles_id = models.ForeignKey(eisfiles) temp_id_id_id = models.IntegerField(blank=True, null=True) -
Django not see the table in generic relation
I'm working with Django 1.7.2 with generic relation (reason: project has two databases), and after import I don't want to have overwritten database. I want to show only active season Here is my model, is overwritten after import: class Season(models.Model): name = models.CharField('Name', max_length=255) start = models.DateField('Start') end = models.DateField('End') def __unicode__(self): return self.name In another place in models.py file I create Generic relation to another model (SaleAndCycle) in another database: if sender.__name__ == 'Season': sender.add_to_class('sale_and_cycles', generic.GenericRelation(SaleAndCycle)) sender.add_to_class('is_sale_active', property( lambda o: o.sale_and_cycles.using('default'))) sender.add_to_class('is_cyclic_event_active', property( lambda o: o.sale_and_cycles.using('default'))) sender.add_to_class('cycle_link', property( lambda o: o.sale_and_cycles.using('default'))) I want to show all active Seasons for not login user: def get_queryset(self): seasons = Season.objects.all() if not self.request.user.is_superuser: all_seasons = Season.objects.filter(events_isactiveflags__is_active=True) print all_seasons I get error: no such table: events_isactiveflag But this table exists in my database. -
Revelants queries suggestion for autocomplete with Solr
I use Solr 6.4 with Haystack 2.6.1, pySolr 3.6: I'm looking for a google like suggestions autocomplete. Actually use EdgeNGram works good but it returns my documents titles only what is not what I want: example: typing: 'new y' return: New york, fabulous city that never sleep A trip to new york by night ... This give the user only the choice to select a document in particular in the suggestion list and the search will return only document with search based on suggested title. What I want is a suggestion of revelants words like: typing: 'new y' return: new york new york by night new york city trip to new york There is an article that suggest to use indexed queries by users that return results and then to use these queries as suggestions: https://lucidworks.com/2009/09/08/auto-suggest-from-popular-queries-using-edgengrams/ This mean parsing solr log or use a Data import (DIH) from a bunch of saved user's queries in DB. Actually this article is pretty old (2009) and since then Solr have bring to us the Suggester (https://cwiki.apache.org/confluence/display/solr/Suggester) Anyway I wonder if there is actually a good tutorial on how to use Suggester with revelant queries instead of returning my documents titles without the … -
updating a django model after saving it
I have a model like this: class Thing(models.Model): photo = models.ImageField(...) verified = models.NullBooleanField(default=None) Using django-rest-framework, I upload an image over an API, which I then need to run some checks on (postprocess it). I need Thing.photo to be saved so that I can run the checks. The checks need to happen within the request cycle, as the HTTP response depends on the outcome. I am using a post_save signal for this now, in which I check the created argument to avoid recursion (as explained in Django signal post_save update) and run the checks only the first time the object is saved. This works, but I am hitting the database twice, which seems unecessary. Ideally I would do something like: def save(self, *args, **kwargs): self.photo = store_the_uploaded_blob() self.verified = run_checks(self.photo) super(Thing, self).save(*args, **kwargs) Can I do this? And how? -
"django.conf.urls" is invalid syntax? Newbie here
I'm trying to create a website in python using Django, and while i was trying to point the root URLconf at the polls.url module. I am following the tutorial here: https://docs.djangoproject.com/en/1.10/intro/tutorial01/ When O test it using python manage.py runserver, the command prompt says django.conf.urls` is invalid syntax Pointing at the "o" in django to be precise. Code I'm using is the same as in the tutorial, this is what it is: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] And I put it in mysite/urls.py. I'm a complete newbie, so I hope this doesn't sound like an incredibly dumb question. My Django version 1.10.6, Python is 2.7.12. -
django rest framework attributeerror
I’m working through a book that introduces Django and the django rest framework. The tutorial creates a rest API with games, categories, players and scores with a suitable relational model between them. I’ve stumbled upon an issue when inserting a game category I get the following error: AttributeError at /game-categories/ 'GameCategory' object has no attribute 'games' Request Method: POST Request URL: http://127.0.0.1:8000/game-categories/ Django Version: 1.10.5 Exception Type: AttributeError Exception Value: 'GameCategory' object has no attribute 'games' Exception Location: C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\rest_framework\fields.py in get_attribute, line 103 Python Executable: C:\Users\user\AppData\Local\Programs\Python\Python36-32\python.exe Python Version: 3.6.0 Python Path: ['C:\\Python\\Django01\\gamesapi', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\python36.zip', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\DLLs', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\lib', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages'] Server time: Wed, 8 Mar 2017 09:40:42 +0000 My Game and GameCategory models are as follows: class GameCategory(models.Model): name = models.CharField(max_length=200) class Meta: ordering = ('name',) def __str__(self): return self.name class Game(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=200, blank=True, default='') game_category = models.ForeignKey(GameCategory, related_name='games', on_delete=models.CASCADE) release_date = models.DateTimeField() game_category = models.CharField(max_length=200, blank=True, default='') played = models.BooleanField(default=False) class Meta: ordering = ('name',) def __str__(self): return self.name and the snippet of my urls.py: urlpatterns = [ url(r'^game-categories/$', views.GameCategoryList.as_view(),name=views.GameCategoryList.name), url(r'^game-categories/(?P<pk>[0-9]+)$', views.GameCategoryDetail.as_view(), name=views.GameCategoryDetail.name), views.py: from games.models import GameCategory from games.models import Game from games.models import Player from games.models import PlayerScore from games.serializers import GameCategorySerializer from games.serializers import … -
Sending a email from a Bootstrap model + Django
So i had the form working and sending on a different page but i wanted to put the form into a pop-up. I have been trying to understand why it now is not working and stripped it back to the basics. The submit button does not seem to do anything. I have been trying to debug it for half an hour now and have a peice of code that should print 'POST' in the cmd if the request method is post. (This is where i validate and send the email, right?. Thats how it worked before) def motors(request): if request.method == 'GET': print 'GET' form = MotorEnquire() elif request.method == 'POST': print 'POST' print 'Working' motors = Motors.objects.all() return render(request, 'motors.html', {'motors': motors, 'form': form}) The Form in template: <form method="POST"> {% csrf_token %} {{ form.as_p }} <div class="form-actions"> <button type="submit">Send</button> </div> </form> When i click send nothing happens, im exspecting something to print to the cmd. When i load the page i get both print messages that i should be getting 'GET' and 'Working' I still have my old code that worked until i moved everything and took away the urls because i put it into the bootstrap model. … -
Automatically translate model data according language
It is possible dynamically translate model data .I'm using Django 1.10 and modeltranslation 0.12. -
uwsgi nginx connection to unix socket refused
I'm trying to migrate django app from ubuntu 14.04 to raspberry pi ( raspbian os) for ubuntu i have done http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html and it worked. in raspbian it's not so simple. this is my nginx.conf # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name 192.168.5.5; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /var/www/html/bills/bills/bills/media; # your Django project's media files - amend as required } location /static { alias /var/www/html/bills/bills/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /var/www/html/bills/bills/uwsgi_params; # the uwsgi_params file you installed } } and this is my UWSGI INI file: [uwsgi] # Django-related settings # the base directory (full path) chdir = /var/www/html/bills/bills # Django's wsgi file module = bills.wsgi # the virtualenv (full path) home = /home/seb/.virtualenvs/bills3 # process-related settings # master master = true # maximum number of worker processes processes = 10 # the socket (use the full … -
Django How to get event of user choosing a file?
I have a script which execution takes a while and I don't want the user to wait for the finish of the script when he saves a new Product. To solve that problem I would like to execute a script when the user chose a file in a FileField in the admin portal without having to press save. So he can give additional information about the Product while the script is already running. Is there a way in Django to get the event when a user chose a file? -
Exclude field from GROUP BY in Django ORM
We have a system written in Django to track patients recruited to clinical trials. Spread sheets are used to record the number of patients recruited each month throughout a financial year; so the sheet only contains 12 months of data even though a study may run for years. There is a table in a django database in to which the spread sheets are imported each month. The data includes the month/year, a count of patients, and some other fields. Each import will include all the previous months data; we need this to make sure no data has been changed on the import sheet since the last import. For example, the import table containing two imports (the first up to January and the second up to February) would look like this: id | study_id | data_date | patient_count | [other fields] --> 100 5456 2016-04-01 10 ... 101 5456 2016-05-01 8 ... 102 5456 2016-06-01 5 ... ... all months in between ... 109 5456 2016-01-01 12 ... 110 5456 2016-02-01 NULL ... 111 5456 2016-03-01 NULL ... 112 5456 2016-04-01 10 ... 113 5456 2016-05-01 8 ... 114 5456 2016-06-01 5 ... ... all months in between ... 121 5456 … -
Cannot make custom __str__ calling parent's __str__ in Django
Although I know how to make it, and have searched examples for comparing my code, I cannot get why I cannot call a model that has its __str__ calling inside its parent's __str__. I get a RuntimeError: maximum recursion depth exceeded in __subclasscheck__ , which should not be happening. Here is my code below. No collateral work that could be affecting it: class A(models.Model): def __str__(self): return self.attr class B(A): def __str__(self): return "%s - %s" % (super(B, self).__str__(), self.attr_two) -
How can I get session in forms?
I have a multistep form with checkboxes, after the user submit the first step form I save the objects he checked on his session, at the second step form I would like to filter the objects with the session datas. To accomplish this I need to get the session on the new ModelForm for the second step, unfortunaltely request is not defined in forms. How can I access my sessions ? class IconSubChoiceForm(forms.ModelForm): session_icons = request.session.get('icons') query = Q(tags__contains=session_icons[0]) | Q(tags__contains=session_icons[1]) | Q(tags__contains=session_icons[2]) icons = CustomSubChoiceField(queryset=CanvaIcon.objects.filter(query), widget=forms.CheckboxSelectMultiple) class Meta: model = CanvaIcon fields = ['icons'] Any suggestion ? -
Create a full-duplex communication between heterogeneous WebApps for long-polling (Django and other)
We have a microservices architecture with a chain of micro-services polling one with the other. All our webservices are written in Python, but using different frameworks The polling chain would be: Browser(JS) --polls N-status--> WS1(Django) --polls M-status--> WS2(Custom Python) --polls P-status--> WS3(Django) Between each web-services there is a polling of different status. We are looking at Django Channels, but it seems applicable to a communication between two Django web-services, even if it uses WebSockets. How can we have a standard, consistent way to create long-term full-duplex connections between heterogeneous web-services. So that a Producer dispatch changes, and Receivers can handle them. Seems that Websockets are use mainly for Browser->Server communications. What would be the way to go? -
Django Admin Fk grouping
How do I go about grouping a set of fields within the Django Admin. By this I mean Table 1: User - User Key - User Name Table 2: Post - Post Key - User Key (FK) In the PostAdmin I would like to display the User Name of the Author also perform an action on the blogs. This works but displays the user name for each blog created by the user. Is there a way I could just display the user name once but in the action update all blogs created by the user? Model class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("email address"), unique=True) first_name = models.CharField( _("first name"), max_length=50, validators=[RegexValidator( regex_alpha, code='invalid_first_name', message=regex_alpha_message, )] ) middle_name = models.CharField( _("middle name"), max_length=50, blank=True, null=True, default=None, validators=[RegexValidator( regex_alpha, code='invalid_middle_name', message=regex_alpha_message, )] ) class Post(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.CharField(_('title'), max_length=250) label = models.ForeignKey(Label, verbose_name=_('label')) significance = models.CharField(max_length=3, choices=SIGNIFICANCE_CHOICES) is_sealed = models.BooleanField(_('Is Sealed?'), default=False) event_date = models.DateField() message = models.TextField(_("Message"), blank=True, default='') PostAdmin (I need to fix the issue here) class PostAdmin(admin.ModelAdmin): list_display = ['owner','is_sealed'] ordering = ['owner'] actions = [open_vault] search_fields = ['owner__email',] list_filter = ['owner__email'] -
what is the difference between allowed_hosts and cors_origin_regex_whitelist in django?
What is the difference between this two django settings : ALLOWED_HOSTS CORS_ORIGIN_REGEX_WHITELIST -
Adding objects to ManyToMany field
I have a model called 'Line', which has a ManyToMany relationship with 'User'. What I am trying to do is to render the form of the line excluding the User field in order to create a costum rendering for the ManyToMany field where the user can search within all the users and then he checks the checkboxes beside the users' names. Then I read the ids of the selected users and get the users from the database and try to set the users of the new line object. Here is the code: Model: class Line(models.Model): name = models.CharField("Name", max_length=50) owners = models.ManyToManyField(User, related_name="owners") def set_owners(self, users): self.owners.clear() for user in users: self.owners.add(user) self.save() Forms: class LineCreationForm(forms.ModelForm): class Meta: model = Line exclude = 'owners' def __init__(self, *args, **kwargs): super(LineCreationForm, self).__init__(*args, **kwargs) for filed in self.visible_fields(): filed.field.widget.attrs['class'] = 'form-control' Views: def new_line(request): if request.method == POST: form = LineCreationForm(request.POST) if form.is_valid(): line = form.save() if 'line_owner' in request.POST: get_integers_from_checked_checkboxes(request, 'line_owner') selected_users = User.objects.filter(pk__in=owners_ids) line.set_owners(selected_users) return redirect(home_page) The problem: I tested the users list and it is working fine. The problem is the owners list stays None after calling the 'line.set_owners(selected_users)' function.