简体   繁体   English

Django将ModelForm显示为html表单

[英]Django show ModelForm as html form

I am trying to do a very simple django webpage where a user fills 2 fields of a form with two numbers, submits them and gets a result at the third field. 我正在尝试做一个非常简单的django网页,其中用户用两个数字填充表单的2个字段,提交并在第三个字段中得到结果。 I am using ModelForms. 我正在使用ModelForms。

For the moment I am only interested in the first part, where the user navigates to the url and is prompted a page with the empty form. 目前,我仅对第一部分感兴趣,在第一部分中,用户导航到url,并被提示带有空白表格的页面。 I do the following, but the page I see at my browser has no form, and only the submit button. 我执行以下操作,但是在浏览器中看到的页面没有表单,只有提交按钮。 I don't know if that's because the ModelForm I try to embed in the html code is still empty, but I tried to give it default values and it still didn't work. 我不知道这是否是因为我尝试嵌入html代码中的ModelForm仍然为空,但是我尝试为其提供默认值,但它仍然无法正常工作。 Any help will be very appreciated! 任何帮助将不胜感激! :) :)

urls.py: urls.py:

urlpatterns = patterns('',
    url(r'^calculator/', views.calculate)
)

models.py: models.py:

class Calc(models.Model):
    field1 = forms.CharField()
    field2 = forms.CharField()
    field3 = forms.CharField()   

class CalcForm(ModelForm):
    class Meta:
        model = Calc

views.py: views.py:

def calculate(request):
    c = CalcForm()
    if request.method == 'POST':
        #do the math
        #return ...
    else:
        return render_to_response('home.html', {'calculator': c}) 

home.html: home.html:

<form action="/calculator/" method="post"> 
<table>
{{ calculator }}<!--I also tried .as_p, .as_ul...-->
</table>
<input type="submit" value="Submit" />
</form>

您的模型应使用models.CharField,而不是form.CharField。

change the following: 更改以下内容:

class Calc(models.Model):
    field1 = forms.CharField()
    field2 = forms.CharField()
    field3 = forms.CharField()

to

class Calc(models.Model):
    field1 = models.CharField(max_length=10)
    field2 = models.CharField(max_length=10)
    field3 = models.CharField(max_length=10)

Did you ever syncdb with the above code? 您是否曾经与上述代码syncdb过? Because if you would've, it must have thrown an error. 因为如果您愿意,它肯定会引发错误。 This makes me think if your db has the correct tables or not. 这让我思考您的数据库是否具有正确的表。 Make sure you syncdb after the above change. 完成上述更改后,请确保您syncdb

Also, you should always check if an instance exist, This will also help you troubleshoot that if the object was correctly passed or not: 另外,您应始终检查实例是否存在,这还将帮助您解决是否正确传递了对象的问题:

{% if calculator %}
    <h3>Calculation Form</h3>
    <form action="/calculator/" method="post"> 
        <table>
            {{ calculator }}
        </table>
        <input type="submit" value="Submit" />
    </form>
{% endif %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM