Home > Enterprise >  How to get username and user email in my form Django
How to get username and user email in my form Django

Time:12-31

I have "creating order form" which is need email and username to purchase. I want to push request username and user email into this form (if user is authorized)

forms.py

class OrderCreateForm(forms.ModelForm):
    username = forms.CharField(label='Имя пользователя', widget=forms.TextInput(attrs={'class': 'form-control'}))
    email = forms.EmailField(label='E-mail', widget=forms.EmailInput(attrs={'class': 'form-control'}))
    vk_or_telegram = forms.CharField(label='Введите ссылку на vk или telegram для связи с админом',
                                     widget=forms.TextInput(attrs={'class': 'form-control'}))

    captcha = ReCaptchaField()


    class Meta:
        model = Order
        fields = ('username', 'email', 'vk_or_telegram')

views.py

def order_create(request):
    cart = Cart(request)

    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            order = form.save()
            for item in cart:
                OrderItem.objects.create(order=order, product=item['post'], price=item['price'])

            cart.clear()
            return render(request, 'store/orders/created.html', {'order': order})
    else:
        form = OrderCreateForm()

    return render(request, 'store/orders/create.html', {'cart': cart, 'form': form})

template of form

CodePudding user response:

You can give initial parameters to the form, which will be prefilled in the form.

First, check if the user is authenticated and if so, push the initial values to the form using the initial argument.

def order_create(request):

    # ...
    if request.method == 'POST':
        # ...
    else:

        # only if the user is logged in, we prepopulate the form
        if request.user.is_authenticated:
            initial = { 
                'username' : request.user.username,
                'email' : request.user.email
            }
        else:
        # else, we just give an empty dict
            initial = {}
        
        form = OrderCreateForm(initial=initial)
        
    # ...

However, ask yourself the question if this is the best approach for your problem. Any user can still alter the username and email field to something else. If you don't want users to be able to manipulate the fields, you could use a ForeignKey to the user table for each order.

  • Related