Credit card validation form error at deleteDelete an element from a dictionaryDelete a file or folderDjango model form is_valid() in specific databaseValueError: not enough values to unpack (expected 2, got 1)filter manytomanyfield form 'str' object has no attribute 'get'Django - No such table: main.auth_user__oldError in function “int() argument must be a string”Django DateField TypeError expected string or bytes-like objectMultiValueDictKeyError at /count/ while using .GET[]
My employer faked my resume to acquire projects
What are the real benefits of using Salesforce DX?
Is the Starlink array really visible from Earth?
Were pens caps holes designed to prevent death by suffocation if swallowed?
Defining the standard model of PA so that a space alien could understand
Plot twist where the antagonist wins
I unknowingly submitted plagarised work
Using credit/debit card details vs swiping a card in a payment (credit card) terminal
Is the Indo-European language family made up?
Image processing: Removal of two spots in fundus images
Why were helmets and other body armour not commonplace in the 1800s?
Crossing US border with music files I'm legally allowed to possess
Is neural networks training done one-by-one?
Is there another way of saying "to take refuge in alcohol"?
Have 1.5% of all nuclear reactors ever built melted down?
Employer demanding to see degree after poor code review
Why colon to denote that a value belongs to a type?
Where have Brexit voters gone?
Compactness of finite sets
What is the largest (size) solid object ever dropped from an airplane to impact the ground in freefall?
How to illustrate the Mean Value theorem?
Why does this if-statement combining assignment and an equality check return true?
Use backslash or single-quotes for field separation
pic versus macro in TikZ
Credit card validation form error at delete
Delete an element from a dictionaryDelete a file or folderDjango model form is_valid() in specific databaseValueError: not enough values to unpack (expected 2, got 1)filter manytomanyfield form 'str' object has no attribute 'get'Django - No such table: main.auth_user__oldError in function “int() argument must be a string”Django DateField TypeError expected string or bytes-like objectMultiValueDictKeyError at /count/ while using .GET[]
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I'm not sure where the error is coming from, if the models, forms or views, most likely the form. I got the editing the form working, also adding a new credit card works, but when I try to delete a credit card object I get this error:
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'
And this is my 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 %
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
<div class="form-group">
<button class="btn btn-danger" type="submit">Delete</button>
</div>
</form>
It's telling me that I have an error on the line that says: number = self.cleaned_data['number']. How can I fix this error? This only happens when I delete a credit card object.
Thank you
python django django-models django-forms django-views
add a comment |
I'm not sure where the error is coming from, if the models, forms or views, most likely the form. I got the editing the form working, also adding a new credit card works, but when I try to delete a credit card object I get this error:
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'
And this is my 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 %
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
<div class="form-group">
<button class="btn btn-danger" type="submit">Delete</button>
</div>
</form>
It's telling me that I have an error on the line that says: number = self.cleaned_data['number']. How can I fix this error? This only happens when I delete a credit card object.
Thank you
python django django-models django-forms django-views
1
If you're deleting a credit card then maybe your code shouldn't get to this line in your view:if user_CreditCardForm.is_valid():which is causing the problem. Would you be able to share the relevant view and html to be able to help further?
– damores
Mar 24 at 8:38
I updated the code, thank you for helping me
– Arturo
Mar 24 at 16:16
@damores any luck?
– Arturo
Mar 24 at 20:11
add a comment |
I'm not sure where the error is coming from, if the models, forms or views, most likely the form. I got the editing the form working, also adding a new credit card works, but when I try to delete a credit card object I get this error:
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'
And this is my 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 %
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
<div class="form-group">
<button class="btn btn-danger" type="submit">Delete</button>
</div>
</form>
It's telling me that I have an error on the line that says: number = self.cleaned_data['number']. How can I fix this error? This only happens when I delete a credit card object.
Thank you
python django django-models django-forms django-views
I'm not sure where the error is coming from, if the models, forms or views, most likely the form. I got the editing the form working, also adding a new credit card works, but when I try to delete a credit card object I get this error:
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'
And this is my 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 %
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
<div class="form-group">
<button class="btn btn-danger" type="submit">Delete</button>
</div>
</form>
It's telling me that I have an error on the line that says: number = self.cleaned_data['number']. How can I fix this error? This only happens when I delete a credit card object.
Thank you
python django django-models django-forms django-views
python django django-models django-forms django-views
edited Mar 24 at 16:15
Arturo
asked Mar 24 at 5:25
ArturoArturo
364212
364212
1
If you're deleting a credit card then maybe your code shouldn't get to this line in your view:if user_CreditCardForm.is_valid():which is causing the problem. Would you be able to share the relevant view and html to be able to help further?
– damores
Mar 24 at 8:38
I updated the code, thank you for helping me
– Arturo
Mar 24 at 16:16
@damores any luck?
– Arturo
Mar 24 at 20:11
add a comment |
1
If you're deleting a credit card then maybe your code shouldn't get to this line in your view:if user_CreditCardForm.is_valid():which is causing the problem. Would you be able to share the relevant view and html to be able to help further?
– damores
Mar 24 at 8:38
I updated the code, thank you for helping me
– Arturo
Mar 24 at 16:16
@damores any luck?
– Arturo
Mar 24 at 20:11
1
1
If you're deleting a credit card then maybe your code shouldn't get to this line in your view:
if user_CreditCardForm.is_valid(): which is causing the problem. Would you be able to share the relevant view and html to be able to help further?– damores
Mar 24 at 8:38
If you're deleting a credit card then maybe your code shouldn't get to this line in your view:
if user_CreditCardForm.is_valid(): which is causing the problem. Would you be able to share the relevant view and html to be able to help further?– damores
Mar 24 at 8:38
I updated the code, thank you for helping me
– Arturo
Mar 24 at 16:16
I updated the code, thank you for helping me
– Arturo
Mar 24 at 16:16
@damores any luck?
– Arturo
Mar 24 at 20:11
@damores any luck?
– Arturo
Mar 24 at 20:11
add a comment |
1 Answer
1
active
oldest
votes
You can try knowing which form was submitted by adding the name attribute to the buttons:
<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>
Then in your view:
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
...
That way when you delete you won't get to if user_CreditCardForm.is_valid(): which is causing the problem.
1
That worked beautifully. Manyyyy thanks!!
– Arturo
Mar 24 at 23:32
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55320977%2fcredit-card-validation-form-error-at-delete%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can try knowing which form was submitted by adding the name attribute to the buttons:
<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>
Then in your view:
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
...
That way when you delete you won't get to if user_CreditCardForm.is_valid(): which is causing the problem.
1
That worked beautifully. Manyyyy thanks!!
– Arturo
Mar 24 at 23:32
add a comment |
You can try knowing which form was submitted by adding the name attribute to the buttons:
<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>
Then in your view:
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
...
That way when you delete you won't get to if user_CreditCardForm.is_valid(): which is causing the problem.
1
That worked beautifully. Manyyyy thanks!!
– Arturo
Mar 24 at 23:32
add a comment |
You can try knowing which form was submitted by adding the name attribute to the buttons:
<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>
Then in your view:
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
...
That way when you delete you won't get to if user_CreditCardForm.is_valid(): which is causing the problem.
You can try knowing which form was submitted by adding the name attribute to the buttons:
<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>
Then in your view:
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
...
That way when you delete you won't get to if user_CreditCardForm.is_valid(): which is causing the problem.
answered Mar 24 at 22:38
damoresdamores
1,5412921
1,5412921
1
That worked beautifully. Manyyyy thanks!!
– Arturo
Mar 24 at 23:32
add a comment |
1
That worked beautifully. Manyyyy thanks!!
– Arturo
Mar 24 at 23:32
1
1
That worked beautifully. Manyyyy thanks!!
– Arturo
Mar 24 at 23:32
That worked beautifully. Manyyyy thanks!!
– Arturo
Mar 24 at 23:32
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55320977%2fcredit-card-validation-form-error-at-delete%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
If you're deleting a credit card then maybe your code shouldn't get to this line in your view:
if user_CreditCardForm.is_valid():which is causing the problem. Would you be able to share the relevant view and html to be able to help further?– damores
Mar 24 at 8:38
I updated the code, thank you for helping me
– Arturo
Mar 24 at 16:16
@damores any luck?
– Arturo
Mar 24 at 20:11