如何让用户输入逗号 [英] How to allow user to input comma

查看:195
本文介绍了如何让用户输入逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型形式的交易。该事务模型有一个字段(DecimaField)。当我尝试输入 1,000 ,它不允许我保存数据,但没有显示错误,它只是刷新。我试图将本地化在模型中,但仍然不允许我。



如何允许表单接受逗号(1,000)?



这是我的代码: p>

forms.py

  class AddTransactionForm form.ModelForm):
amount = forms.DecimalField(localize = True)

class Meta:
model = Transaction
exclude =('envelope','uid '$)

def __init __(self,user,* args,** kwargs):
super(AddTransactionForm,self).__ init __(* args,** kwargs)
//其他代码

views.py



我试图在视图中替换逗号,然后再保存,但会给我一个错误。

  def transaction(request):
if request.method =='POST':
如果请求.pOST ['process'] =='addtrans':
tform = AddTransactionForm(request.user,
request.POST)
如果tform.is_valid():
如果请求.POST ['type'] =='withdraw':
trans = tform.save(commit = False)
trans.amount = 0 - trans.amount
trans.save()
messages.success(request,
事务创建成功)
else:
trans = tform.save()
messages.success(request,
事务创建成功)

如果不是trans.account:
env = Envelope.objects.get(
user = request.user,
name ='Unallocated Income')
trans.envelope = env
trans.save()
env.amount + = trans.amount
env.save()
messages.success(request,
Unallocate income save)
return HttpResponseRedirect(reverse('transactions:transaction'))

return render(request,'trans_list.html ',{
.........
})

我不想修改我的模型。在表单或视图中有一种方式吗?

解决方案

要处理您描述的情况的快速而肮脏的修复程序,您可以复制视图开头的 request.POST querydict,从输入中删除违规逗号,并将您调整的查询传递给表单构造函数 -

  def transaction(request):
if request.POST.method =='POST':
post = request.POST.copy( )
如果'amount'在帖子中:
post ['amount'] = pos ['amount']。replace(',','')
tform = AddTransactionForm(request.user ,post)
#...

(您不能更改请求.POST字典本身,因为它是 immutable )。


I have a modelform for transaction. That transaction model has a field for amount (DecimaField). When I try to enter 1,000 it doesn't allow me to save the data but no error shown, it just refresh. I try to put localize in the modelform but still it doesn't allow me.

How to allow the form to accept the comma (1,000)?

Here are my codes:

forms.py

class AddTransactionForm(forms.ModelForm):
    amount = forms.DecimalField(localize=True)

    class Meta:
        model = Transaction
        exclude = ('envelope', 'uid',)

    def __init__(self, user, *args, **kwargs):
        super(AddTransactionForm, self).__init__(*args, **kwargs)
        //other codes here

views.py

I tried also in views to replace comma before it totally save but it gives me an error.

def transaction(request):   
    if request.method == 'POST':
        if request.POST['process'] == 'addtrans':
            tform = AddTransactionForm(request.user, 
                                       request.POST)
            if tform.is_valid():
                if request.POST['type'] == 'withdrawal':
                    trans = tform.save(commit=False)
                    trans.amount = 0 - trans.amount
                    trans.save()
                    messages.success(request,
                        "Transaction created successfully.")
                else:
                    trans = tform.save()
                    messages.success(request,
                        "Transaction created successfully.")

                if not trans.account:
                    env = Envelope.objects.get(
                        user=request.user,
                        name='Unallocated Income')
                    trans.envelope = env
                    trans.save()
                    env.amount += trans.amount
                    env.save()
                    messages.success(request, 
                        "Unallocate income save")               
                return HttpResponseRedirect(reverse('transactions:transaction'))    

    return render(request, 'trans_list.html', {
        .........
    })  

I don't want to modified my model. Is there a way in forms or views?

解决方案

For a quick and dirty fix to handle the situation you describe, you could copy the request.POST querydict at the beginning of the view, remove the offending commas from the input, and pass your adjusted querydict to form constructor -

def transaction(request): 
    if request.POST.method == 'POST':
        post = request.POST.copy()
        if 'amount' in post:
            post['amount'] = pos['amount'].replace(',','')
        tform = AddTransactionForm(request.user, post)
        #...

(you can't change the request.POST dictionary itself as it's immutable).

这篇关于如何让用户输入逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆