Home > Back-end >  Django how to show choices in select input
Django how to show choices in select input

Time:09-29

how can I show my choices in the "select" input for a form?

And why can't I access the DateInput to set a Input as a datepicker in the form, like I do for "grund" as "Select"?

Code:

from django import forms
from django.forms.widgets import DateInput
from .models import expense

class DateInput(forms.DateInput):                   
    input_type = 'date'

class ExpenseForm(forms.ModelForm):
    class Meta:
        model = expense

        CHOICES = (
            ('ME', '1'),
            ('YOU', '2'),
            ('WE', '3'),
        )

        fields = [
            'datum',
            'grund',
            'beschreibung_grund',
            'summe_ausgabe'
        ]

        widgets = {
            'datum': DateInput(),
            'grund': forms.Select
        }

CodePudding user response:

It not answer to your question, but its the way you can handle forms without using django forms. I'm not using then, because it's complicated.

In your html do something like that:

Create the form

<form action="{% url 'url_to_django_view' %}" method='POST'>
  <input type="text" name='name_to_call'>
  <button type='submit'> submit </button>
</form>

Create the view to handle form

def django_view(request):
    if request.method == 'POST':
       form_info = request.POST['name_to_call']
       # do the stuff 
       return redirect('url_to_redirect') #or any other actions, like return context 
         # with calculated data

Its the way you can handle and kind of input without django forms. It's more easy to understand

CodePudding user response:

I think if you use html form directly to make POST request instead of using Django form, it will be easy for you. My idea is, create a model in model.py with necessery field name you want it to see it in the select options. Migrate and create some objects, call all the objects in the view using ORM and render it to the template. In the template, unpack the objects using for loop and you may use object ID in the value of option Tag and object itself between the option tag which will be shown as select items in the template. Let me know, if you need codes.

  • Related