forms - Django: ManyToManyField.limit_choices_to seems not working properly -
i have following models:
models.py
:
def limit_name_choices(): return {"pk__gt": name.objects.last().pk} class name(models.model): name = models.charfield(max_length=100) primary = models.booleanfield() class robject(models.model): project = models.foreignkey(to=project, null=true) author = models.foreignkey( to=user, null=true, related_name="robjects_in_which_user_is_author") create_by = models.foreignkey( to=user, related_name="robjects_created_by_user", null=true) create_date = models.datetimefield(null=true) modify_by = models.foreignkey(to=user, null=true) name = models.manytomanyfield( "name", related_name="robject_name", help_text='the name of robject', limit_choices_to= get_last_name_pk() )
views.py
:
def robject_create_view(request, *args, **kwargs): if request.method == "post": form = robjectform(request.post) if form.is_valid(): return redirect("/") else: form = robjectform() return render(request, 'robjects/create_robject.html', {"form":form})
and forms.py
:
class robjectform(forms.modelform): class meta: model = robject fields = '__all__' # comes django-addanother (admin popup functionality) widgets = { 'name': addanotherwidgetwrapper( forms.selectmultiple, reverse_lazy('add_name', args=['proj_1']), ), }
i created imitation of admin robject create form. means added 'plus button' next modelmultiplechoicefield
name field, leads popup can create new name. intend have empty name field (without choices) every time open robject create form. unfortunately, see created names when refresh form page.
my problem is, function limit_name_choices
isn't called every time new form instantiated. bug, or doing wrong?
from django documentation: https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.foreignkey.limit_choices_to
if callable used
limit_choices_to
, invoked every time new form instantiated. may invoked when model validated, example management commands or admin. admin constructs querysets validate form inputs in various edge cases multiple times, there possibility callable may invoked several times.
Comments
Post a Comment