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__'
# this comes from 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. This means I added 'plus button' next to ModelMultipleChoiceField
name field, which leads to popup where I can create new Name. I intend to have empty name field (without choices) every time I open my robject create form. Unfortunately, I see previously created Names when I refresh the form page.
My problem is, function limit_name_choices
isn't called every time new form is instantiated. Is it a bug, or I am doing something wrong?
From django documentation: https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to
If a callable is used for
limit_choices_to
, it will be invoked every time a new form is instantiated. It may also be invoked when a model is validated, for example by management commands or the admin. The admin constructs querysets to validate its form inputs in various edge cases multiple times, so there is a possibility your callable may be invoked several times.