Search code examples
pythondjangodjango-formsdjango-viewsdjango-generic-views

How to modify the author choices field in my generic CreateView with authors(fk) only from the current user?


This is my code, i have read the documentations and it seems this method is the right way, i get no errors but i see no results. Can somebody help me in what i am doing wrong?

class BookCreate(LoginRequiredMixin, CreateView):
     model = Book
     fields = ['title', 'isbn', 'year', 'author', 'publisher']


    def form_valid(self, form):
        form.instance.owner = self.request.user
        return super(BookCreate, self).form_valid(form)

    def form_valid(self, form):
        b = Book.objects.all
        form.instance.author = ModelChoiceField(queryset=b.author_set.filter(owner=self.request.user))
        return super(BookCreate, self).form_valid(form)

Solution

  • It is much easier to simply exclude the author from the list of fields, then set it in the form_valid method:

    class BookCreate(LoginRequiredMixin, CreateView):
        model = Book
        fields = ['title', 'isbn', 'year', 'publisher']
    
        def form_valid(self, form):
            form.instance.owner = self.request.user
            return super(BookCreate, self).form_valid(form)
    

    If you do this, make sure you delete your second form_valid method, which is replacing the correct form_valid method above.

    If you must include author as a field with a single option, then the code is much more complicated. You need a custom form with an __init__ method which takes user and sets the queryset for the auth field.

    Then you need to modify your view to use your custom form, and override get_form_kwargs to include self.request.user.