DJANGO:下拉框不会在文本区域中打印。在HTML中出现错误吗?

huangapple go评论62阅读模式
英文:

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

问题

home.html页面中,我有一个combobox和一个textarea。我想要实现的是,如果我点击combobox中的某个项目,在views.py中使用条件语句,我希望在textarea中打印出相应的内容。例如,如果我选择"Red",它应该打印出"You chose red"。非常简单。但是我的代码似乎有问题。问题可能出现在home.html文件或views.py文件中的def home函数中(我认为是这里)。

问题: combobox(独立于数据库且未附加)可以正确浏览列表中的项目,但条件不适用。当我点击按钮时,没有任何反应。

请问如何正确执行条件并在选择combobox项目时在textarea中打印出内容?我是Django的新手,能否请你用代码示例给我一个答案?

请提供home.htmlviews.pyforms.py的代码。我希望有人能帮助我。我认为问题出在HTML中!谢谢!

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.POST['cities']
        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):
    COLOR_CHOICES = (
        ("Red", "Red"),
        ("Blue", "Blue"),
        ("Black", "Black"),
        ("Orange", "Orange"),
    )
    cities = forms.ChoiceField(choices=COLOR_CHOICES)

class SimpleTextbox(forms.Form):
    coverletter = forms.CharField(required=False, widget=forms.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)

请注意,我在代码中进行了一些修改以解决问题,特别是在处理POST请求时。希望这对你有帮助。

英文:

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).

DJANGO:下拉框不会在文本区域中打印。在HTML中出现错误吗?

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

&lt;form method=&quot;post&quot;&gt;
  {% csrf_token %}
  {{ combobox }}
  &lt;button type=&quot;submit&quot;&gt;submit&lt;/button&gt;
&lt;/form&gt;

&lt;form method=&quot;post&quot;&gt;
  {% csrf_token %}
  {{ textarea }}
&lt;/form&gt;

views.py

colours = [&quot;Red&quot;, &quot;Blue&quot;, &quot;Black&quot;, &quot;Orange&quot;]

@login_required
def home(request):

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


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


    message = &quot;&quot;
    picked = &quot;&quot;
    if request.method == &#39;POST&#39;:
        picked = request.form[&#39;colours&#39;]
        if picked == &#39;Red&#39;:
            message = &quot;&lt;&lt;&lt; You chose red&quot;
        elif picked == &#39;Blue&#39;:
            message = &quot;&lt;&lt;&lt; You chose blue&quot;
        elif picked == &#39;Black&#39;:
            message = &quot;&lt;&lt;&lt; You chose black&quot;
        else:
            message = &quot;&lt;&lt;&lt; Oh no, you chose orange&quot;

    return render(request, &#39;app1/home.html&#39;, {&quot;combobox&quot;: combobox, &quot;textarea&quot;: textarea, &quot;colours&quot;: colours, &quot;chosen&quot;: picked, &quot;message&quot;: message})

forms.py

from django import forms


class SimpleCombobox(forms.Form):
    Col1 = &#39;Red&#39;
    Col2 = &#39;Blue&#39;
    Col3 = &#39;Black&#39;
    Col4 = &#39;Orange&#39;
      
    COLOR_CHOICES = (
        (Col1, u&quot;Red&quot;),
        (Col2, u&quot;Blue&quot;),
        (Col3, u&quot;Black&quot;),
        (Col4, u&quot;Orange&quot;),
    )
    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={&#39;rows&#39;: 4, &#39;cols&#39;: 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)

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

答案1

得分: 1

#views.py

def DemoView(request):
    color_choices = ("红色", "蓝色", "黑色", "橙色")
    message = ''
    if request.method == "POST":
        picked = request.POST.get('color')
        if picked == '红色':
            message = '<<< 你选择了红色'
            print(message)
        elif picked == '蓝色':
            message = '<<< 你选择了蓝色'
        elif picked == '黑色':
            message = '<<< 你选择了黑色'
        else:
            message = '<<< 哦,不好,你选择了橙色'
    context = {'message': message, 'color_choices': color_choices}
    return render(request, 'index.html', context)

HTML code

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

<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">提交</button>
      </form>
    </div>
  </div>
</div>

<!-- end snippet -->

Output

DJANGO:下拉框不会在文本区域中打印。在HTML中出现错误吗?

英文:

#views.py

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

HTML code

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

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

<!-- end snippet -->

Output

DJANGO:下拉框不会在文本区域中打印。在HTML中出现错误吗?

huangapple
  • 本文由 发表于 2023年6月22日 15:01:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529318.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定