We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Exception Type: AttributeError when trying to create a password after succeful payment 
Got this exception:
`Exception Type: AttributeError at /order/5d555f01-0f99-4821-b52f-98fa48efce4b/create-password/
Exception Value: 'NoneType' object has no attribute 'addresses'`



--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `saleor/registration/views.py`
Content:
```
1 from django.conf import settings
2 from django.contrib import messages, auth
3 from django.contrib.auth import views as django_views
4 from django.contrib.auth.decorators import login_required
5 from django.shortcuts import redirect
6 from django.utils.translation import ugettext_lazy as _
7 from django.template.response import TemplateResponse
8 
9 from saleor.cart.utils import find_and_assign_anonymous_cart
10 from .forms import LoginForm, SignupForm, SetPasswordForm
11 
12 
13 @find_and_assign_anonymous_cart()
14 def login(request):
15     kwargs = {
16         'template_name': 'account/login.html', 'authentication_form': LoginForm}
17     return django_views.login(request, **kwargs)
18 
19 
20 @login_required
21 def logout(request):
22     auth.logout(request)
23     messages.success(request, _('You have been successfully logged out.'))
24     return redirect(settings.LOGIN_REDIRECT_URL)
25 
26 
27 def signup(request):
28     form = SignupForm(request.POST or None)
29     if form.is_valid():
30         form.save(request=request)
31         messages.success(request, _('User has been created'))
32         return redirect(settings.LOGIN_REDIRECT_URL)
33     ctx = {'form': form}
34     return TemplateResponse(request, 'account/signup.html', ctx)
35 
36 
37 def password_reset(request):
38     template_name = 'account/password_reset.html'
39     post_reset_redirect = 'account_reset_password_done'
40     email_template_name = 'account/email/password_reset_message.txt'
41     subject_template_name = 'account/email/password_reset_subject.txt'
42     return django_views.password_reset(
43         request, template_name=template_name,
44         post_reset_redirect=post_reset_redirect,
45         email_template_name=email_template_name,
46         subject_template_name=subject_template_name)
47 
48 
49 def password_reset_confirm(request, uidb64=None, token=None):
50     template_name = 'account/password_reset_from_key.html'
51     post_reset_redirect = 'account_reset_password_complete'
52     set_password_form = SetPasswordForm
53     return django_views.password_reset_confirm(
54         request, uidb64=uidb64, token=token, template_name=template_name,
55         post_reset_redirect=post_reset_redirect,
56         set_password_form=set_password_form)
57
```

Path: `saleor/order/views.py`
Content:
```
1 import logging
2 
3 from django.conf import settings
4 from django.contrib import messages, auth
5 from django.contrib.auth.decorators import login_required
6 from django.db import transaction
7 from django.http import Http404, HttpResponseForbidden
8 from django.shortcuts import get_object_or_404, redirect
9 from django.template.response import TemplateResponse
10 from django.utils.translation import pgettext_lazy
11 from payments import PaymentStatus, RedirectNeeded
12 
13 from .forms import PaymentDeleteForm, PaymentMethodsForm, PasswordForm
14 from .models import Order, Payment
15 from .utils import check_order_status, attach_order_to_user
16 from ..core.utils import get_client_ip
17 from ..registration.forms import LoginForm
18 from ..userprofile.models import User
19 from . import OrderStatus
20 
21 logger = logging.getLogger(__name__)
22 
23 
24 def details(request, token):
25     orders = Order.objects.prefetch_related('groups__items',
26                                             'groups__items__product')
27     orders = orders.select_related('billing_address', 'shipping_address',
28                                    'user')
29     order = get_object_or_404(orders, token=token)
30     groups = order.groups.all()
31     return TemplateResponse(request, 'order/details.html',
32                             {'order': order, 'groups': groups})
33 
34 
35 def payment(request, token):
36     orders = Order.objects.prefetch_related('groups__items__product')
37     orders = orders.select_related('billing_address', 'shipping_address',
38                                    'user')
39     order = get_object_or_404(orders, token=token)
40     groups = order.groups.all()
41     payments = order.payments.all()
42     form_data = request.POST or None
43     try:
44         waiting_payment = order.payments.get(status=PaymentStatus.WAITING)
45     except Payment.DoesNotExist:
46         waiting_payment = None
47         waiting_payment_form = None
48     else:
49         form_data = None
50         waiting_payment_form = PaymentDeleteForm(
51             None, order=order, initial={'payment_id': waiting_payment.id})
52     if order.is_fully_paid():
53         form_data = None
54     payment_form = None
55     if not order.is_pre_authorized():
56         payment_form = PaymentMethodsForm(form_data)
57         # FIXME: redirect if there is only one payment method
58         if payment_form.is_valid():
59             payment_method = payment_form.cleaned_data['method']
60             return redirect('order:payment', token=order.token,
61                             variant=payment_method)
62     return TemplateResponse(request, 'order/payment.html',
63                             {'order': order, 'groups': groups,
64                              'payment_form': payment_form,
65                              'waiting_payment': waiting_payment,
66                              'waiting_payment_form': waiting_payment_form,
67                              'payments': payments})
68 
69 
70 @check_order_status
71 def start_payment(request, order, variant):
72     waiting_payments = order.payments.filter(status=PaymentStatus.WAITING).exists()
73     if waiting_payments:
74         return redirect('order:payment', token=order.token)
75     billing = order.billing_address
76     total = order.get_total()
77     defaults = {'total': total.gross,
78                 'tax': total.tax, 'currency': total.currency,
79                 'delivery': order.get_delivery_total().gross,
80                 'billing_first_name': billing.first_name,
81                 'billing_last_name': billing.last_name,
82                 'billing_address_1': billing.street_address_1,
83                 'billing_address_2': billing.street_address_2,
84                 'billing_city': billing.city,
85                 'billing_postcode': billing.postal_code,
86                 'billing_country_code': billing.country.code,
87                 'billing_email': order.user_email,
88                 'description': pgettext_lazy(
89                     'Payment description', 'Order %(order_number)s') % {
90                         'order_number': order},
91                 'billing_country_area': billing.country_area,
92                 'customer_ip_address': get_client_ip(request)}
93     variant_choices = settings.CHECKOUT_PAYMENT_CHOICES
94     if variant not in [code for code, dummy_name in variant_choices]:
95         raise Http404('%r is not a valid payment variant' % (variant,))
96     with transaction.atomic():
97         order.change_status(OrderStatus.PAYMENT_PENDING)
98         payment, dummy_created = Payment.objects.get_or_create(
99             variant=variant, status=PaymentStatus.WAITING, order=order,
100             defaults=defaults)
101         try:
102             form = payment.get_form(data=request.POST or None)
103         except RedirectNeeded as redirect_to:
104             return redirect(str(redirect_to))
105         except Exception:
106             logger.exception('Error communicating with the payment gateway')
107             messages.error(
108                 request,
109                 pgettext_lazy(
110                     'Payment gateway error',
111                     'Oops, it looks like we were unable to contact the selected'
112                     ' payment service'))
113             payment.change_status(PaymentStatus.ERROR)
114             return redirect('order:payment', token=order.token)
115     template = 'order/payment/%s.html' % variant
116     return TemplateResponse(request, [template, 'order/payment/default.html'],
117                             {'form': form, 'payment': payment})
118 
119 
120 @check_order_status
121 def cancel_payment(request, order):
122     form = PaymentDeleteForm(request.POST or None, order=order)
123     if form.is_valid():
124         with transaction.atomic():
125             form.save()
126         return redirect('order:payment', token=order.token)
127     return HttpResponseForbidden()
128 
129 
130 def create_password(request, token):
131     if request.user.is_authenticated():
132         return redirect('order:details', token=token)
133     order = get_object_or_404(Order, token=token)
134     email = order.user_email
135     form_data = request.POST.copy()
136     if form_data:
137         form_data.update({'email': email})
138     register_form = PasswordForm(form_data or None)
139     if User.objects.filter(email=email).exists():
140         login_form = LoginForm(initial={'login': email})
141     else:
142         login_form = None
143     if register_form.is_valid():
144         register_form.save(request)
145         password = form_data.get('password1')
146         auth_user = auth.authenticate(email=email, password=password)
147         if auth_user is not None:
148             auth.login(request, auth_user)
149         attach_order_to_user(order, auth_user)
150         return redirect('order:details', token=token)
151     ctx = {'form': register_form, 'email': email, 'order': order,
152            'login_form': login_form}
153     return TemplateResponse(request, 'order/create_password.html', ctx)
154 
155 
156 @login_required
157 def connect_order_with_user(request, token):
158     order = get_object_or_404(
159         Order.objects.filter(user_email=request.user.email, token=token))
160     attach_order_to_user(order, request.user)
161     messages.success(
162         request, pgettext_lazy(
163             'storefront message',
164             'You\'ve successfully connected order with your account'))
165     return redirect('order:details', token=order.token)
166
```

Path: `saleor/registration/forms.py`
Content:
```
1 from django import forms
2 from django.contrib.auth import login, authenticate
3 from django.contrib.auth import forms as django_forms
4 from django.utils.translation import pgettext
5 
6 from saleor.userprofile.models import User
7 
8 
9 class LoginForm(django_forms.AuthenticationForm):
10     username = forms.EmailField(
11         label=pgettext('Form field', 'Email'), max_length=75)
12 
13     def __init__(self, request=None, *args, **kwargs):
14         super(LoginForm, self).__init__(request=request, *args, **kwargs)
15         if request:
16             email = request.GET.get('email')
17             if email:
18                 self.fields['username'].initial = email
19 
20 
21 class SignupForm(forms.ModelForm):
22     password = forms.CharField(
23         label=pgettext('User form field', 'Password'),
24         widget=forms.PasswordInput)
25 
26     class Meta:
27         model = User
28         fields = ('email',)
29 
30     def __init__(self, *args, **kwargs):
31         super(SignupForm, self).__init__(*args, **kwargs)
32         if self._meta.model.USERNAME_FIELD in self.fields:
33             self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update(
34                 {'autofocus': ''})
35 
36     def save(self, request=None, commit=True):
37         user = super(SignupForm, self).save(commit=False)
38         password = self.cleaned_data['password']
39         user.set_password(password)
40         if commit:
41             user.save()
42             if request:
43                 email = self.cleaned_data['email']
44                 user = authenticate(username=email, password=password)
45                 login(request, user)
46         return user
47 
48 
49 class SetPasswordForm(django_forms.SetPasswordForm):
50     def __init__(self, *args, **kwargs):
51         super(SetPasswordForm, self).__init__(*args, **kwargs)
52         del self.fields['new_password2']
53
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/saleor/order/views.py b/saleor/order/views.py
--- a/saleor/order/views.py
+++ b/saleor/order/views.py
@@ -141,12 +141,11 @@
     else:
         login_form = None
     if register_form.is_valid():
-        register_form.save(request)
-        password = form_data.get('password1')
-        auth_user = auth.authenticate(email=email, password=password)
-        if auth_user is not None:
-            auth.login(request, auth_user)
-        attach_order_to_user(order, auth_user)
+        register_form.save()
+        password = register_form.cleaned_data.get('password')
+        user = auth.authenticate(email=email, password=password)
+        auth.login(request, user)
+        attach_order_to_user(order, user)
         return redirect('order:details', token=token)
     ctx = {'form': register_form, 'email': email, 'order': order,
            'login_form': login_form}
diff --git a/saleor/registration/forms.py b/saleor/registration/forms.py
--- a/saleor/registration/forms.py
+++ b/saleor/registration/forms.py
@@ -1,5 +1,4 @@
 from django import forms
-from django.contrib.auth import login, authenticate
 from django.contrib.auth import forms as django_forms
 from django.utils.translation import pgettext
 
@@ -39,10 +38,6 @@
         user.set_password(password)
         if commit:
             user.save()
-            if request:
-                email = self.cleaned_data['email']
-                user = authenticate(username=email, password=password)
-                login(request, user)
         return user
 
 
diff --git a/saleor/registration/views.py b/saleor/registration/views.py
--- a/saleor/registration/views.py
+++ b/saleor/registration/views.py
@@ -27,7 +27,12 @@
 def signup(request):
     form = SignupForm(request.POST or None)
     if form.is_valid():
-        form.save(request=request)
+        form.save()
+        password = form.cleaned_data.get('password')
+        email = form.cleaned_data.get('email')
+        user = auth.authenticate(email=email, password=password)
+        if user:
+            auth.login(request, user)
         messages.success(request, _('User has been created'))
         return redirect(settings.LOGIN_REDIRECT_URL)
     ctx = {'form': form}

{"golden_diff": "diff --git a/saleor/order/views.py b/saleor/order/views.py\n--- a/saleor/order/views.py\n+++ b/saleor/order/views.py\n@@ -141,12 +141,11 @@\n     else:\n         login_form = None\n     if register_form.is_valid():\n-        register_form.save(request)\n-        password = form_data.get('password1')\n-        auth_user = auth.authenticate(email=email, password=password)\n-        if auth_user is not None:\n-            auth.login(request, auth_user)\n-        attach_order_to_user(order, auth_user)\n+        register_form.save()\n+        password = register_form.cleaned_data.get('password')\n+        user = auth.authenticate(email=email, password=password)\n+        auth.login(request, user)\n+        attach_order_to_user(order, user)\n         return redirect('order:details', token=token)\n     ctx = {'form': register_form, 'email': email, 'order': order,\n            'login_form': login_form}\ndiff --git a/saleor/registration/forms.py b/saleor/registration/forms.py\n--- a/saleor/registration/forms.py\n+++ b/saleor/registration/forms.py\n@@ -1,5 +1,4 @@\n from django import forms\n-from django.contrib.auth import login, authenticate\n from django.contrib.auth import forms as django_forms\n from django.utils.translation import pgettext\n \n@@ -39,10 +38,6 @@\n         user.set_password(password)\n         if commit:\n             user.save()\n-            if request:\n-                email = self.cleaned_data['email']\n-                user = authenticate(username=email, password=password)\n-                login(request, user)\n         return user\n \n \ndiff --git a/saleor/registration/views.py b/saleor/registration/views.py\n--- a/saleor/registration/views.py\n+++ b/saleor/registration/views.py\n@@ -27,7 +27,12 @@\n def signup(request):\n     form = SignupForm(request.POST or None)\n     if form.is_valid():\n-        form.save(request=request)\n+        form.save()\n+        password = form.cleaned_data.get('password')\n+        email = form.cleaned_data.get('email')\n+        user = auth.authenticate(email=email, password=password)\n+        if user:\n+            auth.login(request, user)\n         messages.success(request, _('User has been created'))\n         return redirect(settings.LOGIN_REDIRECT_URL)\n     ctx = {'form': form}\n", "issue": "Exception Type: AttributeError when trying to create a password after succeful payment \nGot this exception:\r\n`Exception Type: AttributeError at /order/5d555f01-0f99-4821-b52f-98fa48efce4b/create-password/\r\nException Value: 'NoneType' object has no attribute 'addresses'`\r\n\r\n\n", "before_files": [{"content": "from django.conf import settings\nfrom django.contrib import messages, auth\nfrom django.contrib.auth import views as django_views\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import redirect\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.template.response import TemplateResponse\n\nfrom saleor.cart.utils import find_and_assign_anonymous_cart\nfrom .forms import LoginForm, SignupForm, SetPasswordForm\n\n\n@find_and_assign_anonymous_cart()\ndef login(request):\n    kwargs = {\n        'template_name': 'account/login.html', 'authentication_form': LoginForm}\n    return django_views.login(request, **kwargs)\n\n\n@login_required\ndef logout(request):\n    auth.logout(request)\n    messages.success(request, _('You have been successfully logged out.'))\n    return redirect(settings.LOGIN_REDIRECT_URL)\n\n\ndef signup(request):\n    form = SignupForm(request.POST or None)\n    if form.is_valid():\n        form.save(request=request)\n        messages.success(request, _('User has been created'))\n        return redirect(settings.LOGIN_REDIRECT_URL)\n    ctx = {'form': form}\n    return TemplateResponse(request, 'account/signup.html', ctx)\n\n\ndef password_reset(request):\n    template_name = 'account/password_reset.html'\n    post_reset_redirect = 'account_reset_password_done'\n    email_template_name = 'account/email/password_reset_message.txt'\n    subject_template_name = 'account/email/password_reset_subject.txt'\n    return django_views.password_reset(\n        request, template_name=template_name,\n        post_reset_redirect=post_reset_redirect,\n        email_template_name=email_template_name,\n        subject_template_name=subject_template_name)\n\n\ndef password_reset_confirm(request, uidb64=None, token=None):\n    template_name = 'account/password_reset_from_key.html'\n    post_reset_redirect = 'account_reset_password_complete'\n    set_password_form = SetPasswordForm\n    return django_views.password_reset_confirm(\n        request, uidb64=uidb64, token=token, template_name=template_name,\n        post_reset_redirect=post_reset_redirect,\n        set_password_form=set_password_form)\n", "path": "saleor/registration/views.py"}, {"content": "import logging\n\nfrom django.conf import settings\nfrom django.contrib import messages, auth\nfrom django.contrib.auth.decorators import login_required\nfrom django.db import transaction\nfrom django.http import Http404, HttpResponseForbidden\nfrom django.shortcuts import get_object_or_404, redirect\nfrom django.template.response import TemplateResponse\nfrom django.utils.translation import pgettext_lazy\nfrom payments import PaymentStatus, RedirectNeeded\n\nfrom .forms import PaymentDeleteForm, PaymentMethodsForm, PasswordForm\nfrom .models import Order, Payment\nfrom .utils import check_order_status, attach_order_to_user\nfrom ..core.utils import get_client_ip\nfrom ..registration.forms import LoginForm\nfrom ..userprofile.models import User\nfrom . import OrderStatus\n\nlogger = logging.getLogger(__name__)\n\n\ndef details(request, token):\n    orders = Order.objects.prefetch_related('groups__items',\n                                            'groups__items__product')\n    orders = orders.select_related('billing_address', 'shipping_address',\n                                   'user')\n    order = get_object_or_404(orders, token=token)\n    groups = order.groups.all()\n    return TemplateResponse(request, 'order/details.html',\n                            {'order': order, 'groups': groups})\n\n\ndef payment(request, token):\n    orders = Order.objects.prefetch_related('groups__items__product')\n    orders = orders.select_related('billing_address', 'shipping_address',\n                                   'user')\n    order = get_object_or_404(orders, token=token)\n    groups = order.groups.all()\n    payments = order.payments.all()\n    form_data = request.POST or None\n    try:\n        waiting_payment = order.payments.get(status=PaymentStatus.WAITING)\n    except Payment.DoesNotExist:\n        waiting_payment = None\n        waiting_payment_form = None\n    else:\n        form_data = None\n        waiting_payment_form = PaymentDeleteForm(\n            None, order=order, initial={'payment_id': waiting_payment.id})\n    if order.is_fully_paid():\n        form_data = None\n    payment_form = None\n    if not order.is_pre_authorized():\n        payment_form = PaymentMethodsForm(form_data)\n        # FIXME: redirect if there is only one payment method\n        if payment_form.is_valid():\n            payment_method = payment_form.cleaned_data['method']\n            return redirect('order:payment', token=order.token,\n                            variant=payment_method)\n    return TemplateResponse(request, 'order/payment.html',\n                            {'order': order, 'groups': groups,\n                             'payment_form': payment_form,\n                             'waiting_payment': waiting_payment,\n                             'waiting_payment_form': waiting_payment_form,\n                             'payments': payments})\n\n\n@check_order_status\ndef start_payment(request, order, variant):\n    waiting_payments = order.payments.filter(status=PaymentStatus.WAITING).exists()\n    if waiting_payments:\n        return redirect('order:payment', token=order.token)\n    billing = order.billing_address\n    total = order.get_total()\n    defaults = {'total': total.gross,\n                'tax': total.tax, 'currency': total.currency,\n                'delivery': order.get_delivery_total().gross,\n                'billing_first_name': billing.first_name,\n                'billing_last_name': billing.last_name,\n                'billing_address_1': billing.street_address_1,\n                'billing_address_2': billing.street_address_2,\n                'billing_city': billing.city,\n                'billing_postcode': billing.postal_code,\n                'billing_country_code': billing.country.code,\n                'billing_email': order.user_email,\n                'description': pgettext_lazy(\n                    'Payment description', 'Order %(order_number)s') % {\n                        'order_number': order},\n                'billing_country_area': billing.country_area,\n                'customer_ip_address': get_client_ip(request)}\n    variant_choices = settings.CHECKOUT_PAYMENT_CHOICES\n    if variant not in [code for code, dummy_name in variant_choices]:\n        raise Http404('%r is not a valid payment variant' % (variant,))\n    with transaction.atomic():\n        order.change_status(OrderStatus.PAYMENT_PENDING)\n        payment, dummy_created = Payment.objects.get_or_create(\n            variant=variant, status=PaymentStatus.WAITING, order=order,\n            defaults=defaults)\n        try:\n            form = payment.get_form(data=request.POST or None)\n        except RedirectNeeded as redirect_to:\n            return redirect(str(redirect_to))\n        except Exception:\n            logger.exception('Error communicating with the payment gateway')\n            messages.error(\n                request,\n                pgettext_lazy(\n                    'Payment gateway error',\n                    'Oops, it looks like we were unable to contact the selected'\n                    ' payment service'))\n            payment.change_status(PaymentStatus.ERROR)\n            return redirect('order:payment', token=order.token)\n    template = 'order/payment/%s.html' % variant\n    return TemplateResponse(request, [template, 'order/payment/default.html'],\n                            {'form': form, 'payment': payment})\n\n\n@check_order_status\ndef cancel_payment(request, order):\n    form = PaymentDeleteForm(request.POST or None, order=order)\n    if form.is_valid():\n        with transaction.atomic():\n            form.save()\n        return redirect('order:payment', token=order.token)\n    return HttpResponseForbidden()\n\n\ndef create_password(request, token):\n    if request.user.is_authenticated():\n        return redirect('order:details', token=token)\n    order = get_object_or_404(Order, token=token)\n    email = order.user_email\n    form_data = request.POST.copy()\n    if form_data:\n        form_data.update({'email': email})\n    register_form = PasswordForm(form_data or None)\n    if User.objects.filter(email=email).exists():\n        login_form = LoginForm(initial={'login': email})\n    else:\n        login_form = None\n    if register_form.is_valid():\n        register_form.save(request)\n        password = form_data.get('password1')\n        auth_user = auth.authenticate(email=email, password=password)\n        if auth_user is not None:\n            auth.login(request, auth_user)\n        attach_order_to_user(order, auth_user)\n        return redirect('order:details', token=token)\n    ctx = {'form': register_form, 'email': email, 'order': order,\n           'login_form': login_form}\n    return TemplateResponse(request, 'order/create_password.html', ctx)\n\n\n@login_required\ndef connect_order_with_user(request, token):\n    order = get_object_or_404(\n        Order.objects.filter(user_email=request.user.email, token=token))\n    attach_order_to_user(order, request.user)\n    messages.success(\n        request, pgettext_lazy(\n            'storefront message',\n            'You\\'ve successfully connected order with your account'))\n    return redirect('order:details', token=order.token)\n", "path": "saleor/order/views.py"}, {"content": "from django import forms\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth import forms as django_forms\nfrom django.utils.translation import pgettext\n\nfrom saleor.userprofile.models import User\n\n\nclass LoginForm(django_forms.AuthenticationForm):\n    username = forms.EmailField(\n        label=pgettext('Form field', 'Email'), max_length=75)\n\n    def __init__(self, request=None, *args, **kwargs):\n        super(LoginForm, self).__init__(request=request, *args, **kwargs)\n        if request:\n            email = request.GET.get('email')\n            if email:\n                self.fields['username'].initial = email\n\n\nclass SignupForm(forms.ModelForm):\n    password = forms.CharField(\n        label=pgettext('User form field', 'Password'),\n        widget=forms.PasswordInput)\n\n    class Meta:\n        model = User\n        fields = ('email',)\n\n    def __init__(self, *args, **kwargs):\n        super(SignupForm, self).__init__(*args, **kwargs)\n        if self._meta.model.USERNAME_FIELD in self.fields:\n            self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update(\n                {'autofocus': ''})\n\n    def save(self, request=None, commit=True):\n        user = super(SignupForm, self).save(commit=False)\n        password = self.cleaned_data['password']\n        user.set_password(password)\n        if commit:\n            user.save()\n            if request:\n                email = self.cleaned_data['email']\n                user = authenticate(username=email, password=password)\n                login(request, user)\n        return user\n\n\nclass SetPasswordForm(django_forms.SetPasswordForm):\n    def __init__(self, *args, **kwargs):\n        super(SetPasswordForm, self).__init__(*args, **kwargs)\n        del self.fields['new_password2']\n", "path": "saleor/registration/forms.py"}], "after_files": [{"content": "from django.conf import settings\nfrom django.contrib import messages, auth\nfrom django.contrib.auth import views as django_views\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import redirect\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.template.response import TemplateResponse\n\nfrom saleor.cart.utils import find_and_assign_anonymous_cart\nfrom .forms import LoginForm, SignupForm, SetPasswordForm\n\n\n@find_and_assign_anonymous_cart()\ndef login(request):\n    kwargs = {\n        'template_name': 'account/login.html', 'authentication_form': LoginForm}\n    return django_views.login(request, **kwargs)\n\n\n@login_required\ndef logout(request):\n    auth.logout(request)\n    messages.success(request, _('You have been successfully logged out.'))\n    return redirect(settings.LOGIN_REDIRECT_URL)\n\n\ndef signup(request):\n    form = SignupForm(request.POST or None)\n    if form.is_valid():\n        form.save()\n        password = form.cleaned_data.get('password')\n        email = form.cleaned_data.get('email')\n        user = auth.authenticate(email=email, password=password)\n        if user:\n            auth.login(request, user)\n        messages.success(request, _('User has been created'))\n        return redirect(settings.LOGIN_REDIRECT_URL)\n    ctx = {'form': form}\n    return TemplateResponse(request, 'account/signup.html', ctx)\n\n\ndef password_reset(request):\n    template_name = 'account/password_reset.html'\n    post_reset_redirect = 'account_reset_password_done'\n    email_template_name = 'account/email/password_reset_message.txt'\n    subject_template_name = 'account/email/password_reset_subject.txt'\n    return django_views.password_reset(\n        request, template_name=template_name,\n        post_reset_redirect=post_reset_redirect,\n        email_template_name=email_template_name,\n        subject_template_name=subject_template_name)\n\n\ndef password_reset_confirm(request, uidb64=None, token=None):\n    template_name = 'account/password_reset_from_key.html'\n    post_reset_redirect = 'account_reset_password_complete'\n    set_password_form = SetPasswordForm\n    return django_views.password_reset_confirm(\n        request, uidb64=uidb64, token=token, template_name=template_name,\n        post_reset_redirect=post_reset_redirect,\n        set_password_form=set_password_form)\n", "path": "saleor/registration/views.py"}, {"content": "import logging\n\nfrom django.conf import settings\nfrom django.contrib import messages, auth\nfrom django.contrib.auth.decorators import login_required\nfrom django.db import transaction\nfrom django.http import Http404, HttpResponseForbidden\nfrom django.shortcuts import get_object_or_404, redirect\nfrom django.template.response import TemplateResponse\nfrom django.utils.translation import pgettext_lazy\nfrom payments import PaymentStatus, RedirectNeeded\n\nfrom .forms import PaymentDeleteForm, PaymentMethodsForm, PasswordForm\nfrom .models import Order, Payment\nfrom .utils import check_order_status, attach_order_to_user\nfrom ..core.utils import get_client_ip\nfrom ..registration.forms import LoginForm\nfrom ..userprofile.models import User\nfrom . import OrderStatus\n\nlogger = logging.getLogger(__name__)\n\n\ndef details(request, token):\n    orders = Order.objects.prefetch_related('groups__items',\n                                            'groups__items__product')\n    orders = orders.select_related('billing_address', 'shipping_address',\n                                   'user')\n    order = get_object_or_404(orders, token=token)\n    groups = order.groups.all()\n    return TemplateResponse(request, 'order/details.html',\n                            {'order': order, 'groups': groups})\n\n\ndef payment(request, token):\n    orders = Order.objects.prefetch_related('groups__items__product')\n    orders = orders.select_related('billing_address', 'shipping_address',\n                                   'user')\n    order = get_object_or_404(orders, token=token)\n    groups = order.groups.all()\n    payments = order.payments.all()\n    form_data = request.POST or None\n    try:\n        waiting_payment = order.payments.get(status=PaymentStatus.WAITING)\n    except Payment.DoesNotExist:\n        waiting_payment = None\n        waiting_payment_form = None\n    else:\n        form_data = None\n        waiting_payment_form = PaymentDeleteForm(\n            None, order=order, initial={'payment_id': waiting_payment.id})\n    if order.is_fully_paid():\n        form_data = None\n    payment_form = None\n    if not order.is_pre_authorized():\n        payment_form = PaymentMethodsForm(form_data)\n        # FIXME: redirect if there is only one payment method\n        if payment_form.is_valid():\n            payment_method = payment_form.cleaned_data['method']\n            return redirect('order:payment', token=order.token,\n                            variant=payment_method)\n    return TemplateResponse(request, 'order/payment.html',\n                            {'order': order, 'groups': groups,\n                             'payment_form': payment_form,\n                             'waiting_payment': waiting_payment,\n                             'waiting_payment_form': waiting_payment_form,\n                             'payments': payments})\n\n\n@check_order_status\ndef start_payment(request, order, variant):\n    waiting_payments = order.payments.filter(status=PaymentStatus.WAITING).exists()\n    if waiting_payments:\n        return redirect('order:payment', token=order.token)\n    billing = order.billing_address\n    total = order.get_total()\n    defaults = {'total': total.gross,\n                'tax': total.tax, 'currency': total.currency,\n                'delivery': order.get_delivery_total().gross,\n                'billing_first_name': billing.first_name,\n                'billing_last_name': billing.last_name,\n                'billing_address_1': billing.street_address_1,\n                'billing_address_2': billing.street_address_2,\n                'billing_city': billing.city,\n                'billing_postcode': billing.postal_code,\n                'billing_country_code': billing.country.code,\n                'billing_email': order.user_email,\n                'description': pgettext_lazy(\n                    'Payment description', 'Order %(order_number)s') % {\n                        'order_number': order},\n                'billing_country_area': billing.country_area,\n                'customer_ip_address': get_client_ip(request)}\n    variant_choices = settings.CHECKOUT_PAYMENT_CHOICES\n    if variant not in [code for code, dummy_name in variant_choices]:\n        raise Http404('%r is not a valid payment variant' % (variant,))\n    with transaction.atomic():\n        order.change_status(OrderStatus.PAYMENT_PENDING)\n        payment, dummy_created = Payment.objects.get_or_create(\n            variant=variant, status=PaymentStatus.WAITING, order=order,\n            defaults=defaults)\n        try:\n            form = payment.get_form(data=request.POST or None)\n        except RedirectNeeded as redirect_to:\n            return redirect(str(redirect_to))\n        except Exception:\n            logger.exception('Error communicating with the payment gateway')\n            messages.error(\n                request,\n                pgettext_lazy(\n                    'Payment gateway error',\n                    'Oops, it looks like we were unable to contact the selected'\n                    ' payment service'))\n            payment.change_status(PaymentStatus.ERROR)\n            return redirect('order:payment', token=order.token)\n    template = 'order/payment/%s.html' % variant\n    return TemplateResponse(request, [template, 'order/payment/default.html'],\n                            {'form': form, 'payment': payment})\n\n\n@check_order_status\ndef cancel_payment(request, order):\n    form = PaymentDeleteForm(request.POST or None, order=order)\n    if form.is_valid():\n        with transaction.atomic():\n            form.save()\n        return redirect('order:payment', token=order.token)\n    return HttpResponseForbidden()\n\n\ndef create_password(request, token):\n    if request.user.is_authenticated():\n        return redirect('order:details', token=token)\n    order = get_object_or_404(Order, token=token)\n    email = order.user_email\n    form_data = request.POST.copy()\n    if form_data:\n        form_data.update({'email': email})\n    register_form = PasswordForm(form_data or None)\n    if User.objects.filter(email=email).exists():\n        login_form = LoginForm(initial={'login': email})\n    else:\n        login_form = None\n    if register_form.is_valid():\n        register_form.save()\n        password = register_form.cleaned_data.get('password')\n        user = auth.authenticate(email=email, password=password)\n        auth.login(request, user)\n        attach_order_to_user(order, user)\n        return redirect('order:details', token=token)\n    ctx = {'form': register_form, 'email': email, 'order': order,\n           'login_form': login_form}\n    return TemplateResponse(request, 'order/create_password.html', ctx)\n\n\n@login_required\ndef connect_order_with_user(request, token):\n    order = get_object_or_404(\n        Order.objects.filter(user_email=request.user.email, token=token))\n    attach_order_to_user(order, request.user)\n    messages.success(\n        request, pgettext_lazy(\n            'storefront message',\n            'You\\'ve successfully connected order with your account'))\n    return redirect('order:details', token=order.token)\n", "path": "saleor/order/views.py"}, {"content": "from django import forms\nfrom django.contrib.auth import forms as django_forms\nfrom django.utils.translation import pgettext\n\nfrom saleor.userprofile.models import User\n\n\nclass LoginForm(django_forms.AuthenticationForm):\n    username = forms.EmailField(\n        label=pgettext('Form field', 'Email'), max_length=75)\n\n    def __init__(self, request=None, *args, **kwargs):\n        super(LoginForm, self).__init__(request=request, *args, **kwargs)\n        if request:\n            email = request.GET.get('email')\n            if email:\n                self.fields['username'].initial = email\n\n\nclass SignupForm(forms.ModelForm):\n    password = forms.CharField(\n        label=pgettext('User form field', 'Password'),\n        widget=forms.PasswordInput)\n\n    class Meta:\n        model = User\n        fields = ('email',)\n\n    def __init__(self, *args, **kwargs):\n        super(SignupForm, self).__init__(*args, **kwargs)\n        if self._meta.model.USERNAME_FIELD in self.fields:\n            self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update(\n                {'autofocus': ''})\n\n    def save(self, request=None, commit=True):\n        user = super(SignupForm, self).save(commit=False)\n        password = self.cleaned_data['password']\n        user.set_password(password)\n        if commit:\n            user.save()\n        return user\n\n\nclass SetPasswordForm(django_forms.SetPasswordForm):\n    def __init__(self, *args, **kwargs):\n        super(SetPasswordForm, self).__init__(*args, **kwargs)\n        del self.fields['new_password2']\n", "path": "saleor/registration/forms.py"}]}