Auto pre-fill form Django

huangapple go评论63阅读模式
英文:

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.

The result need like this:

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,
})

huangapple
  • 本文由 发表于 2023年3月31日 04:36:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75892789.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定