如何在Django中预填充表单字段。在形成订单表单时,从User类预填充的数据是什么?
The result need like this:
我的看法
def order_create(request):
cart = Cart(request)
user = request.user
if request.user.is_authenticated:
if request.method == 'POST':
form = OrderCreateForm(request.POST)
if form.is_valid():
order = form.save(commit=False)
if cart.coupon:
order.coupon = cart.coupon
order.discount = cart.coupon.discount
order.save()
for item in cart:
OrderItem.objects.create(order=order,
product=item['product'],
price=item['price'],
quantity=item['quantity'])
cart.clear()
order_created.delay(order.id)
request.session['order_id'] = order.id
return redirect(reverse('payment:process'))
else:
form = OrderCreateForm()
else:
return redirect('login')
return render(request,
'orders/order/create.html',
{'cart': cart, 'form': form})
我的形式
class OrderCreateForm(forms.ModelForm):
class Meta:
model = Order
fields = ['first_name', 'last_name', 'email',
'address', 'postal_code', 'city']
我的模板
<form action="." method="post" class="order-form">
{{ form.as_p }}
<p><input type="submit" value="Place order"></p>
{% csrf_token %}
</form>
我尝试使用初始化,但没有结果。
1条答案
按热度按时间hgb9j2n61#
创建表单示例时,使用初始参数传递“预填充”数据