欢迎朋友们,
我是Django的新手。我需要你的帮助。严重。
我想在表单中添加复选框和单选按钮。
任何帮助将不胜感激。
models.py
from django.db import models
from shop.models import Product
class Order(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
address = models.CharField(max_length=250)
postal_code = models.CharField(max_length=20)
city = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
class Meta:
ordering = ('-created',)
def __str__(self):
return 'Order {}'.format(self.id)
def get_total_cost(self):
return sum(item.get_cost() for item in self.items.all())
forms.py
from django import forms
from .models import Order
class OrderCreateForm(forms.ModelForm):
class Meta:
model = Order
fields = ['first_name', 'last_name', 'email', 'address', 'postal_code', 'city']
create.html上
{% extends "shop/base.html" %}
{% block title %}
Checkout
{% endblock %}
{% block content %}
<h1>Checkout</h1>
<form action="." method="post" class="order-form">
{{ form.as_p }}
<p><input type="submit" value="Place order"></p>
{% csrf_token %}
</form>
{% endblock %}
欢迎任何建议。请帮助。
更新
如何添加选择选项?
答案 0 :(得分:3)
你可以做这样的事情
CHOICES=[('item1','item 1'),
('item2','item 2')]
class OrderCreateForm(forms.ModelForm):
postal_code = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())
....
class Meta:
model = Order
fields = ['first_name', 'last_name', 'email', 'address', 'postal_code', 'city']
同样,您也可以为其他字段做
和复选框,您可以将其定义为BooleanFileld,您可以使用
{{ form.paid }}
在你的模板中。
答案 1 :(得分:1)
表单将使用您在模型中定义的字段类型进行呈现:
您可以在OrderCreateForm类中重新定义小部件:
CHOICES = [('option1','label 1'), ('option2','label 2')]
some_field = forms.ChoiceField(choices=CHOICES,widget=forms.RadioSelect())