【问题标题】:django form: default initial valuedjango形式:默认初始值
【发布时间】:2015-11-03 08:27:27
【问题描述】:

我现在正在使用 django 框架来构建筹款网站。

但是,我在现场遇到了一些问题。 我在模型中制作了不同的类。

我想输入表单默认值。

 {{ form.funding }} ..... -> problem 
 (<input value="{{ funding.price }}">) -> want to same form of this. 

详情请看模板。

例如,

models.py

class Fundinfo(models.Model):
    price = model.PositiveIntegerField(null= False)

class Funding(models.Model):
    funding = models.PositiveIntegerField(null= False)
    info = models.ForeignKey(Fundinfo)

forms.py

class FundingForm(forms.models.ModelForm):
    class Meta:
        model = Funding
        fields = ('funding', )

模板'funding.html'

{% for funding in fundings %}
    <h3>{{ funding.price }}or more</h3>
    <form method= "post" action="">
        {{ form.funding }} ..... -> problem 
        (<input value="{{ funding.price }}">) -> want to same form of this. 
        {% csrf_token %}
    {% if form.errors %}
        <div class = "help-block">{{ form.funding.errors }}</div>
    {% endif %}
    <button id = "" type = "submit">funding</button>
</form>
{% endfor %}

views.py

def view_funding(reqeust, project_id):
     fundings = FundInfo.objects.filter(project= project_id)
     form = PledgeForm() # How to use in here form = FundingForm(initial={'funding': form.funding.price})
     return render(request, 'funding.html', {
    'fundings': info,
    'form': form
    })

【问题讨论】:

  • 您遇到了什么问题?我在这里没有看到任何问题。
  • 一件事:你写的Foriegnkey应该是ForeignKey
  • 我想输入默认的表单值。与 form = FundingForm(initial= {'funding': form.funding.price}) 相同,但我必须放入模板..

标签: python django forms django-forms django-templates


【解决方案1】:

如果您想为表单字段提供一些初始值,请在表单中使用initial

Class MYform(forms.ModelForm):
    funding = forms.PositiveIntgerField(initial=10)

这就是你如何为表单分配初始值的方式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 2014-12-29
    • 1970-01-01
    • 2018-05-17
    相关资源
    最近更新 更多