[Django]-How to fix, limit_choices_to cannot be a ForeignKey in Django?

2👍

You have to do that in the View when creating a Note

form.py

from .models import Note
from django.forms import ModelForm

class NoteForm(ModelForm):
    class Meta:
       model = Note

view.py

from django.views.generic.edit import CreateView
from .form import NoteForm
from .models import Note, Notebook

class NoteCreateView(CreateView):
    model=Note
    form_class=NoteForm

    def get_form(self, form_class=None):
        form = super(NoteCreateView, self).get_form(form_class)
        # Thats the solution:
        form.fields['notebook'].queryset = Notebook.objects.filter(owner=self.request.user)
        return form

Leave a comment