Answer the question
In order to leave comments, you need to log in
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')
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})
form = BookmarksForm(request.POST, user=request.user.id)
Answer the question
In order to leave comments, you need to log in
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)
# 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)
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 questionAsk a Question
731 491 924 answers to any question