gpt4 book ai didi

python - 删除时信用卡验证表单出错

转载 作者:行者123 更新时间:2023-12-01 08:09:58 26 4
gpt4 key购买 nike

我不确定错误来自哪里,如果是模型、表单或 View ,很可能是表单。我可以编辑表单,还可以添加新的信用卡,但是当我尝试删除信用卡对象时,出现此错误:

Traceback:

File "/Users/Arturo/anaconda3/envs/SoftEngVEnv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)

File "/Users/Arturo/anaconda3/envs/SoftEngVEnv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)

File "/Users/Arturo/anaconda3/envs/SoftEngVEnv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/Arturo/anaconda3/envs/SoftEngVEnv/lib/python3.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)

File "/Users/Arturo/Documents/Arturo/Knowledge_center/Computer_Science/Projects/GitHub/Software Engineering 1/softwareEngineering_Group2/bookStore/users/views.py" in creditCardChange
185. if user_CreditCardForm.is_valid():

File "/Users/Arturo/anaconda3/envs/SoftEngVEnv/lib/python3.7/site-packages/django/forms/forms.py" in is_valid
185. return self.is_bound and not self.errors

File "/Users/Arturo/anaconda3/envs/SoftEngVEnv/lib/python3.7/site-packages/django/forms/forms.py" in errors
180. self.full_clean()

File "/Users/Arturo/anaconda3/envs/SoftEngVEnv/lib/python3.7/site-packages/django/forms/forms.py" in full_clean
382. self._clean_form()

File "/Users/Arturo/anaconda3/envs/SoftEngVEnv/lib/python3.7/site-packages/django/forms/forms.py" in _clean_form
409. cleaned_data = self.clean()

File "/Users/Arturo/Documents/Arturo/Knowledge_center/Computer_Science/Projects/GitHub/Software Engineering 1/softwareEngineering_Group2/bookStore/users/forms.py" in clean
121. number = self.cleaned_data['number']

Exception Type: KeyError at /settings/billing/creditcard/6/
Exception Value: 'number'

这是我的forms.py

class CreditCardForm(ModelForm):
def __init__(self, *args, **kwargs):
super(CreditCardForm, self).__init__(*args, **kwargs)

self.fields['name'].widget.attrs['placeholder'] = 'My Discover'
self.fields['number'] = forms.CharField(widget=forms.TextInput(
attrs={'id': 'creditcard-number'}))
self.fields['number'].widget.attrs[
'placeholder'] = '123456789'
self.fields['expdate_month'] = ChoiceField(choices=MONTHS)
self.fields['expdate_year'] = ChoiceField(choices=YEARS)
self.fields['securitycode'].widget.attrs[
'placeholder'] = '123'

class Meta:
model = CreditCard
fields = [
'name', 'number', 'expdate_month', 'expdate_year', 'securitycode'
]

def clean(self):
# errors
self.error_messages = []

# Card number block
number = self.cleaned_data['number']

visa_pattern = r'^4[0-9]{12}(?:[0-9]{3})?$'
mastercard_pattern = r'^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$'
americanexpress_pattern = r'^3[47][0-9]{13}$'
discover_pattern = r'^6(?:011|5[0-9]{2})[0-9]{12}$'

patterns_list = [
discover_pattern,
visa_pattern,
mastercard_pattern,
]
pattern_string = '|'.join(patterns_list)

pattern1 = re.compile(pattern_string) # 3 digits of security code
pattern2 = re.compile(
americanexpress_pattern) # four digits security code

if pattern1.match(str(number)):
security_code_pattern = re.compile(r'^[0-9]{3}$') # 3
elif pattern2.match(str(number)):
security_code_pattern = re.compile(r'^[0-9]{4}$') # 4
else:
security_code_pattern = None

if not pattern1.match(str(number)) and not pattern2.match(str(number)):
self.error_messages.append('Credit card number not valid')
# self._errors['number'] = 'Please enter a valid credit card number'

# Expiration date block
month = int(self.cleaned_data['expdate_month'])
year = int(self.cleaned_data['expdate_year'])
expdate = datetime.datetime(year, month, 1) # first day of the month
today = datetime.datetime.today()

if expdate < today:
self.error_messages.append('Card has expired')

# Security code block
security_code = self.cleaned_data['securitycode']

# if not security_code_pattern created or does not match the work the errors
if not security_code_pattern or not security_code_pattern.match(
str(security_code)):
self.error_messages.append('Invalid security code')
# self._errors[
# 'securitycode'] = 'Please verify the credit card security code'

self.error_message = ''
if len(self.error_messages):
self.error_message = ' & '.join(self.error_messages)
raise forms.ValidationError(' & '.join(self.error_messages))

return self.cleaned_data


class DeleteCreditCardConfirmation(forms.Form):
pass

views.py

@login_required
def creditCardChange(request, creditcard_slug):

# Gets name of the credit card based on id
currentCreditCard = CreditCard.objects.all().get(pk=creditcard_slug)

if request.method == 'POST':
user_CreditCardForm = CreditCardForm(request.POST, instance=currentCreditCard)

if user_CreditCardForm.is_valid():
user_CreditCardForm.save()
messages.success(request, f'Your address has been updated successfully')
return HttpResponseRedirect(request.path_info)
elif DeleteCreditCardConfirmation():
currentCreditCard.delete()
return redirect('settings:billing-settings')
else:
messages.warning(
request, f'There were some errors updating you credit card.')

else:
user_CreditCardForm = CreditCardForm(instance=currentCreditCard)

context = {
'creditcard_slug': creditcard_slug,
'user_CreditCardForm': user_CreditCardForm,
}
return render(request, 'users/creditCardChange.html', context)

html

   <form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{user_CreditCardForm |crispy}}
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Save changes</button>
</div>
</form>

<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{DeleteCreditCardConfirmation |crispy}}
<div class="form-group">
<button class="btn btn-danger" type="submit">Delete</button>
</div>
</form>

它告诉我,该行出现错误:number = self.cleaned_data['number']。我该如何修复这个错误?仅当我删除信用卡对象时才会发生这种情况。

谢谢

最佳答案

您可以通过向按钮添加 name 属性来尝试了解提交的表单:

<button class="btn btn-outline-info" type="submit" name="save_changes">Save changes</button>
...
<button class="btn btn-danger" type="submit" name="delete">Delete</button>

那么在你看来:

if request.method == 'POST': 
if 'save_changes' in request.POST: # handle editing form
user_CreditCardForm = CreditCardForm(request.POST, instance=currentCreditCard)

if user_CreditCardForm.is_valid():
...
elif 'delete' in request.POST: # handle deleting
...

这样,当您删除时,您将不会遇到导致问题的 if user_CreditCardForm.is_valid():

关于python - 删除时信用卡验证表单出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55320977/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com