Esempio n. 1
0
def register(request):

    context = RequestContext(request)
    registered = False

    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.set_password(user.password)
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()
            registered = True
        else:
            print user_form.errors, profile_form.errors
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    #Render the template depending on the context

    return render_to_response(
        'register.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'registered': registered
        }, context)
Esempio n. 2
0
def update_profile(request):
    """User can update its profile
    via Profile.html and related form"""
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = UserProfileForm(request.POST,
                                       instance=request.user.userprofile)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request,
                             ('Your profile was successfully updated!'),
                             extra_tags="Profile Updated")
            return redirect(reverse('index'))
        else:
            messages.error(request, ('Please correct the error below.'))
            return render(
                request, 'edit_profile.html', {
                    "user_form": user_form,
                    "profile_form": profile_form,
                    "background_image": background["default"]
                })
    else:
        user_form = UserForm(instance=request.user)
        profile_form = UserProfileForm(instance=request.user.userprofile)
    return render(
        request, 'profile.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            "background_image": background["default"]
        })
Esempio n. 3
0
def signup_user(request):
    if request.method == 'GET':
        context = {
            'user_form': UserForm(),
            'profile_form': UserProfileForm(),
        }

        return render(request, 'accounts/signup.html', context)
    else:
        user_form = UserForm(request.POST)
        profile_form = UserProfileForm(request.POST, request.FILES)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            profile = profile_form.save(commit=False)
            profile.user = user

            group = Group.objects.get(name='customer')
            user.groups.add(group)

            profile.save()

            login(request, user)

            return redirect('user profile')

        context = {
            'user_form': user_form,
            'profile_form': profile_form,
        }
        return render(request, 'accounts/signup.html', context)
def edit_profile(request):

    if request.method == "POST":
        form = UserProfileForm(request.POST,
                               request.FILES,
                               instance=request.user)
        if form.is_valid():
            print "FORM IS VALID"
            user = request.user
            if request.POST.get('first_name', False):
                user.first_name = request.POST.get('first_name', False)
            if request.POST.get('last_name', False):
                user.last_name = request.POST.get('last_name', False)
            if request.POST.get('company', False):
                user.company = request.POST.get('company', False)
            if request.POST.get('phone_number', False):
                user.phone_number = request.POST.get('phone_number', False)
            if request.POST.get('location', False):
                user.location = request.POST.get('location', False)
            user.save()

            form.save()

            return redirect(profile)
    else:
        form = UserProfileForm(instance=request.user)
    return render(request, 'edit-profile.html', {'form': form})
Esempio n. 5
0
File: views.py Progetto: Anych/shop
def dashboard(request):
    user = request.user
    try:
        user_profile = UserProfile.objects.get(user=user)
    except Exception:
        _profile(user)
        user_profile = UserProfile.objects.get(user=user)

    orders = Order.objects.order_by('-created_at').filter(user_id=request.user.id, is_ordered=True)
    orders_count = orders.count()
    if request.method == 'POST':

        user_form = UserForm(request.POST, instance=request.user)
        profile_form = UserProfileForm(request.POST, request.FILES, instance=user_profile)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, 'Ваши данные успешно обновлены!')
            return redirect('dashboard')
    else:
        user_form = UserForm(instance=request.user)
        profile_form = UserProfileForm(instance=user_profile)

    context = {
        'orders': orders,
        'orders_count': orders_count,
        'user_form': user_form,
        'profile_form': profile_form,
        'user_profile': user_profile,
    }
    return render(request, 'accounts/dashboard.html', context)
Esempio n. 6
0
def register(request):
    registered = False
    profile = UserProfile.objects.get(user=request.user)

    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.set_password(user.password)
            user.save()

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

	    profile.save()
            registered = True

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

    return render(request,
            'accounts/reg.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered, 'profile': profile,} )
Esempio n. 7
0
def user_profile(request):
    user = request.user
    user_profile = user.userprofile
    consignments = Consignment.objects.filter(receiver_id=user.id).first()

    if request.method == 'GET':
        context = {
            'profile_user': user,
            'profile': user_profile,
            'consignments': consignments,
            'form': UserProfileForm(),
            'is_worker': user.groups.filter(name='worker').exists(),
            'is_customer': user.groups.filter(name='customer').exists(),
        }
        return render(request, 'accounts/user_profile.html', context)
    else:
        old_image = user_profile.profile_picture
        form = UserProfileForm(request.POST,
                               request.FILES,
                               instance=user_profile)

        if form.is_valid():
            if old_image:
                os.remove(old_image.path)
            form.save()
            return redirect('user profile')

        return redirect('user profile')
Esempio n. 8
0
def editProfile(request):
    user = request.user
    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                userprofile = user.userprofile
            except UserProfile.DoesNotExist:
                userprofile = form.instance

            userprofile.user = user
            userprofile.is_verified = True
            userprofile.act_key = "1111"
            userprofile.exp_key = datetime.datetime.now()
            userprofile.gender = form.cleaned_data['gender']
            userprofile.birth_date = form.cleaned_data['birth_date']
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            user.save()
            userprofile.save()
            messages.success(request, _('Changes are done.'))
            return redirect(reverse('profile'))
        else:
            messages.error(request, _('Edit is failed.'))
            return redirect(reverse('register'))
    else:
        form = UserProfileForm()

    return render(request, 'accounts/profile.html', {'form': form})
Esempio n. 9
0
def user_profile_edit(request, pk):
    page = "edit-profile-page"
    user_obj = User.objects.get(pk=pk)
    current_user = request.user
    if user_obj != current_user:
        context = {
            'current_user': current_user,
            'page': page,
        }
        return render(request, 'access-denied.html', context)
    if request.method == 'GET':
        form = UserProfileForm(instance=user_obj.userprofile)
        context = {
            'form': form,
            'current_user': user_obj,
            'user': user_obj,
            'page': page,
        }
        return render(request, 'profile-edit.html', context)
    # old_img = user_obj.userprofile.profile_picture
    form = UserProfileForm(request.POST,
                           request.FILES,
                           instance=user_obj.userprofile)
    if form.is_valid():
        # if old_img:
        #     clean_up_files(old_img.path)
        form.save()
        return redirect('user profile', user_obj.pk)
    context = {
        'form': form,
        'user': user_obj,
        'current_user': user_obj,
        'page': page,
    }
    return render(request, 'profile.html', context)
Esempio n. 10
0
 def get_context_data(self, **kwargs):
     context = {}
     
     try:
         context['emp_info'] = Employment_detail.objects.none()
     except :
         context['emp_info'] = UserProfileForm()
     try:
         context['profile_form'] = UserProfileForm(instance = self.get_object())
     except :
         context['profile_form'] = UserProfileForm()
     try:
         context['edu_detailform'] = Education_levelForm(instance=Education_level.objects.filter(user=self.request.user).first())
     except :
         context['edu_detailform'] = Education_levelForm()
     try:
         context['emp_detailform'] = Employement_DetailForm(instance=Employment_detail.objects.all().filter(user=self.request.user).first())
     except :
         context['emp_detailform'] = Employement_DetailForm()
     try:
         context['pref_form'] = Preference_Form(instance=Preference.objects.filter(user=self.request.user).first())
     except :
         context['pref_form'] = Preference_Form()         
     try:
         context['file_uploadform'] = File_UploadForm(instance=File_uploaded.objects.filter(user=self.request.user).first())
     except :
         context['file_uploadform'] = File_UploadForm()  
     
     return context 
Esempio n. 11
0
def registration(request):

    registered = False

    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()
            profile = profile_form.save(commit=False)
            profile.user = user

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

            profile.save()

            registered = True

        else:
            print user_form.errors, profile_form.errors

    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    return render(
        request, 'accounts/register.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'registered': registered
        })
Esempio n. 12
0
def register(request):
    if request.method == "POST":
        uform = CreateUserForm(request.POST)
        pform = UserProfileForm(request.POST)
        if uform.is_valid() and pform.is_valid():
            # create the user and redirect to profile
            user = uform.save()
            profile = pform.save(commit=False)
            profile.user = user
            profile.save()
            # this would be usefull when the profile is
            # allready created when post_save is triggered
            # profile = user.get_profile()
            # profile.address = pform.cleaned_data['address']
            # profile.save()

            # login the user automatically after registering
            user = authenticate(username=user.username,
                                password=uform.cleaned_data['password'])
            login(request, user)

            return HttpResponseRedirect(reverse('fi_home'))
    else:
        uform = CreateUserForm()
        pform = UserProfileForm()

    ctx = {
        'user_form': uform,
        'profile_form': pform,
    }

    return render(request, 'accounts/register.html', ctx)
Esempio n. 13
0
def change_avatar(request):
    if request.user.is_authenticated:
        if request.method == "POST":
            profileform = UserProfileForm(request.POST, request.FILES)
            if profileform.is_valid():
                pf = profileform.save(commit=False)
                pf.user = request.user
                pf.link = request.FILES['avatar'].name
                if pf.link[-3:] not in ['png', 'jpg', 'gif']:
                    pass
                else:
                    with open(AVATAR_DIR + pf.user.username, "wb+") as f:
                        print AVATAR_DIR + pf.user.username
                        for chunk in request.FILES['avatar'].chunks():
                            f.write(chunk)
                return HttpResponseRedirect('/')
            else:
                return render(request, 'update_avatar.html', {
                    'form': profileform,
                    'merrors': True
                })
        else:
            pform = UserProfileForm()
            return render(request, 'update_avatar.html', {'form': pform})
    else:
        return HttpResponseRedirect("/")
Esempio n. 14
0
def user_signup(request):
    registered = False

    if request.method == 'POST':
        user_form = CreateUserForm(data=request.POST)
        profile_form = UserProfileForm(request.POST, request.FILES)

        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  # one to one relationship

            if 'profile_pic' in request.FILES:
                print('profile pic is uploaded')
                profile.profile_pic = request.FILES['profile_pic']

            profile.save()
            registered = True

        else:
            print(user_form.errors, profile_form.errors)

    else:
        user_form = CreateUserForm()
        profile_form = UserProfileForm()

    return render(
        request, 'accounts/registration.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'registered': registered
        })
Esempio n. 15
0
def update_profile(request, pk):
    user = request.user
    user_profile = UserProfile.objects.get(username=user.username)

    if request.method == "POST ":
        user_form = CreateUserForm(data=request.POST, instance=user)
        profile_form = UserProfileForm(data=request.POST,
                                       instance=user_profile)

        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()
            return HttpResponseRedirect(
                reverse_lazy('accounts:profile', kwargs={'pk': user.pk}))

        else:
            print(user_form.errors, profile_form.errors)

    else:
        user_form = CreateUserForm(instance=user)
        profile_form = UserProfileForm(instance=user_profile)

    return render(request, 'accounts/update_profile.html', {
        'user_form': user_form,
        'profile_form': profile_form,
    })
def edit_profile(request):
    user = get_object_or_404(get_user_model(), pk=request.user.pk)
    if hasattr(user, 'userprofile'):
        up_instance = user.userprofile
    else:
        up_instance = None
    if request.method == "POST":
        user_form = P7UserChangeForm(request.POST,
                                     instance=user,
                                     initial={'confirm_email': user.email})
        profile_form = UserProfileForm(request.POST,
                                       request.FILES,
                                       instance=up_instance)
        if all([user_form.is_valid(), profile_form.is_valid()]):
            user_form.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            sanitizer = Sanitizer()
            profile.bio = sanitizer.sanitize(profile.bio)
            profile.save()
            return redirect(reverse('accounts:profile'))

    else:  # GET
        user_form = P7UserChangeForm(instance=user,
                                     initial={'confirm_email': user.email})
        profile_form = UserProfileForm(instance=up_instance)

    template = 'accounts/edit_profile.html'
    context = {'user_form': user_form, 'profile_form': profile_form}
    return render(request, template, context)
Esempio n. 17
0
def register(request):
    """
    user registration form: GET/POST /registration
    """
    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():
            human = True
            user = user_form.save(commit=False)
            user.set_password(user.password)
            user.save()
            
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()
            
            # save user in session
            login(request, user)
            
            logger.info('user {0} registered successfully'.format(user.username))
            
            request.session['username'] = user.name
            return HttpResponseRedirect(reverse('profile'))

        else:
            print user_form.errors
#             raise Http404("Your registration is failed.")
        
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()
    context = {'user_form': user_form, 'profile_form': profile_form};
    return render(request, 'register.html', context);
Esempio n. 18
0
def profile(request):
    # fetch user from db
    user = User.objects.get(pk=request.user.id)

    # save the forms
    if request.method == "POST":
        # create the form to edit the user
        uform = EditUserForm(data=request.POST, instance=user)
        # also edit the profile of this user
        pform = UserProfileForm(data=request.POST,
                                instance=request.user.get_profile())

        if uform.is_valid() and pform.is_valid():
            uform.save()
            pform.save()
            messages.success(request, 'User udated.')
        else:
            messages.success(request, 'There was an error.')

    else:
        # create the form to edit the user
        uform = EditUserForm(instance=user)
        # also edit the profile of this user
        pform = UserProfileForm(instance=request.user.get_profile())

    ctx = {
        'user_form': uform,
        'profile_form': pform,
    }

    return render(request, 'accounts/profile.html', ctx)
Esempio n. 19
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.

    # 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, 'accounts/register.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'registered': registered
        })
Esempio n. 20
0
def checkout(request):
    if request.method == "POST":
        billing_form = BillingForm(request.POST)
        payment_form = MakePaymentForm(request.POST)
        shipping_form = UserProfileForm(request.POST)

        if payment_form.is_valid() and billing_form.is_valid(
        ) and shipping_form.is_valid():
            order = billing_form.save(commit=False)
            order.user = request.user
            order.date = timezone.now()
            order.save()

            cart = request.session.get('cart', {})
            total = 0
            for id, quantity in cart.items():
                product = get_object_or_404(Product, pk=id)
                total += quantity * product.price
                order_line_item = OrderLineItem(order=order,
                                                product=product,
                                                quantity=quantity)
                order_line_item.save()

            try:
                customer = stripe.Charge.create(
                    amount=int(total * 100),
                    currency="EUR",
                    description=request.user.email,
                    card=payment_form.cleaned_data['stripe_id'])
            except stripe.error.CardError:
                messages.error(request, "Your card was declined!")

            if customer.paid:
                messages.error(request, "You have successfully paid")
                request.session['cart'] = {}
                return redirect(reverse('products'))
            else:
                messages.error(request, "Unable to take payment")
        else:
            print(payment_form.errors)
            messages.error(request,
                           "We were unable to take a payment with that card!")
    else:
        profile = get_object_or_404(UserProfile, user=request.user)

        payment_form = MakePaymentForm()
        billing_form = BillingForm()
        shipping_form = UserProfileForm(instance=profile)

    return render(
        request, "checkout.html", {
            "billing_form": billing_form,
            "shipping_form": shipping_form,
            "payment_form": payment_form,
            "publishable": settings.STRIPE_PUBLISHABLE
        })
Esempio n. 21
0
def edit_profile(request):

    if request.method == "POST":
        profile_form = UserProfileForm(request.POST, request.FILES, instance=request.user)
        if profile_form.is_valid():
            profile_form.save()
            return redirect(profile)
    else:
        profile_form = UserProfileForm()
    return render(request, 'profileform.html', {'profile_form': profile_form})
Esempio n. 22
0
    def test_form_fails_validation_if_required_items_missing(self):
        no_dob_form = UserProfileForm(
            data={'date_of_birth': None, 'bio': self.valid_bio}
        )
        no_bio_form = UserProfileForm(
            data={'date_of_birth': self.valid_date, 'bio': ''}
        )

        for form in [no_dob_form, no_bio_form]:
            self.assertFalse(form.is_valid())
Esempio n. 23
0
def register_user(request):
    """
    Register a user and log them in
    """
    active = "active"
    if request.user.is_authenticated:
        messages.error(request, 'You are already registered')
        return redirect(reverse('index'))

    if request.method == "POST":
        register_form = UserRegistrationForm(request.POST)
        profile_form = UserProfileForm(request.POST, request.FILES)
        if register_form.is_valid() and profile_form.is_valid():
            register_form.save()
            user = auth.authenticate(username=request.POST['username'],
                                     password=request.POST['password1'])
            hasOrg = False
            if user:
                myuserprofile = profile_form.save(commit=False)
                myuserprofile.user = user
                myuserprofile.save()
                auth.login(user=user, request=request)
                messages.success(request, "You have successfully registered")
                userprofile = UserProfile.objects.get(user=user)
                return render(
                    request, 'index.html', {
                        "hasOrg": hasOrg,
                        'active1': active,
                        'userprofile': userprofile
                    })
            else:
                messages.error(request, "Unable to register at this time.")
                return render(
                    request, 'registration.html', {
                        "register_form": register_form,
                        'profile_form': profile_form,
                        'active5': active
                    })
        else:
            messages.error(request, "The form is not valid.")
            return render(
                request, 'registration.html', {
                    "register_form": register_form,
                    'profile_form': profile_form,
                    'active5': active
                })
    else:
        register_form = UserRegistrationForm()
        profile_form = UserProfileForm()
        return render(
            request, 'registration.html', {
                "register_form": register_form,
                'profile_form': profile_form,
                'active5': active
            })
Esempio n. 24
0
def user_center_proinfo(request):
    user = request.user
    user_profile = UserProfile.objects.filter(user=user).first()
    if request.method == 'POST':
        form = UserProfileForm(request.POST)
        print(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            real_name = data.get('real_name')
            age = data.get('age')
            qq = data.get('qq')
            address = data.get('address')
            phone_no = data.get('phone_no')
            gender = data.get('gender')
            province = data.get('province')
            city = data.get('city')
            area = data.get('area')
            email = data.get('email')
            nickname = data.get('nickname')
            up = UserProfile.objects.get_or_create(user=user)
            up = up[0]

            up.real_name = real_name
            up.age = age
            up.qq = qq
            up.address = address
            up.phone_no = phone_no
            up.gender = gender
            up.area = area
            up.province = province
            up.city = city
            up.save()
            user.email = email
            user.nickname = nickname
            user.save()
            return JsonResponse({'status': 200})

        else:
            # params = request.POST.get('params')
            # print(form.non_field_errors())

            error = form.non_field_errors()
            rest = {'data': error, 'age': ''}
            age = request.POST.get('age')
            if isinstance(age, str):
                age_error = '日期格式不正确'
                rest['age'] = age_error
            print(1111)
            return JsonResponse(rest)
    form = UserProfileForm()
    return render(request, 'user_manage/user_center_proinfo.html', {
        'form': form,
        'user_profile': user_profile
    })
Esempio n. 25
0
def Dashboard(request):
    form= UserProfileForm()
    if request.method=='POST':
        form=UserProfileForm(request.POST, request.FILES or None)
        if form.is_valid():
            form.save()
            #user=form.save()
            #user.set_password(user.password)
            #user.save()

    return render(request,'accounts/dashboard.html',{'form':form})
Esempio n. 26
0
def profile_edit(request):
    user = request.user
    profile = user.get_profile()
    if request.method == 'POST':
        form = UserProfileForm(request.POST,request.FILES, instance=profile)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('profile', args=[user.username]))
    else:
        form = UserProfileForm(instance=profile)
    return render_to_response("edit.html", {
        'profile_form': form,
    }, context_instance=RequestContext(request))
Esempio n. 27
0
def order_info(request, template_name="registration/order_info.html"):
    if request.method == 'POST':
        postdata = request.POST.copy()
        form = UserProfileForm(postdata)
        if form.is_valid():
            profile.set(request)
            url = reverse('my_account')
            return HttpResponseRedirect(url)
    else:
        user_profile = profile.retrieve(request)
        form = UserProfileForm(instance=user_profile)
    page_title = 'Edit Order Information'
    return render(request, template_name, locals(), RequestContext(request))
Esempio n. 28
0
def edit_user_profile(request):
    '''
    Edit users profile
    '''
    active = "active"
    if request.user.is_authenticated:
        hasOrg = False
        instance = get_object_or_404(UserProfile, user=request.user)
        org = Org.objects.filter(user=request.user)
        if request.method == "POST":
            profile_form = UserProfileForm(request.POST, request.FILES)
            if profile_form.is_valid():
                user_profile = profile_form.save(commit=False)
                if user_profile.profile_picture:
                    if user_profile.profile_picture != instance.profile_picture:
                        instance.profile_picture.delete(save=True)
                        user_profile.profile_picture = request.FILES[
                            "profile_picture"]
                else:
                    user_profile.profile_picture = instance.profile_picture
                user_profile.user = request.user
                user_profile.id = instance.id
                user_profile.save(force_update=True)
                messages.success(
                    request, "You have successfully updated your user profile")
                return render(
                    request, 'index.html', {
                        'active1': active,
                        'userprofile': user_profile,
                        'hasOrg': hasOrg
                    })
            else:
                messages.error(request, "Unable to edit at this time.")
                return render(
                    request, 'edituserprofile.html', {
                        'profile_form': profile_form,
                        'userprofile': instance,
                        'active10': active,
                        'hasOrg': hasOrg
                    })
        else:
            profile_form = UserProfileForm(instance=instance)
            return render(
                request, 'edituserprofile.html', {
                    'profile_form': profile_form,
                    'userprofile': instance,
                    'active10': active,
                    'hasOrg': hasOrg
                })
    else:
        return render(request, 'index.html', {'active1': active})
Esempio n. 29
0
def user_profile(request, pk=None):
    user = request.user if pk is None else User.objects.get(pk=pk)
    if request.method == "GET":
        context = {
            'user': user,
            'profile': user.userprofile,
            'pets': user.userprofile.pet_set.all(),
            'form': UserProfileForm(),
        }
        return render(request, 'accounts/user_profile.html', context)
    else:
        form = UserProfileForm(request.POST, request.FILES, isinstance=user.userprofile)
        if form.is_valid():
            form.save()
        return redirect('current_user_profile')
Esempio n. 30
0
    def post(self, *args, **kwargs):
        data = self.request.POST
        # Load User and Profile forms
        form = UserForm(data)
        profileform = UserProfileForm(data)

        # Calls the validation method of the two model forms
        if form.is_valid() and profileform.is_valid():
            # create and save user object
            user = form.save()
            # create and save profile object
            # assign `user` as a fk of the user field in the profile object
            profile = profileform.save(commit=False)
            profile.user = user
            profile.save()
            # authenticate user
            self.login_user_no_password(user)

            # Redirect to dashboard
            return HttpResponseRedirect(reverse('dashboard'))

        else:
            self.context['form'] = form
            self.context['profileform'] = profileform
            return render(self.request, self.template_name, self.context)