如何使用数据库值在django中创建自定义表单

时间:2014-02-23 13:48:40

标签: python django django-templates django-views django-urls

model.py

class Venue(models.Model):
    venue_Name = models.CharField(max_length=100)
    place = models.CharField(max_length=50)
    rent = models.IntegerField()
    parking_area = models.IntegerField()


class Decoration(models.Model):
    rate = models.IntegerField()

我已经在数据库中打印了数据作为单选按钮,我想要做的是我想得到总和,即venue.rent + decoration.rate并将其打印在另一页中我在表单行动中给出了什么?我不熟悉表格。

HTML

 <form action="{%  %}" method="post">
 {% for venue in venues %}
 <input type="radio" name=venue value=venue.rent />{{  venue.venue_Name}}
 {% endfor %}

{% for decoration in decorations %}
<input type="radio" name=decor value=decoration.rate />{{  decoration.rating }}
{% endfor %}
<input type="submit" value=" " />
</form>

我应该在视图和网址中写什么来获得总和

1 个答案:

答案 0 :(得分:1)

您可以使用Django的表单进行验证和解析。为此你可以设置一个这样的表格:

forms.py

from django import forms

class TotalSumForm(forms.Form):
    venue = forms.ModelChoiceField(queryset=Venue.objects.all(), required=True)
    decoration = forms.ModelChoiceField(
        queryset=Decoration.objects.all(), required=True)

    def get_total(self):
        # send email using the self.cleaned_data dictionary
        return self.cleaned_data['venue'].rent +\
               self.cleaned_data['decoration'].rate

然后使用基于类的视图,在提交时将结果添加到上下文中。

views.py

from myapp.forms import TotalSumForm(
from django.views.generic.edit import FormView

class TotalCost(FormView):
    template_name = 'your_template.html'
    form_class = TotalSumForm
    success_url = '/thanks/'

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        total_result = form.get_total()
        # return back to your_template.html with the total in context
        return self.render_to_response(self.get_context_data(
            form=form, total=total_result))

网址非常简单:

urls.py

from django.conf.urls import patterns, url

import myapp.views

urlpatterns = patterns(
    '',
    url(r'^total_calc/$', myapp.views.TotalCost.as_view(), name='calculate_total'),
)

你的html可以像这样修改

your_template.html

<html>
    <body>
        <h1>TEST SUCCESFULL!</h1>
            {% if total %}
        <p>Total cost for venue and decoration: {{ total }}</p>
    {% endif %}
        <form action="{% url 'calculate_total' %}" method="post">
            {{ form.as_p }}
            <input type="submit" value="Calculate Total" />
        </form>
    </body>
</html>