def user_profile(request):
    """
    Form to update User profile
    """
    user_ = get_user_in_token(request)

    if request.method == 'POST':
        nic = request.POST.get('nicname')
        profileForm = UserProfileForm(request.POST, request.FILES, instance=user_.get_profile())
        userForm = UserForm(request.POST, instance=user_)
        # if profileForm.is_valid() and userForm.is_valid():
        if profileForm.is_valid():
            profileForm.save()
            userForm.save()
            return output_format_json_response(201, message='프로필이 변경 되었습니다.', statusCode='0000')
    else:
        profile = request.user.get_profile()
        profile_data = {
            'nickname': profile.nickname,
            'picture_url': profile.get_image_url(),
            'phone_number': profile.phone_number
        }
        return output_format_response(200, statusCode='0000', data=profile_data)

    return output_format_json_response(message='요청이 잘못되었습니다.', statusCode='5555')
Esempio n. 2
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. 3
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. 4
0
def edit(request):
    try:
        profile = UserProfile.objects.get(pk=1)
    except UserProfile.DoesNotExist:
        raise Http404

    if 'POST' == request.method:
        form = UserProfileForm(request.POST, instance=profile)
        if request.is_ajax():
            if form.is_valid():
                form.save()
                success = True
                errors = []
            else:
                success = False
                errors = [(k, unicode(v[0])) for k, v in form.errors.items()]
            json = simplejson.dumps(({'success': success,
                                      'errors': errors, }))
            return HttpResponse(json, mimetype='application/javascript')

        else:
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/edit/saved/')
    else:
        form = UserProfileForm(instance=profile)
    return render_to_response('accounts/edit.html',
                              {'form': form},
                              context_instance=RequestContext(request))
Esempio n. 5
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. 6
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. 7
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. 8
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))
class ProfileView(TemplateResponseMixin, LoginRequiredMixin, View):
    template_name = 'aonebrains_main/students/profile_form.html'
    user_form = None

    def get(self, request, *args, **kwargs):
        self.user_form = UserProfileForm(instance=request.user)
        return self.render_to_response({'form': self.user_form})

    def post(self, request, *args, **kwargs):
        self.user_form = UserProfileForm(instance=request.user, data=request.POST, files=request.FILES)
        if self.user_form.is_valid():
            self.user_form.save()
            return redirect('aonebrains_main:Home')
        return self.render_to_response({'form': self.user_form})
Esempio n. 10
0
def edit_profile(request):
    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
            messages.add_message(request, messages.SUCCESS, 'Your profile has been updated')
            return HttpResponseRedirect('/profile')
        else:
            # form = ContactView()
            # messages.add_message(request, messages.ERROR, 'Your message not sent. Not enough data')
            return render(request, 'loggedin.html', {'form': form})

    else:
        form = UserProfileForm()
        return render(request, 'loggedin.html', {'form': form})
Esempio n. 11
0
def profile_edit(request):
    profile, is_created = UserProfile.objects.get_or_create(user=request.user)

    if request.method == 'POST':
        form = UserProfileForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            messages.success(request, 'Profile 정보가 업데이트되었습니다.')
            next_url = request.GET.get('next', 'accounts.views.profile_detail')
            return redirect(next_url)
    else:
        form = UserProfileForm(instance=profile)
    return render(request, 'form.html', {
        'form': form,
    })
Esempio n. 12
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. 13
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. 14
0
 def test_profile_forms(self):
     user_form_data = {'username': '******',
                  'first_name': 'dave',
                  'last_name': 'Bright',
                  'email':'*****@*****.**',
                  'password':'******',
                  'password_confirm':'pwd123',
                  }
     user_form = UserForm(data=user_form_data)
     
     if not user_form.is_valid():
         print user_form.errors
     else:
         self.assertTrue(user_form.is_valid())
         user = user_form.save(commit=False)
         user.set_password(user.password)
         user.save()
         
         profile_form_data = {
             'birth_year':1983,
             'captcha_0':'dummy-value',
             'captcha_1':'PASSED'
         }
         profile_form = UserProfileForm(data=profile_form_data)
         
         if not profile_form.is_valid():
             print profile_form.errors
         else:
             profile = profile_form.save(commit=False)
             profile.user = user
             profile.save()
Esempio n. 15
0
def user_profile(request):
    if request.method == "POST":
        form = UserProfileForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            # my_form = form.save(commit=False)
            form.save()
            # messages.add_message(request, messages.SUCCESS, 'Your message has been sent. Thank you.')
            return HttpResponseRedirect("/profile")
        else:
            # form = ContactView()
            # messages.add_message(request, messages.ERROR, 'Your message not sent. Not enough data')
            return render(request, "contact.html", {"form": form})

    else:
        form = UserProfileForm()
        return render(request, "contact.html", {"form": form})
Esempio n. 16
0
def edit_my_profile(request):
	u = request.user
	
	try: profile = u.get_profile()
	except UserProfile.DoesNotExist: profile = None
	
	if request.method == 'POST':
		POST = request.POST.copy()
		POST['user'] = u.id
		
		profile_form = UserProfileForm(POST, request.FILES, instance=profile)
		user_form = UserForm(request.POST, request.FILES, instance=u)
		
		if user_form.is_valid() and profile_form.is_valid():
			u = user_form.save()
			profile = profile_form.save()
			profile.user = u
			
			request.user.message_set.create(message="Your Profile was updated")
			
			return HttpResponseRedirect(profile.get_absolute_url())
	else:
		user_form = UserForm(instance=u)
		
		if profile: profile_form = UserProfileForm(instance=profile)
		else: profile_form = UserProfileForm(initial={'user':request.user})
		
	return render(request, 'edit_profile.html', {'profile_form':profile_form, 'user_form':user_form})
Esempio n. 17
0
 def post(self, request, *args, **kwargs):
     # Attempt to grab information from the raw form information.
     # Note that we make use of both UserForm and PublicForm.
     form_args = {
         'data': request.POST,
     }
     user_form = UserForm(data=request.POST, instance=request.user)
     instance = UserProfile.objects.get(user=request.user)
     kwargs.setdefault('curruser', instance)
     profile_form = UserProfileForm(data=request.POST, instance=instance)
     # 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 sort out the Public 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 Public model.
         if 'picture' in request.FILES:
             profile.picture = request.FILES['picture']
         # Now we save the Public model instance.
         profile.save()
 
     # 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
     kwargs.setdefault("user_form", self.user_form_class(instance=instance.user))
     kwargs.setdefault("profile_form", self.profile_form_class(instance=instance))
     return super(Profile, self).get(request, *args, **kwargs)
Esempio n. 18
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. 19
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,
    })
Esempio n. 20
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. 21
0
def register(request):
	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

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


			profile.save()

		else:
			print user_form.errors, profile_form.errors

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

	context = {'user_form' : user_form, 'profile_form' : profile_form}
	return render_to_response('accounts/register.html', context, context_instance=RequestContext(request))
Esempio n. 22
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. 23
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. 24
0
def details(request):
    ctx = {}
    form = AccountForm(instance=request.user)
    pform = UserProfileForm(instance=request.user.get_profile())
    if request.method == 'POST':
        form = AccountForm(request.POST, instance=request.user)
        pform = UserProfileForm(request.POST,
            instance=request.user.get_profile())
        if form.is_valid() and pform.is_valid():
            form.save()
            pform.save()
            messages.info(request, _('Account updated.'))
    ctx['form'] = form
    ctx['pform'] = pform
    return render_to_response('accounts/details.html', ctx,
        context_instance=RequestContext(request))
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. 26
0
def change_user_profile(request):
    """
    View for display and processing of a user profile form.
    """
    try:
        # Try to get a existing user profile
        user_profile = request.user.get_profile()
    except UserProfile.DoesNotExist:
        user_profile = None
    if request.method == 'POST':
        # Form processing
        form = UserProfileForm(request.POST)
        if form.is_valid():
            profile = form.save(commit=False)

            if user_profile:
                profile.id = user_profile.id
            profile.user = request.user
            profile.save()

    else:
        # Render the form
        form = UserProfileForm(instance=user_profile)
    return render_to_response('accounts/profile_form.html', {
        'formset': form,}, context_instance=RequestContext(request))
Esempio n. 27
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. 28
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)
Esempio n. 29
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)
Esempio n. 30
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. 31
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. 32
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. 33
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. 34
0
def register(request):
    # Like before, get the request's context.
    context = RequestContext(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_to_response(
            'register.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
            context)
Esempio n. 35
0
def details(request):
    ctx = {}
    form = AccountForm(instance=request.user)
    pform = UserProfileForm(instance=request.user.get_profile())
    if request.method == 'POST':
        form = AccountForm(request.POST, instance=request.user)
        pform = UserProfileForm(request.POST,
                                instance=request.user.get_profile())
        if form.is_valid() and pform.is_valid():
            form.save()
            pform.save()
            messages.info(request, _('Account updated.'))
    ctx['form'] = form
    ctx['pform'] = pform
    return render_to_response('accounts/details.html',
                              ctx,
                              context_instance=RequestContext(request))
Esempio n. 36
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. 37
0
File: views.py Progetto: Anych/shop
def edit_profile(request):
    userprofile = get_object_or_404(UserProfile, user=request.user)
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = UserProfileForm(request.POST, request.FILES, instance=userprofile)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, 'Your profile has been updated.')
            return redirect('edit_profile')
    else:
        user_form = UserForm(instance=request.user)
        profile_form = UserProfileForm(instance=userprofile)
    context = {
        'user_form': user_form,
        'profile_form': profile_form,
        'userprofile': userprofile,
    }
    return render(request, 'accounts/edit_profile.html', context)
Esempio n. 38
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. 39
0
def update(request):
    if request.method == 'POST':
        userform = UserForm(request.POST, instance=request.user)
        profileform = UserProfileForm(request.POST, instance=request.user.get_profile())
        if userform.is_valid() and profileform.is_valid():
            userform.save()
            profileform.save()
            request.user.message_set.create(message="Ændringerne er blevet opdateret.")
            return HttpResponseRedirect(reverse('user_profile', args=[request.user.username]))  
    else:
        userform = UserForm(instance=request.user)
        try:
            profileform = UserProfileForm(instance=request.user.get_profile())
        except UserProfile.DoesNotExist:
            UserProfile(user=request.user).save()
            profileform = UserProfileForm(instance=request.user.get_profile())
    return render_to_response(
        'profiles/update.html', { 'userform': userform, 'profileform': profileform },
        context_instance = RequestContext(request)
    )
Esempio n. 40
0
def update_profile(request):
    
    if request.user.is_authenticated():

        profile, created = UserProfile.objects.get_or_create(user=request.user)
        profile.name = profile.name or request.user.first_name

        form = UserProfileForm(request.POST or None, instance=profile)

        

        if request.POST:
            if form.is_valid():
                form.save()
            return HttpResponseRedirect('/')
    else:
        form = None
        #messages.add_message(request, messages.INFO, 'You may sign in to update your profile.')
    return render_to_response("accounts/profile_edit.html",
        {'form': form,},context_instance=RequestContext(request))
def edit_profile(request, pk=None):

    # Get user profile details
    profile = get_object_or_404(UserProfile, user=request.user) 
    
    info = UserProfile.objects.filter(user=request.user)
    for i in info:
        username = i.user

    if request.method == "POST":
        form = UserProfileForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            form.save()
            return redirect(reverse('profile'))
    else:
        form = UserProfileForm(instance=profile)
    return render(request, 'profileform.html', {
        'form': form,
        'username': username
    })
Esempio n. 42
0
def view_profile(request: HttpRequest) -> HttpResponse:
    header_title = 'Profile'
    user = User.objects.get(pk=request.user.pk)
    if request.method == 'POST':
        user_form = UserProfileForm(request.POST, instance=user)
        profile_form = UserProfileBaseForm(request.POST,
                                           instance=user.userprofilebase)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
        messages.success(request, 'Profile updated successfully.')
    else:
        user_form = UserProfileForm(instance=user)
        profile_form = UserProfileBaseForm(instance=user.userprofilebase)
    return render(
        request, 'accounts/accounts_profile.html', {
            'header_title': header_title,
            'user_form': user_form,
            'profile_form': profile_form
        })
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.is_active = False

            username = user.username
            email = user.email
            salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
            activation_key = hashlib.sha1(salt + email).hexdigest()
            key_expires = datetime.datetime.today() + datetime.timedelta(2)

            user.save()

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

            profile.activation_key = activation_key
            profile.key_expires = key_expires

            profile.save()

            registered = True

            # Send email with activation key
            email_subject = 'Account confirmation'
            email_body = "Hey %s, thanks for signing up. To activate your account, click this link within \
            48hours http://127.0.0.1:8000/accounts/confirm/%s" % (username, activation_key)

            send_mail(email_subject, email_body, '*****@*****.**',
                      [email], fail_silently=False)

        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(
        'accounts/register.html',
        {'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
        context)
Esempio n. 44
0
def profile_edit(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.
    updated = 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 = UpdateProfile(data=request.POST, instance=request.user)
        profile_form = UserProfileForm(data=request.POST, instance=request.user.userprofile)

        # 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()
            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 'mobitel' in request.POST:
                profile.mobitel = request.POST['mobitel']
            if 'zupanija' in request.POST:
                profile.zupanija = request.POST['zupanija']

            # Now we save the UserProfile model instance.
            profile.save()
            
            # Update our variable to tell the template registration was successful.
            updated = 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 = UpdateProfile(instance=request.user)
        profile_form = UserProfileForm(instance=request.user.userprofile)

    # Render the template depending on the context.
    return render(request,
            'accounts/profile_edit_form.html',
            {'user_form': user_form, 'profile_form': profile_form, 'updated': updated} )
Esempio n. 45
0
def checkout_success(request, order_number):
    # Successful checkout
    save_info = request.session.get('save_info')
    order = get_object_or_404(Order, order_number=order_number)

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

        # Save the user's info
        if save_info:
            account_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_profile_form = UserProfileForm(account_data, instance=account)
            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 'cart' in request.session:
        del request.session['cart']

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

    return render(request, template, context)
Esempio n. 46
0
def respondent_intro(request):
    countries = models.CountryMaster.objects.filter(
        is_active=True).order_by('country_name')
    user_profile = UserProfile.objects.get(user=request.user)
    img_profile = user_profile.profile_pic
    # img_company = user_profile.company_logo
    if request.method == 'POST':
        if request.data.get("skip", None):
            # print("skip-1")
            form_class = UserProfileForm(request.POST,
                                         request.FILES,
                                         instance=user_profile)
            if form_class.is_valid():
                # print("valid-1")
                obj = form_class.save(commit=False)
                obj.save()
                # form_class = UserProfileCompleteForm(instance=user_profile)
                context = {
                    'form': form_class,
                    'skip': '1',
                    'countries': countries
                }
            else:
                # print("error-1")
                context = {
                    'form': form_class,
                    'profile_src': img_profile,
                    'countries': countries
                }
            return render(request, 'respondent_intro.html', context=context)

    else:
        # print("============ Client Intro ============")
        # print("************ Client GET   ************")

        if user_profile.first_name is None or user_profile.city is None or user_profile.state is None \
                or user_profile.pincode is None or user_profile.country is None:
            form_class = UserCompleteForm(instance=user_profile)
            context = {
                'form': form_class,
                'profile_src': img_profile,
                'countries': countries
            }

        else:
            form_class = UserCompleteForm(instance=user_profile)
            context = {
                'form': form_class,
                'profile_src': img_profile,
                'countries': countries
            }
        return render(request, 'respondent_intro.html', context=context)
Esempio n. 47
0
    def post(self, request):
        form = UserProfileForm(request.POST, request.FILES)

        if form.is_valid():
            user_profile = form.save(commit=False)
            user_profile.user = request.user
            user_profile.save()

            return HttpResponseRedirect(reverse_lazy('xplrmain:feed-page'))
        else:
            print("Image Upload: {}".format(request.POST['profile_pic']))

        return render(request, 'registration/welcome.html', {'form': form})
Esempio n. 48
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. 49
0
def profile(request):
    context = {}
    if request.method == 'POST':
        form = UserProfileForm(request.POST)
        if form.is_valid():
            try:
                profile = UserProfile.objects.get(user_id=request.user.id)
                form.instance.pk = profile.pk
            except ObjectDoesNotExist:
                pass

            form.instance.user = request.user
            form.save()
            context['info_message'] = _('Profile saved')
    else:
        try:
            profile = UserProfile.objects.get(user_id=request.user.id)
            form = UserProfileForm(instance=profile)
        except ObjectDoesNotExist:
            form = UserProfileForm()

    context['form'] = form
    return render(request, 'accounts/profile.html', context)
Esempio n. 50
0
def registration(request):

    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.

        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 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,
            'accounts/register.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )
Esempio n. 51
0
def register(request):
    # Like before,get the request's context.
    context = RequestContext(request)

    registered = False

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

        # 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()

            # hash the password
            user.set_password(user.password)
            user.save()

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

            # Did the user provide a profile picture?
            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']

            # save UserProfile model instance
            profile.save()

            registered = True

        # invalid forms,
        else:
            print user_form.errors, profile_form.errors

    # not a http post
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    # Render the template depending on the context
    return render_to_response(
        'account/register.html',
        {'user_form': user_form,
         'profile_form': profile_form,
         'registered': registered},
        context
    )
Esempio n. 52
0
def register2(request):
    if request.method == 'POST':
        form = UserProfileForm(request.POST)
        if form.is_valid():
            hi = form.save(commit=False)
            hi.user = request.user
            UserProfile.objects.filter(user=request.user).delete()
            hi.save()
            return redirect('/account/profile')
    else:
        form = UserProfileForm()

        args = {
            'form': form,
        }
        return render(request, 'accounts/reg_form_2.html', args)
Esempio n. 53
0
def profile_update(request):

    profile, created = UserProfile.objects.get_or_create(user=request.user)

    if request.method == 'POST':
        form = UserProfileForm(request.POST, instance=profile)
        if form.is_valid():
            profile = form.save()
            messages.add_message(request, SUCCESS, 'Your profile has been updated successfully.')
        else:
            messages.add_message(request, ERROR, 'Something went wrong.')
    else:
        form = UserProfileForm(instance=profile)

    return render(request, 'profile_update.html', {
        'userprofile': form,
    })
Esempio n. 54
0
def profile(request):
    try:
        info = UserProfile.objects.get(user=request.user)
    except:
        info = UserProfile(user=request.user)
    if request.method == 'POST':
        info_form = UserProfileForm(request.POST, request.FILES, instance=info)
        if info_form.is_valid():
            info_form = info_form.save()
        else:
            logger.debug("验证错误!")
        return HttpResponseRedirect("/accounts/profile")
    else:
        info_form = UserProfileForm(instance=info)
    return render_to_response("accounts/profile.html", {
            'form':info_form
            },context_instance=RequestContext(request))
Esempio n. 55
0
def edit(request):
    context = {}
    edit_form = UserEditForm(instance=request.user)
    edit_profile_form = UserProfileForm(instance=request.user.get_profile())

    if request.method == "POST":
        edit_form = UserEditForm(data=request.POST, instance=request.user)
        if edit_form.is_valid():
            edit_profile_form = UserProfileForm(data=request.POST, instance=request.user.get_profile())
            if edit_profile_form.is_valid():
                try:
                    team = Team.objects.get(name=request.POST['team'])
                except:
                    team = Team.objects.create(name=request.POST['team'])
                try:
                    old_team = TeamUser.objects.get(user=request.user)
                except:
                    old_team = TeamUser.objects.none()


                if not old_team or old_team.team.name != team.name:
                    old_team.delete()
                    print old_team
                    team_user = TeamUser.objects.create(team=team, user=request.user)
            
            
                user = edit_form.save()
                user.set_password(user.password)
                user.email = request.POST['email']
                user.first_name = request.POST['first_name']
                user.last_name = request.POST['last_name']
                user.save();
                
                user_profile = edit_profile_form.save()
                return HttpResponseRedirect(reverse('dashboard.views.index'))
            else:
                print edit_profile_form.errors
        else:
            print userform.errors
                

    context = {'edit_user_form': edit_form, 
               'edit_user_profile_form': edit_profile_form}

    return render_to_response('edit.html', RequestContext(request, context))
Esempio n. 56
0
def new(request):
    context = {}
    user_form = UserCreationForm()
    user_profile_form = UserProfileForm()
    if request.method == "POST":
        user_profile_form = UserProfileForm(data=request.POST)
        if not user_profile_form.is_valid():
            context['new_user_form'] = user_form
            context['new_user_profile_form'] = user_profile_form
            return render_to_response("new.html", RequestContext(request, context))
        user_form = UserCreationForm(data=request.POST)
        if user_form.is_valid():
            user = User.objects.create_user(user_form.cleaned_data['username'],
                                            user_form.cleaned_data['email'],
                                            user_form.cleaned_data['password'])
            if user_profile_form.is_valid():
                user_profile = user_profile_form.save(commit=False)
                user_profile.user = user
                user_profile.save()
                try:
                    team = Team.objects.get(name=request.POST['team'])
                except:
                    team = Team(name=request.POST['team'])
                    team.save()
                team_user = TeamUser(team=team, user=user)
                team_user.save()
                
                if request.POST.get("isadmin", False):
                    user.groups.add(Group.objects.get(name="Administrator"))
                else:
                    user.groups.add(Group.objects.get(name="Standard User"))
                
                return HttpResponseRedirect(reverse('accounts.views.login'))
            else:
                raise Exception("Form not valid")
        else:
            print user_form.errors
        pass

    context['new_user_form'] = user_form
    context['new_user_profile_form'] = user_profile_form

    return render_to_response("new.html", RequestContext(request, context))
Esempio n. 57
0
def register(request):
    template = 'accounts/register.html'
    if request.method=='GET':
        return render(request, template, {'userForm':UserForm(),
                                          'userProfileForm':UserProfileForm()})
    # request.method == 'POST':
    userForm = UserForm(request.POST)
    userProfileForm = UserProfileForm(request.POST)
    if not (userForm.is_valid() and userProfileForm.is_valid()):
        return render(request, template, {'userForm':userForm,
                                          'userProfileForm':userProfileForm})
    user = userForm.save()
    user.set_password(user.password)
    user.save()
    userProfile = userProfileForm.save(commit=False)
    userProfile.user = user
    userProfile.save()
    messages.success(request, '歡迎註冊')
    return redirect(reverse('main:main'))
Esempio n. 58
0
def registration(request):

    registered = False
    
    try:

        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
            
                return redirect('/accounts/login/')

            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()

            return render(request,
                'accounts/register.html',
                {'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )
                
    except Exception as err:
        
        print err
Esempio n. 59
0
def register(request, template_name='accounts/register.html'):
    """
    Allow a user to register an account.

    :returns:
        A :py:class:`!django.http.HttpResponse` on GET, which renders a
        registration form.
        A :py:class:`!django.http.HttpResponseRedirect on successful POST,
        which redirects to the 'success' view.
    """
    context = {}
    post_signup_url = request.REQUEST.get('next') or 'register_success'
    if "post_signup_url" in request.session:
        post_signup_url = request.session["post_signup_url"]

    reg_form = RegistrationForm(request.POST or None)
    profile_form = UserProfileForm(request.POST or None)
    if reg_form.is_valid() and profile_form.is_valid():
        user = reg_form.save()
        if user.user_profile is not None:
            # Re-make the profile form against the auto-created user profile
            profile_form = UserProfileForm(request.POST,
                                           instance=user.user_profile)

        user_profile = profile_form.save(commit=False)
        user_profile.user = user
        user_profile.activation_key = user_profile.generate_activation_key()
        user_profile.detected_country = request.country
        user_profile.preferred_currency = request.session.get('preferred_currency', '')
        user_profile.save()
        Events(request).user_signup(user)
        
        # logging him in
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        auth_login(request, user)

        request.session['new_user'] = True
        messages.success(request, REGISTER_SUCCESS_MESSAGE)
        return redirect(post_signup_url)

    context.update({'reg_form': reg_form, 'profile_form': profile_form})
    return render(request, template_name, context)