I am trying to create a form for a library where a user can perform 2 actions: add a new book or open the stored information of an existing one. Books have 2 fields (title and a
You should use ModelChoiceField.
class CronForm(forms.Form):
days = forms.ModelChoiceField(queryset=Books.objects.all().order_by('name'))
Then your views, it should look something like this:
def show_book(request):
form = CronForm()
if request.method == "POST":
form = CronForm(request.POST)
if form.is_valid:
#redirect to the url where you'll process the input
return HttpResponseRedirect(...) # insert reverse or url
errors = form.errors or None # form not submitted or it has errors
return render(request, 'path/to/template.html',{
'form': form,
'errors': errors,
})
To add a new book or edit one, you should use a ModelForm. Then in that view you'll check if it's a new form or not
book_form = BookForm() # This will create a new book
or
book = get_object_or_404(Book, pk=1)
book_form = BookForm(instance=book) # this will create a form with the data filled of book with id 1