2017-12-14 13 views
1

내 장고 앱에 스트라이프 결제 처리를 통합하려고하는데 고객의 카드를 확인하는 '올바른'방법을 알 수 없습니다. 정보를 입력하고 사용자의 스트라이프 고객 ID가 포함 된 행을 내 사용자 테이블에 삽입하십시오.Django가있는 스트라이프 - 양식 필드가 아닌 양식 clean() 메소드 반환 값을 만듭니다.

이상하게도, CheckoutForm이 카드 세부 정보를 확인하고 올바르지 않은 경우 ValidationError 양식을 제기하는 다음 행을 따라 뭔가를하고 싶습니다. 그러나이 솔루션을 사용하면 clean() 함수에서 생성 된 customer.id를 가져 오는 방법을 찾을 수 없습니다.

forms.py 내가 생각할 수있는 유일한 해결책은 뷰의 stripe.Customer.create() 함수를 실행하는 것입니다

# If the form is valid... 
if form.is_valid(): 

    # Create a new user 
     user = get_user_model().objects.create_user(email=form.cleaned_data['email'], stripe_customer_id=<<<I want the customer.id generated in my form's clean() method to go here>>>) 
     user.save() 

class CheckoutForm(forms.Form): 
    email = forms.EmailField(label='E-mail address', max_length=128, widget=forms.EmailInput(attrs={'class': 'form-control'})) 
    stripe_token = forms.CharField(label='Stripe token', widget=forms.HiddenInput) 

    def clean(self): 
     cleaned_data = super().clean() 
     stripe_token = cleaned_data.get('stripe_token') 
     email = cleaned_data.get('email') 

     try: 

      customer = stripe.Customer.create(
       email=email, 
       source=stripe_token, 
      ) 
      // I can now get a customer.id from this 'customer' variable, which I want to insert into my database 

     except: 
      raise forms.ValidationError("It looks like your card details are incorrect!") 

views.py .py 이후에 양식 유효성이 검사됩니다. 그게 작동 할거야,하지만 그것을 이해하기 때문에 양식 필드의 모든 유효성 검사는 forms.py 내에서 이루어지기 때문에, 코드화하는 것은 '옳은'방법처럼 보이지 않습니다.

이 상황에서 적절한 장고 코딩 연습은 무엇입니까? 나는 카드 유효성 검사 코드를 views.py로 옮겨야 하는가, 아니면 카드 유효성 검사 코드를 forms.py에 저장하고 customer.id를 빼내는 더 깨끗한 방법이 있을까?

답변

1

적절한 장고 코딩 연습은이 상황에서 파이썬 코딩 연습과 다른 점이라고 생각하지 않습니다. Django 폼은 클래스 일 뿐이므로 customer에 대한 속성을 정의 할 수 있습니다. 이런 식으로 뭔가 :

class CheckoutForm(forms.Form): 
    email = forms.EmailField(label='E-mail address', max_length=128, widget=forms.EmailInput(attrs={'class': 'form-control'})) 
    stripe_token = forms.CharField(label='Stripe token', widget=forms.HiddenInput) 

    _customer = None 

    def clean(self): 
     cleaned_data = super().clean() 
     stripe_token = cleaned_data.get('stripe_token') 
     email = cleaned_data.get('email') 

     try: 
      self.customer = stripe.Customer.create(
       email=email, 
       source=stripe_token, 
      ) 
     except: 
      raise forms.ValidationError("It looks like your card details are incorrect!") 

    @property 
    def customer(self): 
     return self._customer 

    @customer.setter 
    def customer(self, value): 
     self._customer = value 

는 그런 다음 views.py form.is_valid() 후,이 속성을 호출 것입니다.

if form.is_valid(): 
    customer = form.customer 

아니면 @property은 과잉이고 당신은 이런 식으로 할 단순히 수 :

class CheckoutForm(forms.Form): 
    email = forms.EmailField(label='E-mail address', max_length=128, widget=forms.EmailInput(attrs={'class': 'form-control'})) 
    stripe_token = forms.CharField(label='Stripe token', widget=forms.HiddenInput) 

    customer = None 

    def clean(self): 
     cleaned_data = super().clean() 
     stripe_token = cleaned_data.get('stripe_token') 
     email = cleaned_data.get('email') 

     try: 
      self.customer = stripe.Customer.create(
       email=email, 
       source=stripe_token, 
      ) 
     except: 
      raise forms.ValidationError("It looks like your card details are incorrect!") 

... 그리고 views.py 여전히 form.customer.

둘 다 작동해야하지만 코드를 테스트하지 않았습니다.

+0

알았어 - 완전히 이해가된다, 보루트! 응답 주셔서 감사합니다, 나는 이것을 정답으로 받아 들였습니다. 신속한 후속 조치 : clean() 메서드에서 구문 분석 논리를 모두 포함하도록 '적절한 장고 코딩 연습'을 고려할 것입니까? 예를 들어, 모든 'user ='코드 블록을 views.py에서 forms.py의 clean() 메소드로 이동해야합니까? – Sam

+0

폼 검증과 관련된 모든 것을'clean()'안에 포함시키는 것이 좋습니다. 보기에서 양식 (또는 사용자가 게시 한 데이터)의 유효성을 검사하면 안됩니다. 'clean()'에서'user' 유효성 검사를 포함하는 것에 관해서; 나는 내 프로젝트 중 몇 가지를 확인해 보았고, 내가 그 일을하거나 내게 의미가있는 많은 사례를 발견하지 못했다. – Borut

+0

훌륭합니다. 도와 줘서 고마워! – Sam