python - Select2 widget for ManyToMany relationship -
i using django-select2 widgets nicer manytomany
widget. view looks nicer , can search , select many different users. however, when save model, list of allowed users blank. tried direct view , unit tests. cannot fathom doing wrong.
any idea?
i suspect there 2 problems: 1 in saving of form created model , 1 how set data
dictionary values.
my model:
class projectcode(models.model): allowed_users = models.manytomanyfield(user, blank=true)
my form:
class projectcodeform(forms.modelform): class meta: model = projectcode fields = '__all__' widgets = {'allowed_users': select2multiplewidget(), }
my view:
def create_code(request): context = {} if request.method == 'post': form = projectcodeform(request.post) if form.is_valid(): new = form.save(commit=false) new.save() form = projectcodeform() context['form'] = form return render(request, 'order_book/create_code.html', context)
my test:
def test_code_create_post_pass(self): init = len(projectcode.objects.all()) data = {'allowed_users': [self.jdoe.pk, ], } response = self.client.post('/order_book/code/create/', data) self.assertequal(response.status_code, 200) self.assertcontains(response, "create project code") self.assertequal(init + 1, len(projectcode.objects.all())) self.assertequal("jdoe", projectcode.objects.all()[0].display_allowed_users())
this tests fails with:
====================================================================== fail: test_code_create_post_pass (order_book.tests.authorisedviewtest) ---------------------------------------------------------------------- traceback (most recent call last): file "/path/tests.py", line 385, in test_code_create_post_pass "jdoe", projectcode.objects.all()[0].display_allowed_users()) assertionerror: u'jdoe' != u'' - jdoe +
post question, continue play pdb
, idea pops up… modified view to:
def create_code(request): context = {} if request.method == 'post': form = projectcodeform(request.post) if form.is_valid(): new = form.save(commit=false) # doing "clever" things new object here, # setting creator , created date/time… new.save() usr in form.cleaned_data['allowed_users']: # ← not correct new.allowed_users.add(usr) # ← neither this… form = projectcodeform() context['form'] = form return render(request, 'order_book/create_code.html', context)
i getting error saying allowed_users
not set new
did not have primary key yet. lead me try set data after having saved object.
note test data
correct , test passes fine.
alternatively, read freaking documentation , use correct method save_m2m()
:
def create_code(request): context = {} if request.method == 'post': form = projectcodeform(request.post) if form.is_valid(): new = form.save(commit=false) # doing "clever" things new object here, # setting creator , created date/time… new.save() form.save_m2m() # ← correct! form = projectcodeform() context['form'] = form return render(request, 'order_book/create_code.html', context)
Comments
Post a Comment