E
E
EgorLee2021-08-20 13:55:58
Django
EgorLee, 2021-08-20 13:55:58

How to normally limit a dropdown list in a form?

I'm trying to limit the dropdown list (only shows fields related to a specific user), I did it like this:

forms.py:

class BookmarksForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(BookmarksForm, self).__init__(*args, **kwargs)
        self.fields['folder'].queryset = Folders.objects.filter(user=user)

    class Meta:
        model = Bookmarks
        fields = ('link', 'folder')


views.py:

def bookmarks(request):

    if request.method == 'POST' and 'create_folder' in request.POST:    # форма создания папки
        form = FolderForm(request.POST)
        f = form.save(commit=False)
        user = User.objects.get(id=request.user.id)
        f.user = user
        if form.is_valid():
            print('here')
            f.save()
            return redirect('bookmarks')
        else:
            form.add_error(None, 'Ошибка добавления папки')

    elif request.method == 'POST' and 'create_bm' in request.POST:  # форма создания закладки
        form = BookmarksForm(request.POST)
        f = form.save(commit=False)
        try:
            title = get_name_site(f.link)
            f.name = title
        except:
            f.name = f.link
        if form.is_valid():
            f.save()
            return redirect('bookmarks')
        else:
            form.add_error(None, 'Ошибка добавления закладки')
    else:
        folder_form = FolderForm()
        bookmarks_form = BookmarksForm(user=request.user.id)
        folder = Folders.objects.filter(user=request.user.id)
        fastlink = Fastlinks.objects.filter(user=request.user.id)
    return render(request, 'mainapp/bookmarks.html', {'title': 'закладки', 'folder_form': folder_form, 'bm_form': bookmarks_form, 'folders': folder, 'fl': fastlink})


Now the list is displayed correctly, but when submitting the form it gives an error:

Field 'id' expected a number but got .

611f89dac9daf780727697.png

If I try to pass user:

form = BookmarksForm(request.POST, user=request.user.id)


an error occurs:
__init__() got multiple values ​​for argument 'user'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2021-08-23
@pyHammer

EgorLee you shouldn't do that,

# forms.py
class BookmarksForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(BookmarksForm, self).__init__(*args, **kwargs)
        self.fields['folder'].queryset = Folders.objects.filter(user=user)

# views.py
form = BookmarksForm(request.POST, user=request.user.id)

you better do it like this
# views.py

def bookmarks(request):
    if request.method == 'POST' and 'create_folder' in request.POST:    # форма создания папки
        form = FolderForm(request.POST)
        form.fields['folder'].queryset = Folders.objects.filter(user=request.user)

PS
Well, here's another thing that can be improved. This structure avoids code duplication.
def bookmarks(request):
    if request.method == 'POST':
        folder_form = FolderForm(request.POST)

        if folder_form.is_valid():
            if 'create_folder' in request.POST:
                pass
            if 'create_bm' in request.POST:
                pass

            return redirect('bookmarks')
        else:
            form.add_error(None, 'Ошибка добавления папки')
    else:
        folder_form = FolderForm()

    return render(request, 'mainapp/bookmarks.html', {
        'title': 'закладки',
        'folder_form': folder_form,
        'bm_form': bookmarks_form,
        'folders': folder,
        'fl': fastlink
    })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question