I am currently trying to improve my form by restricting choices inside an input (user can choose only their own tags).
I tried to do that inside the get/post function :
def post(self, request, *args, **kwargs):
form = DateInputForm(request.POST, limit_choices_to={'tags__user': request.user})
def get(self, request, *args, **kwargs):
form = DateInputForm(limit_choices_to={'tags__user': request.user})
(1) I get an error.
BaseModelForm.init() got an unexpected keyword argument 'limit_choices_to'
My form :
class DateInputForm(ModelForm):
class Meta:
model = Task
# exclude = ('user',)
fields = ['user', 'title', 'description', 'date_to_do', 'complete', 'tags']
widgets = {
'date_to_do': forms.DateTimeInput(format='%Y-%m-%dT%H:%M',
attrs={'type': 'datetime-local', 'class': 'timepicker'}),
}
My view :
class TaskUpdate(LoginRequiredMixin, UpdateView):
model = Task
template_name = "tasks/task_form.html"
form_class = DateInputForm
Tag model :
class Tag(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
tag_name = models.CharField(max_length=200, null=True, blank=False, default='')
Globally: the goal is to limit the tags that can be chosen by the user in my task form (with the tag input); currently, a user can choose another user's tag, which is not what I want.
CodePudding user response:
I think the easiest way to do this is to override the constructor of your form, as shown in this answer: https://stackoverflow.com/a/1969081/18728725
CodePudding user response:
To filter the tags in my input, I went back and followed the join method by StefanoTrv. Here is my solution :
def __init__(self, *args, **kwargs):
super(DateInputForm, self).__init__(*args, **kwargs)
if 'instance' in kwargs:
new_kwargs = kwargs.get('instance')
self.fields['tags'].queryset = Tag.objects.filter(user=new_kwargs.user.id)
Warning, that's not working in the createView