Search code examples
pythonpython-3.xdjangodjango-viewsdjango-forms

DJANGO: the combobox doesn't print in the textarea. Error in in html?


In the home.html page, i have a combobox and a textarea. I would like to achieve that if i click on an item in the combobox, using an (if) condition in views.py, i get the printout in the textarea. For example if I select "Red" then it must print "You chose red". Very simple. But there is something wrong with my code. Probably the problem is in the home.html file or in the def home function in the views.py file (i believe).

enter image description here

Problem: combobox(independent and NOT attached to a database) correctly browses items from list, but the condition doesn't apply. When I click on button, nothing happens.

How can I execute the condition correctly and print in the textarea when I select the combobox item? I'm new to django, can you show me an answer with the code please?

Post the code of home.html, views.py and forms.py. I hope someone can help me please. I think the problem is in the html! Thank you!

home.html

<form method="post">
  {% csrf_token %}
  {{ combobox }}
  <button type="submit">submit</button>
</form>

<form method="post">
  {% csrf_token %}
  {{ textarea }}
</form>

views.py

colours = ["Red", "Blue", "Black", "Orange"]

@login_required
def home(request):

    #Combobox
    if request.method == "POST":
        combobox = SimpleCombobox(request.POST)
        if combobox.is_valid():
            print(combobox.cleaned_data)
            return redirect("home")
    else:
        combobox = SimpleCombobox()


    #TextArea
    if request.method == "POST":
        textarea = SimpleTextbox(request.POST)
        if textarea.is_valid():
            print(textarea.cleaned_data)
            return redirect("home")
    else:
        textarea = SimpleTextbox()


    message = ""
    picked = ""
    if request.method == 'POST':
        picked = request.form['colours']
        if picked == 'Red':
            message = "<<< You chose red"
        elif picked == 'Blue':
            message = "<<< You chose blue"
        elif picked == 'Black':
            message = "<<< You chose black"
        else:
            message = "<<< Oh no, you chose orange"

    return render(request, 'app1/home.html', {"combobox": combobox, "textarea": textarea, "colours": colours, "chosen": picked, "message": message})

forms.py

from django import forms


class SimpleCombobox(forms.Form):
    Col1 = 'Red'
    Col2 = 'Blue'
    Col3 = 'Black'
    Col4 = 'Orange'
      
    COLOR_CHOICES = (
        (Col1, u"Red"),
        (Col2, u"Blue"),
        (Col3, u"Black"),
        (Col4, u"Orange"),
    )
    cities = forms.ChoiceField(choices=COLOR_CHOICES)


class SimpleTextbox(forms.Form):
    coverletter = forms.CharField(required=False,
              widget=forms.Textarea(
                # rows and colums of the textarea
                attrs={'rows': 4, 'cols': 40}))
    

#LOGIN
class LoginForm(forms.Form):
    username = forms.CharField(max_length=65)
    password = forms.CharField(max_length=65, widget=forms.PasswordInput)

UPDATE ONLY FOR INFO

For info, if it could help for the answer, I previously use this code html on Flask and it worked fine (I use the same combobox, textarea and condition but with Flask and it worked fine)

    <form name="Item_1" action="/user/home" method="POST">
      <select name="colours">
        {% for colour in colours %}
          {% if colour == chosen %}
           <option value="{{ colour }}" SELECTED>{{ colour }}</option>
         {% else %}
           <option value="{{ colour }}">{{ colour }}</option>
          {% endif %}     
        {% endfor %}     
     </select>
     <input type="submit">
  </form>
    
  <form action = "/result" method = "POST">
    <input type="text" name="result" value="{{ message }}" />
  </form>

Solution

  • #views.py

    def DemoView(request):
      color_choices = ("Red","Blue","Black","Orange")
      message =''
      if request.method =="POST":
        picked = request.POST.get('color')
        if picked == 'Red':
          message = "<<< You chose red"
          print(message)
        elif picked == 'Blue':
            message = "<<< You chose blue"
        elif picked == 'Black':
            message = "<<< You chose black"
        else:
            message = "<<< Oh no, you chose orange"
      context = {'message':message,'color_choices':color_choices}
      return render(request, 'index.html', context)
    

    HTML code

    <div class="container p-5">
      <div class="row mx-auto">
        <div class="col-6">
          <form action="" method="POST" novalidate class="form-group">
            {% csrf_token %}
            <select name="color" class="form-select" >
              {% for i in color_choices %}
              <option value="{{i}}">{{i}}</option>
              {% endfor %}
            </select>
            <textarea class="form-control" name="msg" cols="30" rows="10">{{message}}</textarea>
            <button class="btn btn-primary mt-3" type="submit">Submit</button>
          </form>
        </div>
      </div>
    </div>

    Output

    enter image description here