Esempio n. 1
0
def checkout_success(request, order_number):
    save_info = request.session.get('save_info')
    order = get_object_or_404(Order, order_number=order_number)

    if request.user.is_authenticated:
        profile = UserProfile.objects.get(user=request.user)
        # connect  profile to the order
        order.user = profile
        order.save()

        # Save the user's info
        if save_info:
            profile_data = {
                'default_phone_number': order.phone_number,
                'default_country': order.country,
                'default_postcode': order.postcode,
                'default_town_or_city': order.town_or_city,
                'default_street_address1': order.street_address1,
                'default_street_address2': order.street_address2,
                'default_county': order.county,
            }
            user_form = UserForm(profile_data, instance=profile)
            if user_form.is_valid():
                user_form.save()

    if 'cart' in request.session:
        del request.session['cart']

    template = 'checkout/checkout_success.html'
    context = {
        'order': order,
    }

    return render(request, template, context)
def edit_user(request):
    user = request.user
    rater = user.rater
    profile = user.profile
    if request.method == "POST":
        if "user_edit" in request.POST:
            user_form = UserForm(request.POST)
            if user_form.is_valid():
                user_form.save(commit=False)
                password = user_form.password
                user.set_password(password)
                user.save()
                messages.add_message(request, messages.SUCCESS, "You have updated your account")
        elif "rater_edit" in request.POST:
            rater_form = RaterForm(request.POST)
            if rater_form.is_valid():
                rater_form.save()
                messages.add_message(request, messages.SUCCESS, "You have updated your demographic info")
        elif "profile_edit" in request.POST:
            profile_form = ProfileForm(request.POST)
            if profile_form.is_valid():
                profile_form.save()
                messages.add_message(request, messages.SUCCESS, "You have updated your profile")

    user_form = UserForm(request.POST or None, instance=request.user)
    rater_form = RaterForm(request.POST or None, instance=request.user.rater)
    profile_form = ProfileForm(request.POST or None, instance=request.user.profile)
    return render(request, "user_edit.html", {'user_form': user_form,
                                        'rater_form': rater_form, 'profile_form':profile_form})
Esempio n. 3
0
def user_update(request):
    """ User profile settings form """

    user = request.user
    profile = request.user.get_profile()
    
    if request.method == "POST":
        user_form = UserForm(request.POST, instance=user, prefix="UserForm")
        profile_form = UserProfileForm(request.POST, request.FILES, instance=profile, prefix="UserProfileForm")
        
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            
            request.user.message_set.create(message=_("Your profile settings have been updated."))
            
            return HttpResponseRedirect(profile.get_absolute_url())
    
    else:
        user_form = UserForm(instance=user, prefix="UserForm")
        profile_form = UserProfileForm(instance=profile, prefix="UserProfileForm")

    return render_to_response("profiles/user_update.html", {
        "user_form" : user_form,
        "profile_form" : profile_form
    }, context_instance=RequestContext(request))
def view_dashboard(request):
    user = request.user
    rater = user.rater
    if request.method == "GET":
        pass
    elif request.method == "POST":
        if "user_edit" in request.POST:
            user_form = UserForm(request.POST)
            if user_form.is_valid():
                user.username = requet.POST.get('username')
                user.email = requet.POST.get('email')
                user.save()
                messages.add_message(request, messages.SUCCESS, "You have updated your account")
        elif "rater_edit" in request.POST:
            rater_form = RaterForm(request.POST)
            if rater_form.is_valid():
                rater.age = request.POST.get('age')
                rater.gender = request.POST.get('gender')
                rater.occupation = request.POST.get('occupation')
                rater.zip_code = request.POST.get('zip_code')
                rater.save()
                messages.add_message(request, messages.SUCCESS, "You have updated your profile")
        elif "delete_button" in request.POST:
            idx = int(request.POST.get('rating'))
            rating = Rating.objects.get(pk=idx)
            sometext = "Sucessfully deleted rating of {}".format(rating.movie.title)
            Rating.objects.get(pk=idx).delete()
            messages.add_message(request, messages.SUCCESS, sometext)

    user_form = UserForm(initial={'username':user.username, 'email':user.email})
    rater_form = RaterForm(initial = {'age':rater.age, 'gender':rater.gender,
                        'occupation':rater.occupation, 'zip_code':rater.zip_code})
    return render(request, "movies/dashboard.html", {'user_form': user_form,
                                        'rater_form': rater_form})
Esempio n. 5
0
 def test_update_account_form(self):
     login = self.client.login(username="******",
                               password="******")
     user = self.test_user
     response = self.client.post(reverse("update_account_details"))
     form_data = {"username": "******"}
     form = UserForm(data=form_data)
     self.assertTrue(form.is_valid())
Esempio n. 6
0
 def test_email_validation_raises_error_on_update(self, admin_user):
     """
     Test taht error will be raised if passed email belong to another user.
     """
     form = UserForm(instance=admin_user)
     user = User.objects.create_user('somesome', '*****@*****.**')
     form.cleaned_data = {'email': user.email}
     with pytest.raises(ValidationError):
         form.clean_email()
Esempio n. 7
0
def register(request):

    # A boolean value for telling the template whether the registration was successful.
    # Set to False initially. Code changes value to True when registration succeeds.
    registered = False

    # If it's a HTTP POST, we're interested in processing form data.
    if request.method == 'POST':
        # Attempt to grab information from the raw form information.
        # Note that we make use of both UserForm and UserProfileForm.
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)

        # If the two forms are valid...
        if user_form.is_valid() and profile_form.is_valid():
            # Save the user's form data to the database.
            user = user_form.save()

            # Now we hash the password with the set_password method.
            # Once hashed, we can update the user object.
            user.set_password(user.password)
            user.save()

            # Now sort out the UserProfile instance.
            # Since we need to set the user attribute ourselves, we set commit=False.
            # This delays saving the model until we're ready to avoid integrity problems.
            profile = profile_form.save(commit=False)
            profile.user = user

            # Did the user provide a profile picture?
            # If so, we need to get it from the input form and put it in the UserProfile model.
            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']

            # Now we save the UserProfile model instance.
            profile.save()

            # Update our variable to tell the template registration was successful.
            registered = True

        # Invalid form or forms - mistakes or something else?
        # Print problems to the terminal.
        # They'll also be shown to the user.
        else:
            print user_form.errors, profile_form.errors

    # Not a HTTP POST, so we render our form using two ModelForm instances.
    # These forms will be blank, ready for user input.
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    # Render the template depending on the context.
    return render(request,
            'register.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )
Esempio n. 8
0
def user_create(request):
    form = UserForm()
    if request.method == "POST":
        form = UserForm(request.POST)
        if form.is_valid():
            form.save()
            user = authenticate(username=request.POST['username'], password=request.POST['password'])
            login(request,user)
            return HttpResponseRedirect(user.get_absolute_url())
    return render_to_response("profiles/user_create.html",{"form":form},context_instance=RequestContext(request))
Esempio n. 9
0
File: views.py Progetto: cmm863/Blix
def create_user(request):
    if request.POST:
        formf = UserForm(request.POST)

        formf.save()
        return HttpResponseRedirect('/')
    else:
        form = UserForm()

    args = {}
    args.update(csrf(request))
    args['form'] = form
    return render_to_response('create_user.html', args)
Esempio n. 10
0
def checkout_success(request, order_number):
    """
    This view displays details of a users order.
    The view also updates the user profile if the
    save-info box has been ticked.
    The session basket is also cleared.
    The "checkout success" boolean is used to
    identify the order progress.
    """
    save_info = request.session.get('save_info')
    order = get_object_or_404(Order, order_number=order_number)

    if request.user.is_authenticated:
        profile = UserProfile.objects.get(user=request.user)
        order.user_profile = profile
        order.save()
        if save_info:
            delivery_data = {
                'default_phone_number': order.phone_number,
                'default_address_1': order.address_1,
                'default_address_2': order.address_2,
                'default_city': order.city,
                'default_county': order.county,
                'default_country': order.country,
                'default_postcode': order.postcode,
            }
            user_data = {
                'first_name': order.full_name.split()[0],
                'last_name': order.full_name.split()[-1],
                'email': order.email,
            }
            user_profile_form = UserProfileForm(delivery_data,
                                                instance=profile)
            if user_profile_form.is_valid():
                user_profile_form.save()

            user_form = UserForm(user_data, instance=request.user)
            if user_form.is_valid():
                user_form.save()

    if 'basket' in request.session:
        del request.session['basket']

    context = {
        'order': order,
        'checkout_success': True,
    }

    return render(request, 'checkout/checkout_success.html', context)
Esempio n. 11
0
def profile_edit(request):
    """
    Edit profile page
    """
    if request.method == "POST":
        user_form = UserForm(request.POST, instance=request.user)

        if user_form.is_valid():
            user_form.save()

            return HttpResponseRedirect(reverse("profiles_profile_landing"))
    else:
        user_form = UserForm(instance=request.user)

    return render_to_response(
        "profiles/profile_form.html", {"user_form": user_form}, context_instance=RequestContext(request)
    )
Esempio n. 12
0
def register(request):
    '''
    TO DO:
    Authenticate email
    '''
    if request.method == 'POST':
        formUser = UserForm(data=request.POST)
        formProfile=ProfileForm(data=request.POST)
        if formUser.is_valid() and formProfile.is_valid():
            password1=formUser.cleaned_data['password']
            password2=request.POST.get('password2')
            first_name=formUser.cleaned_data['first_name']
            last_name=formUser.cleaned_data['last_name']
            email=formUser.cleaned_data['email']
            if(password1!=password2):
                return render(request, 'register.html', {'formUser': formUser, 'formProfile':formProfile,'passwordError':'passwordError'})
            if User.objects.filter(username = email).exists():
                return render(request, 'register.html', {'formUser': formUser, 'formProfile':formProfile, 'error_message':'error_message'})
            user = formUser.save()
            user.set_password(user.password)
            user.is_active = False
            user.first_name=first_name
            user.last_name=last_name
            user.email=email
            user.username=email
    
            body=formProfile.cleaned_data['body']
            birthDate=formProfile.cleaned_data['birthDate']
            gender=formProfile.cleaned_data['gender']
            city=formProfile.cleaned_data['city']
            country=formProfile.cleaned_data['country']
            address=formProfile.cleaned_data['address']
            postalCode=formProfile.cleaned_data['postalCode']
            phoneNumber=formProfile.cleaned_data['phoneNumber']
            try:
                image = request.FILES['image']
            except:
                image=""
            user.save()
            newProfile=Profile(user=user,body=body,birthDate=birthDate,gender=gender,city=city,address=address,postalCode=postalCode,phoneNumber=phoneNumber,country=country,image=image)
            newProfile.save()
            return HttpResponseRedirect('/profiles/login')
    else:
        formUser = UserForm()
        formProfile=ProfileForm()
    return render(request, 'register.html', {'formUser': formUser, 'formProfile':formProfile})
Esempio n. 13
0
def add_info(request):
    # функция, выводящая форму для ввода информации о пользователе
    # или перенаправляющая на страницу профиля при повторной авторизации пользователя
    if request.method == 'POST':
        profile_form = UserProfileForm(request.POST,
                                       request.FILES,
                                       instance=request.user.profile)
        user_form = UserForm(request.POST,
                             request.FILES,
                             instance=request.user)
        if profile_form.is_valid() and user_form.is_valid():
            profile_form.save()
            user_form.save()
            if info_is_completed(request.user):
                messages.success(request, 'Успешное изменение профиля!')
                return redirect('/my_profile/')
            else:
                messages.error(request, 'Необходимо ввести все поля формы')
        else:
            messages.error(
                request, 'Необходимо ввести корректные значения в поля формы!')
    elif info_is_completed(request.user):
        return redirect('/my_profile/')
    else:
        profile_form = UserProfileForm(instance=request.user.profile)
        user_form = UserForm(instance=request.user)
    heading = "Пожалуйста, введите все свои данные в форму ниже:"
    return render(request, 'data_input.html', {
        'profile_form': profile_form,
        'user_form': user_form,
        'heading': heading
    })
Esempio n. 14
0
def edit_profile(request):
    # метод для изменения информации о пользователе
    # используются две формы, которые отправляются на сервер одной кнопкой
    if request.method == 'POST':
        profile_form = UserProfileForm(request.POST,
                                       request.FILES,
                                       instance=request.user.profile)
        user_form = UserForm(request.POST,
                             request.FILES,
                             instance=request.user)
        if profile_form.is_valid() and user_form.is_valid():
            profile_form.save()
            user_form.save()
            if info_is_completed(request.user):
                messages.success(request, 'Успешное изменение профиля!')
                return redirect('/my_profile/')
            else:
                messages.error(request, 'Необходимо ввести все поля формы')
        else:
            messages.error(
                request, 'Необходимо ввести корректные значения в поля формы!')
    else:
        profile_form = UserProfileForm(instance=request.user.profile)
        user_form = UserForm(instance=request.user)
    heading = "Здесь Вы можете изменить личную информацию профиля:"
    return render(request, 'data_input.html', {
        'profile_form': profile_form,
        'user_form': user_form,
        'heading': heading
    })
def checkout_success(request, order_number):
    """
    Handle successful checkouts
    """
    order = get_object_or_404(Order, order_number=order_number)
    order_id = order.id
    line_items = OrderLineItem.objects.filter(order=order_id)
    save_info = request.session.get('save_info')

    if request.user.is_authenticated:
        profile = UserProfile.objects.get(user=request.user)
        order.user_profile = profile
        profile.loyalty_points += order.loyalty_points
        profile.save()
        order.save()

        if save_info:
            profile_data = {
                'default_phone_number': order.phone_number,
                'default_postcode': order.postcode,
                'default_town_or_city': order.town_or_city,
                'default_street_address1': order.street_address1,
                'default_street_address2': order.street_address2,
                'default_county': order.county,
            }
            user_profile_form = UserForm(profile_data, instance=profile)
            if user_profile_form.is_valid():
                user_profile_form.save()

    if 'bag' in request.session:
        del request.session['bag']
    if 'discount' in request.session:
        del request.session['discount']
    if 'loyalty' in request.session:
        del request.session['loyalty']

    template = 'checkout/checkout_success.html'
    context = {
        'order': order,
        'line_items': line_items,
    }

    return render(request, template, context)
Esempio n. 16
0
def payment_success(request, order_number):
    """
    Successful payments
    """
    save_info = request.session.get('save_info')
    order = get_object_or_404(Payment, order_number=order_number)

    if request.user.is_authenticated:
        profile = UserProfile.objects.get(user=request.user)
        # Attach the user's profile to the order
        order.user_profile = profile
        order.save()

        # Save the user's info
        if save_info:
            profile_data = {
                'email': order.email,
                'phone_number': order.phone_number,
                'country': order.country,
                'street_address1': order.street_address1,
                'street_address2': order.street_address2,
                'town_or_city': order.town_or_city,
                'county': order.county,
                'postcode': order.postcode,
            }
            user_form = UserForm(profile_data, instance=profile)
            if user_form.is_valid():
                user_form.save()

    messages.success(request, f'Booking successfully processed! \
        Your order number is {order_number}. A confirmation \
        email will be sent to {order.email} and your Expert will be in touch shortly by phone or email to book in a time and date.')

    if 'bag' in request.session:
        del request.session['bag']

    template = 'payments/payment_success.html'
    context = {
        'order': order,
    }

    return render(request, template, context)
Esempio n. 17
0
def checkout_completed(request, order_number):
    """
    Handles a completed checkout, and attaches it to a user profile
    """
    save_info = request.session.get('save_info')
    order = get_object_or_404(Order, order_number=order_number)

    if request.user.is_authenticated:
        profile = UserProfile.objects.get(user=request.user)
        order.user_profile = profile
        order.save()

        # handles the save user info tick-box
        if save_info:
            profile_data = {
                'default_phone_number': order.phone_number,
                'default_country': order.country,
                'default_postcode': order.postcode,
                'default_town_or_city': order.town_or_city,
                'default_street_address1': order.street_address1,
                'default_street_address2': order.street_address2,
                'default_county': order.county,
                'default_country': order.country,
            }
            user_profile_form = UserForm(profile_data, instance=profile)
            if user_profile_form.is_valid():
                user_profile_form.save()

    messages.success(
        request, f'Order successfully processed! \
        Your order number is {order_number}. A confirmation \
        email will be sent to {order.email}.')

    if 'basket' in request.session:
        del request.session['basket']

    template = 'checkout/checkout_completed.html'
    context = {
        'order': order,
    }

    return render(request, template, context)
Esempio n. 18
0
def user_register(request):
    if request.method == "GET":
        user_form = UserForm()
        profile_form = ProfileForm()
    elif request.method == "POST":
        user_form = UserForm(request.POST)
        profile_form = ProfileForm(request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save(commit=False)  # setting password done in forms.py
            user.alias = user.username
            user.save()
            # extra password thing
            # password = user.password # The form doesn't know to call this special method on user.
            # user.set_password(password)
            # user.save() # You must call authenticate before login. :(
            # end extra password thing
            profile = profile_form.save(commit=False)
            if Location.objects.count() > 0:
                profile.location = Location.objects.all()[0]
            profile.user = user
            profile.save()
            user = authenticate(username=request.POST['username'],
                                password=request.POST['password'])
            login(request, user)
            messages.add_message(
                request, messages.SUCCESS,
                "Congratulations, {}, on creating your new account! You are now logged in.".format(
                    user.username))
            send_mail("Welcome to Share Lockers","""\
{},

Your account on sharelockers.come has been created! \
We look forward to seeing what you have to share. \
You might start by stocking some items to sell, or by adding items you have \
at home which you would be willing to sell.

-ShareLockers Team""".format(user.username),
                    settings.EMAIL_HOST_USER, [user.email], fail_silently=settings.EMAIL_SILENT)
            return redirect('view_index')
    return render(request, "profiles/register.html", {'user_form': user_form,
                                                      'profile_form': profile_form,
                                                      })
Esempio n. 19
0
def register(request, key=''):

    registered = False

    try:
        invite_record = Invitation.objects.get(key=key)
        if invite_record.activated == True:
            return HttpResponseRedirect(reverse('home'))
    except ObjectDoesNotExist:
        return HttpResponseRedirect(reverse('home'))

    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.save()

            profile = profile_form.save(commit=False)
            invite_record = Invitation.objects.get(key=key)
            profile.user = user

            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']

            profile.save()

            registered = True
            invite_record.activated = True

        else:
            print user_form.errors, profile_form.errors
    
    else:
        user_form = UserForm(instance=invite_record)
        profile_form = UserProfileForm()

    return render(request,
            'register.html',
			{'user_form': user_form, 'profile_form': profile_form, 'registered': registered})
Esempio n. 20
0
def register_user(request):
    context_dict = {}
    registered = False
    if request.method == 'POST':
        # user_form = UserForm(data=request.POST)
        user_form = UserForm(request.POST)
        if user_form.is_valid():
            user = user_form.save(commit=True)

            person = Person()
            person.username = user.username
            person.email = user.email
            person.save()

            user.set_password(user.password)
            user.save()
            registered = True
            context_dict = {'boldmessage': "User createlly correctly"}
        else:
            print user_form.errors
    else:
        user_form = UserForm()
    return render(request, 'webUser/register.html', {
        'user_form': user_form,
        'registered': registered
    })
Esempio n. 21
0
def register(request):
    registered = False
    if request.method == "POST":
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileInfoForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user

            if 'profile_pic' in request.FILES:
                profile.profile_pic = request.FILES['profile_pic']

            profile.save()
            registered = True
        else:
            print(user_form.errors, profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = UserProfileInfoForm()

    return render(
        request, 'profiles/register.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'registered': registered
        })
Esempio n. 22
0
def checkout_success(request, order_number):
    # Handle successful checkouts
    save_info = request.session.get('save-info')
    order = get_object_or_404(Order, order_number=order_number)

    if request.user.is_authenticated:
        profile = UserProfile.objects.get(user=request.user)
        order.user_profile = profile
        order.save()

        if save_info:
            profile_data = {
                'default_full_name': order.full_name,
                'default_email': order.email,
                'default_phone_number': order.phone_number,
                'default_street_address1': order.street_address1,
                'default_street_address2': order.street_address1,
                'default_town_or_city': order.town_or_city,
                'default_county':  order.county,
                'default_postcode': order.postcode,
                'default_country': order.country,
            }
            user_profile_form = UserForm(profile_data, instance=profile)
            if user_profile_form.is_valid():
                user_profile_form.save()

    messages.success(request, f'Your order has been processes! \
        Your order number is {order_number} and \
        a confirmation has been sent to {order.email}.')

    if 'cart' in request.session:
        del request.session['cart']

    template = 'checkout/checkout_success.html'
    context = {
        'order': order,
    }

    return render(request, template, context)
def view_register(request):
    if request.method == "GET":
        user_form = UserForm()
        profile_form = ProfileForm()
        rater_form = RaterForm()
    elif request.method == "POST":
        user_form = UserForm(request.POST)
        rater_form = RaterForm(request.POST)
        profile_form = ProfileForm(request.POST)
        if user_form.is_valid() and rater_form.is_valid():
            user = user_form.save()
            rater = rater_form.save(commit=False)
            rater.user = user
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.age = rater.age
            profile.gender = rater.gender
            profile.save()
            rater.save()

            password = user.password
            # The form doesn't know to call this special method on user.
            user.set_password(password)
            user.save()

            # You must call authenticate before login. :(
            user = authenticate(username=user.username,
                                password=password)
            login(request, user)
            messages.add_message(
                request,
                messages.SUCCESS,
                "Congratulations, {}, on creating your new account! You are now logged in.".format(
                    user.username))
            return redirect('/')
    return render(request, "profiles/register.html", {'user_form': user_form,
                                                   'rater_form': rater_form})
Esempio n. 24
0
def profile_edit(request, template_name='profiles/profile_form.html'):
    """Edit profile."""

    if request.POST:
        profile = Profile.objects.get(user=request.user)
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST,
                                   request.FILES,
                                   instance=profile)
        service_formset = ServiceFormSet(request.POST, instance=profile)
        link_formset = LinkFormSet(request.POST, instance=profile)

        if profile_form.is_valid() and user_form.is_valid(
        ) and service_formset.is_valid() and link_formset.is_valid():
            profile_form.save()
            user_form.save()
            link_formset.save()
            service_formset.save()
            # return HttpResponseRedirect(reverse('profile_detail', kwargs={'username': request.user.username}))
            return HttpResponseRedirect(reverse('profiles-profile-edit'))
        else:

            from lib.util.form_errors import merge_form_errors
            form_errors = merge_form_errors([
                user_form,
                profile_form,
                service_formset,
                link_formset,
            ])

            context = {
                'object': profile,
                'action_form': ActionForm(),
                'profile_form': profile_form,
                'user_form': user_form,
                'service_formset': service_formset,
                'link_formset': link_formset,
                'form_errors': form_errors,
            }

    else:
        profile = Profile.objects.get(user=request.user)
        link_formset = LinkFormSet(instance=profile)
        service_formset = ServiceFormSet(instance=profile)

        context = {
            'object': profile,
            'action_form': ActionForm(),
            'profile_form': ProfileForm(instance=profile),
            'user_form': UserForm(instance=request.user),
            'service_formset': service_formset,
            'link_formset': link_formset
        }
    return render_to_response(template_name,
                              context,
                              context_instance=RequestContext(request))
Esempio n. 25
0
def update_profile(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=request.user.profile)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, ('Ваш профиль был успешно обновлен!'))
            return redirect('profile')
        else:
            messages.error(request, ('Пожалуйста, исправьте ошибки.'))
    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)
    return render(request, 'profile.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })
Esempio n. 26
0
def user_register(request):
    if request.method == "GET":
        user_form = UserForm()
        profile_form = ProfileForm()
    elif request.method == "POST":
        user_form = UserForm(request.POST)
        profile_form = ProfileForm(request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save(
                commit=False)  # setting password done in forms.py
            user.alias = user.username
            user.save()
            # extra password thing
            # password = user.password # The form doesn't know to call this special method on user.
            # user.set_password(password)
            # user.save() # You must call authenticate before login. :(
            # end extra password thing
            profile = profile_form.save(commit=False)
            if Location.objects.count() > 0:
                profile.location = Location.objects.all()[0]
            profile.user = user
            profile.save()
            user = authenticate(username=request.POST['username'],
                                password=request.POST['password'])
            login(request, user)
            messages.add_message(
                request, messages.SUCCESS,
                "Congratulations, {}, on creating your new account! You are now logged in."
                .format(user.username))
            send_mail("Welcome to Share Lockers",
                      """\
{},

Your account on sharelockers.come has been created! \
We look forward to seeing what you have to share. \
You might start by stocking some items to sell, or by adding items you have \
at home which you would be willing to sell.

-ShareLockers Team""".format(user.username),
                      settings.EMAIL_HOST_USER, [user.email],
                      fail_silently=settings.EMAIL_SILENT)
            return redirect('view_index')
    return render(request, "profiles/register.html", {
        'user_form': user_form,
        'profile_form': profile_form,
    })
Esempio n. 27
0
def register(request):
    """
    Registration page which shows a form for the user to complete
    """
    registered = False
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        if user_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            if user_form.cleaned_data['is_developer']:
                user.developer.active = True
                add_default_service(user.developer)
            if user_form.cleaned_data['is_provider']:
                user.provider.active = True
                # When a new provider is registered,
                # a new rabbitmq user should be added to the system
                initialize_rabbitmq_user(user)
                # TODO: create hyperledger fabric user
            if USE_FABRIC:
                r = fabric.invoke_new_monetary_account(user.username, '700')
                if 'jwt expired' in r.text or 'jwt malformed' in r.text or 'User was not found' in r.text:
                    token = fabric.register_user()
                    r = fabric.invoke_new_monetary_account(user.username, '700', token = token)
            user.save()
            user = authenticate(username=user_form.cleaned_data['username'], password=user_form.cleaned_data['password'])
            login(request, user)
            messages.success(request, "Successful Login")
            registered = True
            if user_form.cleaned_data['is_provider']:
                return render(request, 'providers_app/index.html')
        else:
            print(user_form.errors)

    else:
        user_form = UserForm()
    return render(request, 'profiles/registration.html',
                           {'user_form': user_form,
                            'registered': registered})
Esempio n. 28
0
File: views.py Progetto: osya/tryTen
 def get_object(self, queryset=None):
     user = get_user_model().objects.get(
         pk=self.request.session['_auth_user_id'])
     return UserForm(instance=user)
Esempio n. 29
0
def edit_profile(request, form_class=ProfileForm, success_url=None,
                 template_name='profiles/edit_profile.html',
                 extra_context=None):
    """
    Edit the current user's profile.

    If the user does not already have a profile (as determined by
    ``User.get_profile()``), a redirect will be issued to the
    :view:`profiles.views.create_profile` view; if no profile model
    has been specified in the ``AUTH_PROFILE_MODULE`` setting,
    ``django.contrib.auth.models.SiteProfileNotAvailable`` will be
    raised.

    **Optional arguments:**

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``form_class``
        The form class to use for validating and editing the user
        profile. This form class must operate similarly to a standard
        Django ``ModelForm`` in that it must accept an instance of the
        object to be edited as the keyword argument ``instance`` to
        its constructor, and it must implement a method named
        ``save()`` which will save the updates to the object. If this
        argument is not specified, this view will use a ``ModelForm``
        generated from the model specified in the
        ``AUTH_PROFILE_MODULE`` setting.

    ``success_url``
        The URL to redirect to following a successful edit. If not
        specified, this will default to the URL of
        :view:`profiles.views.profile_detail` for the profile object
        being edited.

    ``template_name``
        The template to use when displaying the profile-editing
        form. If not specified, this will default to
        :template:`profiles/edit_profile.html`.

    **Context:**

    ``form``
        The form for editing the profile.

    ``profile``
         The user's current profile.

    **Template:**

    ``template_name`` keyword argument or
    :template:`profiles/edit_profile.html`.

    """
    try:
        profile_obj = request.user.get_profile()
    except ObjectDoesNotExist:
        return HttpResponseRedirect(reverse('profiles_create_profile'))

    #
    # See the comment in create_profile() for discussion of why
    # success_url is set up here, rather than as a default value for
    # the argument.
    #

    if success_url is None:
        success_url = reverse('profiles_profile_detail',
                              kwargs={ 'username': request.user.username })
    if form_class is None:
        form_class = utils.get_profile_form()

    if request.method == 'POST':
        profile_form = form_class(data=request.POST, files=request.FILES, instance=profile_obj)
        user_form = UserForm(data=request.POST, files=request.FILES,
                             instance=request.user)

        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            return HttpResponseRedirect(success_url)
    else:
        user_form = UserForm(instance=request.user)
        profile_form = form_class(instance=profile_obj)

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
                              { 'user_form': user_form,
                                'profile_form': profile_form,
                                'profile': profile_obj, },
                              context_instance=context)
Esempio n. 30
0
def create_profile(request, form_class=ProfileForm, success_url=None,
                   template_name='profiles/create_profile.html',
                   extra_context=None):
    """
    Create a profile for the current user, if one doesn't already
    exist.

    If the user already has a profile, as determined by
    ``request.user.get_profile()``, a redirect will be issued to the
    :view:`profiles.views.edit_profile` view. If no profile model has
    been specified in the ``AUTH_PROFILE_MODULE`` setting,
    ``django.contrib.auth.models.SiteProfileNotAvailable`` will be
    raised.

    **Optional arguments:**

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``form_class``
        The form class to use for validating and creating the user
        profile. This form class must define a method named
        ``save()``, implementing the same argument signature as the
        ``save()`` method of a standard Django ``ModelForm`` (this
        view will call ``save(commit=False)`` to obtain the profile
        object, and fill in the user before the final save). If the
        profile object includes many-to-many relations, the convention
        established by ``ModelForm`` of using a method named
        ``save_m2m()`` will be used, and so your form class should
        also define this method.

        If this argument is not supplied, this view will use a
        ``ModelForm`` automatically generated from the model specified
        by ``AUTH_PROFILE_MODULE``.

    ``success_url``
        The URL to redirect to after successful profile creation. If
        this argument is not supplied, this will default to the URL of
        :view:`profiles.views.profile_detail` for the newly-created
        profile object.

    ``template_name``
        The template to use when displaying the profile-creation
        form. If not supplied, this will default to
        :template:`profiles/create_profile.html`.

    **Context:**

    ``form``
        The profile-creation form.

    **Template:**

    ``template_name`` keyword argument, or
    :template:`profiles/create_profile.html`.

    """
    try:
        profile_obj = request.user.get_profile()
        return HttpResponseRedirect(reverse('profiles_edit_profile'))
    except ObjectDoesNotExist:
        pass

    #
    # We set up success_url here, rather than as the default value for
    # the argument. Trying to do it as the argument's default would
    # mean evaluating the call to reverse() at the time this module is
    # first imported, which introduces a circular dependency: to
    # perform the reverse lookup we need access to profiles/urls.py,
    # but profiles/urls.py in turn imports this module.
    #

    if success_url is None:
        success_url = reverse('profiles_profile_detail',
                              kwargs={ 'username': request.user.username })
    if form_class is None:
        form_class = utils.get_profile_form()

    if request.method == 'POST':
        profile_form = form_class(data=request.POST, files=request.FILES)
        user_form = UserForm(data=request.POST, files=request.FILES,
                             instance=request.user)
        if user_form.is_valid() and profile_form.is_valid():
            user_obj = user_form.save()

            profile_obj = profile_form.save(commit=False)
            profile_obj.user = request.user
            profile_obj.save()

            if hasattr(profile_form, 'save_m2m'):
                profile_form.save_m2m()
            return HttpResponseRedirect(success_url)
    else:
        user_form = UserForm(instance=request.user)
        profile_obj = UserProfile.objects.create(user=request.user)
        profile_form = form_class(instance=profile_obj)

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
                              { 'user_form': user_form,
                               'profile_form': profile_form},
                              context_instance=context)
Esempio n. 31
0
 def test_email_validation_not_raises_error(self, admin_user):
     """Test that error won't be raisedif passed email is user email."""
     form = UserForm(instance=admin_user)
     form.cleaned_data = {'email': admin_user.email}
     email = form.clean_email()
     assert email == admin_user.email
Esempio n. 32
0
 def test_email_validation_not_raises_error_if_available(self, admin_user):
     """Test that error won't be raised if passed email is available"""
     form = UserForm(instance=admin_user)
     form.cleaned_data = {'email': '*****@*****.**'}
     email = form.clean_email()
     assert email == '*****@*****.**'