Ejemplo n.º 1
0
def edit(request, user_id=0):

    if user_id != 0 and can_edit_user(request, user_id):
        view_user = User.objects.get(pk=user_id)
    elif user_id == 0:
        view_user = request.user
    else:
        raise PermissionDenied

    key = ApiKey.objects.get(user=view_user)
    if request.method == 'POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            # update basic data
            edit_form_process(form, view_user)

            messages.success(request, _(u"Profile updated"))

            # if password should be changed
            password = form.cleaned_data.get("password")
            if password:
                view_user.set_password(password)
                view_user.save()
                messages.success(request, _(u"Password updated"))
    else:
        initial = edit_form_initial(view_user, key)
        form = ProfileForm(initial=initial)

    return render(request, 'profile/profile.html', {
        'form': form,
        'user': view_user
    })
Ejemplo n.º 2
0
def profile(request, username):
    
    user = get_object_or_404(User, username=username)
#    profile = Profile.objects.get_or_create(user=user)[0]
    profile = user.get_profile()

    if request.method == 'POST':
        if request.POST.has_key('change_rep'):
            if not request.user.is_staff:
                return HttpRepsonse("Unauthorized")
            rep_form = RepForm(request.POST)
            if rep_form.is_valid():
                profile.reputation = rep_form.cleaned_data['base_rep']
                profile.save()
                return HttpResponseRedirect(reverse('quanda_public_profile', args=[username]))
        elif request.POST.has_key('save_profile'):
            if not request.user == profile.user:
                return HttpResponse("Unauthorized")
            profile_form = ProfileForm(request.POST, instance=profile)
            if profile_form.is_valid():
                #return HttpResponse("ready to save")
                profile = profile_form.save()
                return HttpResponseRedirect(reverse('quanda_public_profile', args=[username]))
    else:
        profile_form = ProfileForm(instance=profile)
        rep_form = RepForm(initial={'base_rep': profile.reputation})
    
    return render_to_response("quanda/profile.html", {
        'rep_form': rep_form,
        'profile_form': profile_form,
        'questions': Question.objects.filter(author__username=username).order_by('-posted'),
        'answers': Answer.objects.filter(author__username=username).order_by('-posted'),
        'profile': profile,
        'tinymce': TINY_MCE_JS_LOCATION,
        }, context_instance=RequestContext(request))
    def process_profile_update(self, bundle):
        errors = []
        data = {'email': bundle.data['email']
                if 'email' in bundle.data else '',
                'first_name': bundle.data['first_name'],
                'last_name': bundle.data['last_name'],
                'username': bundle.request.user}

        custom_fields = CustomField.objects.all()
        for custom_field in custom_fields:
            try:
                data[custom_field.id] = bundle.data[custom_field.id]
            except KeyError:
                pass

        profile_form = ProfileForm(data=data)
        if not profile_form.is_valid():
            error_str = ""
            for key, value in profile_form.errors.items():
                for error in value:
                    error_str += error + "\n"
            raise BadRequest(error_str)
        else:
            email = bundle.data['email'] if 'email' in bundle.data else ''
            first_name = bundle.data['first_name']
            last_name = bundle.data['last_name']

        try:
            user = User.objects.get(username=bundle.request.user)
            bundle.obj = user
            bundle.obj.first_name = first_name
            bundle.obj.last_name = last_name
            bundle.obj.email = email
            bundle.obj.save()
        except User.DoesNotExist:
            raise BadRequest(_(u'Username not found'))

        # Create base UserProfile
        user_profile = self.process_profile_update_base_profile(bundle)
        # Create any CustomField entries
        user_fields = [f.name for f in User._meta.get_fields()]
        custom_fields = {field: bundle.data[field] for field in bundle.data if field not in user_fields}
        update_custom_fields_errors = user_profile.update_customfields(custom_fields)

        if update_custom_fields_errors:
            errors += update_custom_fields_errors

        if errors:
            DataRecovery.create_data_recovery_entry(
                user=user,
                data_type=DataRecovery.Type.USER_PROFILE,
                reasons=errors,
                data=bundle.data
            )

        return bundle
Ejemplo n.º 4
0
def edit(request, user_id=0):

    if user_id != 0 and can_edit_user(request, user_id):
        view_user = User.objects.get(pk=user_id)
    elif user_id == 0:
        view_user = request.user
    else:
        raise exceptions.PermissionDenied

    key = ApiKey.objects.get(user=view_user)
    if request.method == 'POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            # update basic data
            email = form.cleaned_data.get("email")
            first_name = form.cleaned_data.get("first_name")
            last_name = form.cleaned_data.get("last_name")
            view_user.email = email
            view_user.first_name = first_name
            view_user.last_name = last_name
            view_user.save()

            user_profile, created = UserProfile.objects.get_or_create(
                user=view_user)
            user_profile.job_title = form.cleaned_data.get("job_title")
            user_profile.organisation = form.cleaned_data.get("organisation")
            user_profile.save()

            messages.success(request, _(u"Profile updated"))

            # if password should be changed
            password = form.cleaned_data.get("password")
            if password:
                view_user.set_password(password)
                view_user.save()
                messages.success(request, _(u"Password updated"))
    else:
        user_profile, created = UserProfile.objects.get_or_create(
            user=view_user)

        form = ProfileForm(
            initial={
                'username': view_user.username,
                'email': view_user.email,
                'first_name': view_user.first_name,
                'last_name': view_user.last_name,
                'api_key': key.key,
                'job_title': user_profile.job_title,
                'organisation': user_profile.organisation,
            })

    return render(request, 'profile/profile.html', {
        'form': form,
    })
Ejemplo n.º 5
0
def edit(request, user_id=0):
        
    if user_id != 0 and can_edit_user(request, user_id):
        view_user = User.objects.get(pk=user_id)
    elif user_id == 0:
        view_user = request.user    
    else:
        raise exceptions.PermissionDenied
        
    key = ApiKey.objects.get(user=view_user)
    if request.method == 'POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            # update basic data
            email = form.cleaned_data.get("email")
            first_name = form.cleaned_data.get("first_name")
            last_name = form.cleaned_data.get("last_name")
            view_user.email = email
            view_user.first_name = first_name
            view_user.last_name = last_name
            view_user.save()

            user_profile, created = UserProfile.objects.get_or_create(user=view_user)
            user_profile.job_title = form.cleaned_data.get("job_title")
            user_profile.organisation = form.cleaned_data.get("organisation")
            user_profile.save()
        
            messages.success(request, _(u"Profile updated"))

            # if password should be changed
            password = form.cleaned_data.get("password")
            if password:
                view_user.set_password(password)
                view_user.save()
                messages.success(request, _(u"Password updated"))
    else:
        user_profile, created = UserProfile.objects.get_or_create(user=view_user)
        
        form = ProfileForm(initial={'username': view_user.username,
                                    'email': view_user.email,
                                    'first_name': view_user.first_name,
                                    'last_name': view_user.last_name,
                                    'api_key': key.key,
                                    'job_title': user_profile.job_title,
                                    'organisation': user_profile.organisation, })

    return render(request, 'oppia/profile/profile.html',
                  {'form': form, })
Ejemplo n.º 6
0
def profile(request, username, template_name="profiles/profile.html"):
    if request.user.is_authenticated():
        if request.method == "POST":
            if request.POST["action"] == "update":
                profile_form = ProfileForm(request.POST, instance=user.get_profile())
                if profile_form.is_valid():
                    profile = profile_form.save(commit=False)
                    profile.user = user
                    profile.save()
        else:
            profile_form = ProfileForm(instance=user.get_profile())
    else:
        profile_form = None

    return render_to_response(template_name, {
        "profile_form": profile_form,
    }, context_instance=RequestContext(request))
Ejemplo n.º 7
0
    def process_profile_update(self, bundle):
        data = {'email': bundle.data['email']
                if 'email' in bundle.data else '',
                'first_name': bundle.data['first_name'],
                'last_name': bundle.data['last_name'],
                'username': bundle.request.user}

        custom_fields = CustomField.objects.all()
        for custom_field in custom_fields:
            try:
                data[custom_field.id] = bundle.data[custom_field.id]
            except KeyError:
                pass

        profile_form = ProfileForm(data=data)

        dashboard_accessed.send(sender=None,
                                request=bundle.request,
                                data=bundle.data)

        if not profile_form.is_valid():
            error_str = ""
            for key, value in profile_form.errors.items():
                for error in value:
                    error_str += error + "\n"
            raise BadRequest(error_str)
        else:
            email = bundle.data['email'] if 'email' in bundle.data else ''
            first_name = bundle.data['first_name']
            last_name = bundle.data['last_name']

        try:
            bundle.obj = User.objects.get(username=bundle.request.user)
            bundle.obj.first_name = first_name
            bundle.obj.last_name = last_name
            bundle.obj.email = email
            bundle.obj.save()
        except User.DoesNotExist:
            raise BadRequest(_(u'Username not found'))

        # Create base UserProfile
        user_profile = self.process_profile_update_base_profile(bundle)
        # Create any CustomField entries
        user_profile.update_customfields(bundle.data)

        return bundle
Ejemplo n.º 8
0
def personal(request):
    """
    Personal data of the user profile
    """
    profile, created = Profile.objects.get_or_create(user=request.user)

    if request.method == "POST":
        form = ProfileForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse("profile_edit_personal_done"))
    else:
        form = ProfileForm(instance=profile)

    template = "profile/profile/personal.html"
    data = { 'section': 'personal', 'GOOGLE_MAPS_API_KEY': GOOGLE_MAPS_API_KEY,
             'form': form, }
    return render_to_response(template, data, context_instance=RequestContext(request))
Ejemplo n.º 9
0
def profile_view(request):
    """
    Allow user to add personnal data to his profile
    """
    profile = request.user.get_profile()
    context = {"current": "account"}
    if request.method == "POST":
        profile_form = ProfileForm(instance=profile, data=request.POST)
        user_form = UserForm(instance=request.user, data=request.POST)
        if profile_form.is_valid() and user_form.is_valid():
            profile_form.save()
            user_form.save()
            context["profile_saved"] = True
    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=profile)
    context.update({"user_form": user_form, "profile_form": profile_form, "current": "account"})
    return render_response(request, "profile/profile.html", context)
Ejemplo n.º 10
0
def profile_update(request, username):
    '''
    Update profile of User.
    @param request:
    '''
    profile, created = Profile.objects.get_or_create(user = request.user)
    if created:
        active = Activity(user = request.user)
        active.save()

    if request.method == "POST":
        profile_form = ProfileForm(request.POST, request.FILES, instance = profile)
        if profile_form.is_valid():
            profile_form.save()
            return HttpResponseRedirect('/profile/' + username)
    else:        
        profile_form = ProfileForm(instance = profile)
            
    return render_to_response('profile/update_profile.html',
                              {"form": profile_form}, 
                              context_instance = RequestContext(request))
Ejemplo n.º 11
0
def profile_view(request, template_name='profile_form.html'):
    """
    Allow user to add personnal data to his profile
    if the profile is saved, a context variable profile_saved is set to True
    """
    profile = request.user.get_profile()
    context = {}
    if request.method == "POST":
        profile_form = ProfileForm(instance=profile, data=request.POST)
        user_form = UserForm(instance=request.user, data=request.POST)
        if profile_form.is_valid() and user_form.is_valid():
            profile_form.save()
            user_form.save()
            context['profile_saved'] = True
    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=profile)
    context.update({'user_form': user_form,
                    'profile_form': profile_form,
                    'current':'account'})
    return render_response(request, template_name, context)
Ejemplo n.º 12
0
def profile_edit(request, **kwargs):
    
    template_name = kwargs.get("template_name", "profile/profile_edit.html")
    
    if request.is_ajax():
        template_name = kwargs.get(
            "template_name_facebox",
            "profile/profile_edit_facebox.html"
        )
    
    profile = request.user.get_profile()
    
    if request.method == "POST":
        if request.POST.has_key('change_rep'):
            if not request.user.is_staff:
                return HttpRepsonse("Unauthorized")
            rep_form = RepForm(request.POST)
            if rep_form.is_valid():
                profile.reputation = rep_form.cleaned_data['base_rep']
                profile.save()
                return HttpResponseRedirect(reverse("profile_detail", args=[request.user.username]))
        else:
            if not request.user == profile.user:
                return HttpResponse("Unauthorized")
            profile_form = ProfileForm(request.POST, instance=profile)
            if profile_form.is_valid():
                profile = profile_form.save()
                return HttpResponseRedirect(reverse("profile_detail", args=[request.user.username]))

    else:
        profile_form = ProfileForm(instance=profile)
        rep_form = RepForm(initial={'base_rep': profile.reputation})
    
    return render_to_response(template_name, {
        "profile": profile,
        "profile_form": profile_form,
        "rep_form": rep_form,
        'tinymce': TINY_MCE_JS_LOCATION,
    }, context_instance=RequestContext(request))
Ejemplo n.º 13
0
def edit_profile(request):
    profile = request.profile
    if request.method == 'POST':
        form = ProfileForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            form.save()
            messages.info(request, MESSAGES['profile_saved'])
            return HttpResponseRedirect(reverse(my_profile))
    else:
        form = ProfileForm(instance=profile)
    return HttpResponseRedirect(reverse('my_profile'))
Ejemplo n.º 14
0
def change_email(request):
    u = request.GET.get('u')
    t = request.GET.get('t')

    from main.utils import hash_ten
    if not (u and t) or not (hash_ten(u) == t):
        raise Http404

    from django.contrib.auth.models import User
    user = User.objects.get(pk=u)

    p = user.get_profile()

    from profile.forms import ProfileForm
    form = ProfileForm(instance=p)

    return locals()
Ejemplo n.º 15
0
def update_profile(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=request.user.profile)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            return redirect('profile-home')
    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)
    return render(request, 'profile/profile.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })
Ejemplo n.º 16
0
def info_edit(request, user_id):
    workspace = request.user.profile.workspace
    user = Profile.objects.get(workspace=workspace, user=user_id)
    if request.method == 'POST':
        form = ProfileForm(workspace,
                           request.user,
                           request.POST,
                           instance=user)
        if form.is_valid():
            form.save()
    else:
        form = ProfileForm(workspace, request.user, instance=user)
    return render(
        request, 'dashboard/ajax_form.html', {
            'form':
            form,
            'form_action':
            reverse_lazy('user_info_edit', kwargs={'user_id': user_id})
        })
Ejemplo n.º 17
0
def edit_profile(request):
    initial_phones = [{
        'phone': nubmer
    } for nubmer in request.user.phones_m2m.values_list('phone_id', flat=True)]
    initial = {
        'is_realtor': bool(request.user.get_agency()),
        'is_developer': request.user.is_developer()
    }

    if request.method == 'POST' and 'profile_form' in request.POST:
        form = ProfileForm(request.POST,
                           request.FILES,
                           instance=request.user,
                           initial=initial)
        phones_formset = UserPhonesFormSet(request.POST,
                                           initial=initial_phones,
                                           prefix='phones',
                                           user=request.user)

        if form.is_valid() and phones_formset.is_valid():
            form.save()
            phones_formset.update_phones_m2m(request.user.phones_m2m)

            if 'is_realtor' in form.changed_data and form.cleaned_data[
                    'is_realtor']:
                request.user.create_agency()
            if 'is_developer' in form.changed_data and form.cleaned_data[
                    'is_developer']:
                request.user.create_developer()

            return HttpResponseRedirect(reverse(edit_profile))
    else:
        phones_formset = UserPhonesFormSet(initial=initial_phones,
                                           prefix='phones',
                                           user=request.user)
        form = ProfileForm(instance=request.user, initial=initial)

    leadgeneration = request.user.get_leadgeneration()
    if request.method == 'POST' and 'leadgeneration_form' in request.POST:
        leadgeneration_form = LeadGenerationForm(request.POST,
                                                 instance=leadgeneration)
        if leadgeneration_form.is_valid():
            leadgeneration = leadgeneration_form.save(commit=False)
            leadgeneration.user = request.user

            # Если застройщики Укрбуд, Киевгорстрой, Интегралбуд или Дарий Бендарчик
            # то мы им разрешаем показывать собственные телефоны, вместо наших
            if request.user.id in [129163, 128586, 128226, 147304]:
                leadgeneration.is_shown_users_phone = True

            leadgeneration.save()
            if 'next' in request.POST:
                return redirect(request.POST['next'])
    else:
        leadgeneration_form = LeadGenerationForm(instance=leadgeneration)

    # удаление привязки к соц. сетям
    if 'social_link_disconnect' in request.GET:
        request.user.social_auth.filter(
            pk=request.GET['social_link_disconnect']).delete()
        return redirect(edit_profile)

    enabled_social_auths = [
        {
            'key': 'vkontakte',
            'backend': 'vk-oauth2',
            'name': u'ВКонтакте'
        },
        {
            'key': 'facebook',
            'backend': 'facebook',
            'name': u'Facebook'
        },
        {
            'key': 'google',
            'backend': 'google-oauth2',
            'name': u'Google'
        },
        {
            'key': 'twitter',
            'backend': 'twitter',
            'name': u'Twitter'
        },
    ]

    title = _(u'Редактирование профиля')

    # Для риелтора (ограничение в шаблоне) с лидогенерацией дополнительно проверяем необходимость пополнения баланса
    money_to_activate_ad = 0
    if request.user.has_active_leadgeneration(
    ) and request.user.get_balance() < 10:
        money_to_activate_ad = int(200 - request.user.get_balance())

    return render(request, 'profile/edit_profile.jinja.html', locals())