如何在Django的表单中添加下拉列表?

时间:2019-03-06 08:17:24

标签: ajax django database forms dropdown

我有一个允许用户使用Django将新记录插入数据库的表格。

表单正在正常工作。

并且我有一个下拉列表国家/地区,该国家/地区已预先填充了数据库中的数据,并且可以正常工作。

现在我想在表单中输入下拉列表,以允许用户从中选择。

我该怎么办?

models.py

class Country(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return str(self.name)


    class Person(models.Model):
        boolChoice = (
            ("M","Male"),("F","Female")
            )

        name = models.CharField(max_length=50)
        date = models.DateField()
        description = models.TextField()
        gender = models.CharField(max_length = 1,choices=boolChoice)
        country = models.ForeignKey("Country", on_delete = models.CASCADE)

addPerson.html

{% extends 'base.html' %}

{% block content %}

<div class="hero__content">
   <form method="POST" class="form-style-9">{% csrf_token %}
        {{ form.as_p }}


<ul>

    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<li>
    {# <input type="number" name="field1" class="field-style field-split align-right" placeholder="اﻟﺴﻨﺔ" id="year"/> #}
    {# <input type="date" name="field2" class="field-style field-split align-left" placeholder="اﻟﺘﺎﺭﻳﺦ" id="date" /> #}
    <h2>Add Member</h2>

</li>

<li>
    <input type="text" name="name" class="field-style field-split align-right" placeholder= "enter ur name " id="name"/>
</li>
<li>
    <input type="date" name="date" class="field-style field-full align-none" placeholder= " your birthdate" id="birthdate" />

</li>
<li>
    <input type="radio" name="gender"  value="M"> Male<br>
    <input type="radio" name="gender"  value="F"> Female<br>

</li>

<li>
<textarea name="description" class="field-style" placeholder= "introduce yourself " id="description"></textarea>
</li>

<li>
<input type="submit" class="field-style field-full align-none" id="save" value="ADD" />
    <script type="text/javascript">
                 $(function(){
                    $('#save').on('click',function(e){
                        e.preventDefault()
                        name=$('#name').val()
                        birthdate=$('#birthdate').val()
                        description=$('#description').val()
                        radioValue = $("input[name = 'gender']:checked").val()
                        if (radioValue){
                            alert("radioValue =", radioValue)
                        }


     $.ajax({
      url:'/addperson/',
      method:'POST',
      data: {

                na:name,
                bi:birthdate,
                de:description,
                ra:radioValue,
          },
      headers:{
       'X-CSRFToken':'{{csrf_token}}'
      }
     }).done(function(msg) {
                        document.location = "/addPerson.html"     
                        alert('ﻟﻘﺪ ﺗﻢّ ﺣﻔﻆ اﻟﻤﻌﻠﻮﻣﺎﺕ')


     }).fail(function(err){
      alert('ﻟﻢ ﻳﺘﻢ اﻟﺤﻔﻆ')
     })
    })

})
</script>
</li>
    </ul>
</form>

  </div>


{% endblock %}

views.py

def addPerson(request):
    print("request method = " , request.method)
    countries = Country.objects.all()
    print (countries)
    if request.method == "POST":
        name = request.POST['na']
        birthdate = request.POST['bi']
        description=request.POST['de']
        gender=request.POST['ra']

        person=Person.objects.create(
            name=name,
            date=birthdate,
            description=description,
            gender = gender,
        )
        print("name  = ", name + "birthdate = " , birthdate + "dec = ", description + "gender = " , gender)
        person.save()
        return render(request,'./addPerson.html',{'countries': countries})
    else:
        print("this is a get METHOD")

1 个答案:

答案 0 :(得分:0)

我可以看到您正在返回带有响应的列表,很好。您需要使用该方法; render_to_response('template / path',{'countries':国家,})。然后,您可以访问此模板中的“国家”,并使用模板进行循环渲染HTML

return render_to_response(templates/path.html', {'countries': countries })


<h1>All available countries</h1>
<ul>
  {% for country in countries %}
    <li>{{ country.name}}</li>
  {% endfor %}
</ul>