[Fixed]-Django form dropdown list of stored models

46👍

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

0👍

Supplement to J. Ghyllebert’s answer to address rendering question in comments.
Template rendering:

<form action="" class="YourFormClass" method="post">
    {% csrf_token %}
    {{ form.as_p }}
</form>

Or single field:

<form action="" class="YourFormClass" method="post">
    {% csrf_token %}
    <label class="YourLabelClass">{{ form.days.label }}</label>
    <div class="YourSelectClass">
        {{ form.days }}
    </div>
</form>

Documentation: https://docs.djangoproject.com/en/3.1/topics/forms/#the-template

👤Sliwa

Leave a comment