django form dropdown list of stored models

前端 未结 2 1075
暗喜
暗喜 2021-02-01 07:04

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

相关标签:
2条回答
  • 2021-02-01 07:29

    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

    0 讨论(0)
  • 2021-02-01 07:34

    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 讨论(0)
提交回复
热议问题