Auto pre-fill form Django

Question:

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.

Asked By: chazzy

||

Answers:

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,
})
Answered By: Iain Shelvington
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.