如何在我的表单中获取用户名和用户邮箱Django

zlwx9yxi  于 2023-01-03  发布在  Go
关注(0)|答案(1)|浏览(121)

我有“创建订单”,这是需要电子邮件和用户名购买。我想推到这个表单请求用户名和用户电子邮件(如果用户被授权)
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

7gcisfzg

7gcisfzg1#

您可以为表单给予初始参数,这些参数将被预填充到表单中。
首先,检查用户是否经过身份验证,如果是,则使用initial参数将初始值推送到表单。

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)
        
    # ...

但是,请扪心自问,这是否是解决问题的最佳方法。任何用户仍然可以将usernameemail字段更改为其他内容。如果不希望用户能够操作这些字段,则可以对每个订单的用户表使用外键。

相关问题