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

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

模型.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()

我已经将数据库中的值打印为单选按钮,我想要做的是我想要获得总和,即 field .租金+装饰.率并将其打印在另一页中我应该在表单操作中给出什么I'我对表单不太熟悉。

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>

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

最佳答案

您可以使用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

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

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>

关于python - 如何使用数据库值在 django 中创建自定义表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21969051/

相关文章:

django - 如何防止 Django 自动转换日期时间

python - 使用 Beautiful Soup 提取链接的等效正则表达式

python - 计算字典键的总和

python - 使用 BeautifulSoup 根据 name 属性获取属性值

django - 如何配置 VS Code 以使用 Prettier HTML 格式化程序?

javascript mouseover 没有注册,但是 CSS 是

python - 获取应用程序的 Django 版本

python - 严格递增子序列的最小数量

python - 在 Django 的管理器中验证对象属性

python - 应用过滤器后引用 django-templates 中的键/值