英文:
Auto pre-fill form Django
问题
To pre-fill form fields in Django using the initial
parameter, you can modify your OrderCreateForm
in your Django forms.py like this:
class OrderCreateForm(forms.ModelForm):
class Meta:
model = Order
fields = ['first_name', 'last_name', 'email', 'address', 'postal_code', 'city']
def __init__(self, *args, **kwargs):
super(OrderCreateForm, self).__init__(*args, **kwargs)
if self.instance:
# Pre-fill the form fields with data from the User class
self.fields['first_name'].initial = self.instance.user.first_name
self.fields['last_name'].initial = self.instance.user.last_name
self.fields['email'].initial = self.instance.user.email
This code ensures that the first_name
, last_name
, and email
fields in your order form are pre-filled with the corresponding data from the User class when forming the order form.
英文:
How to pre-fill form fields in Django. What would be the pre-filled data from the User class when forming the order form.
my view
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})
my form
class OrderCreateForm(forms.ModelForm):
class Meta:
model = Order
fields = ['first_name', 'last_name', 'email',
'address', 'postal_code', 'city']
my teplate
<form action="." method="post" class="order-form">
{{ form.as_p }}
<p><input type="submit" value="Place order"></p>
{% csrf_token %}
</form>
Im try to use initial but with no result.
答案1
得分: 0
通过在创建表单实例时使用 initial 参数来传递“预填充”数据。
form = OrderCreateForm(initial={
'first_name': user.first_name,
'email': user.email,
})
英文:
Pass your "pre-fill" data using the initial argument when creating your form instance
form = OrderCreateForm(initial={
'first_name': user.first_name,
'email': user.email,
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论