Exemple #1
0
def save_settings(request, cid):
    print 'update_settings request.method = %s' % request.method
    if request.method == 'POST':
        con = get_construct(request.user, cid)
        if not con:
            return JsonResponse({
                'errors': {
                    'all': "Construct with id '%s' not found",
                },
            } % cid, ERROR)
        form = SettingsForm(request.POST, instance=con.settings)
        if form.is_valid():
            form.save()
            con.reset()
            data = {}
            for key, value in form.cleaned_data.items():
                data[key] = str(value)
            return JsonResponse({
                'modified': con.last_modified(),
                'fields': data
            })
        return JsonResponse({
            'errors': form.errors,
        }, ERROR)
    raise Http404
Exemple #2
0
def cms_settings(request):
    # 1.默认User表里是没有avatar,所以用到了CMSUser表
    # 2.CMSUser表和User表建立了一对一
    # 3.我们先查找CMSUser里的用户id
    # 4.如果用户存在则存储avatar,否则新建该用户并储存
    if request.method == 'GET':
        return render(request, 'cms_settings.html')
    else:
        form = SettingsForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username', None)
            avatar = form.cleaned_data.get('avatar', None)
            # 存储username
            # user = User.objects.all().first()
            user = request.user
            user.username = username
            user.save()
            # 存储avatar
            cms_user = CmsUserModel.objects.filter(user__pk=user.pk)
            if cms_user:
                cms_user.avatar = avatar
            else:
                CmsUserModel(user=user, avatar=avatar)
            cms_user.save()
            return myjson.json_result()
        else:
            return render(request, 'cms_settings.html',
                          {'error': form.get_error()})
Exemple #3
0
def front_settings(request):
    if request.method == 'GET':
        return render(request, 'front_settings.html')
    else:
        form = SettingsForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username', None)
            realname = form.cleaned_data.get('realname', None)
            qq = form.cleaned_data.get('qq', None)
            avatar = form.cleaned_data.get('avatar', None)
            signature = form.cleaned_data.get('signature', None)
            gender = form.cleaned_data.get('gender', None)
            # 用户登录之后只要获取当前用户的信息,然后就可以直接传入数据
            user_model = request.user
            # 只有用户名是必填项,其他如果没有可以不填,所以需要判断,而性别是有默认选项
            user_model.username = username
            user_model.gender = gender
            if realname:
                user_model.realname = realname
            if qq:
                user_model.qq = qq
            if avatar:
                user_model.avatar = avatar
            if signature:
                user_model.signature = signature
            user_model.save()
            return myjson.json_result()
        else:
            return render(request, 'cms_reset_email.html',
                          {'error': form.get_error()})
Exemple #4
0
def user_settings(request):
    if request.method == 'POST':
        form = SettingsForm(request.POST, request.FILES)

        if form.is_valid():
            im = Image.open(request.FILES['profile_pic'])
            im = ImageOps.fit(im, (120, 120), Image.ANTIALIAS)

            if not os.path.exists(os.path.join(settings.MEDIA_ROOT, "profile")):
                os.makedirs(os.path.join(settings.MEDIA_ROOT, "profile"))

            im.save(os.path.join(settings.MEDIA_ROOT, "profile/{}.png".format(request.user.netid)))
            request.user.photo = "png"
            request.user.save()

            messages.success(request, 'Votre profil a été mis à jour.')

            return render(request, "users/settings.html", {'form': SettingsForm()})
    else:
        form = SettingsForm()

    return render(request, 'users/settings.html', {
        'form': form,
        'stream': actor_stream(request.user),
    })
Exemple #5
0
def settings_edit(request, response_format='html'):
    "Settings"

    if not request.user.profile.is_admin('anaf.services'):
        return user_denied(
            request,
            message=
            "You don't have administrator access to the Service Support module"
        )

    if request.POST:
        if 'cancel' not in request.POST:
            form = SettingsForm(request.user.profile, request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(reverse('services_settings_view'))
        else:
            return HttpResponseRedirect(reverse('services_settings_view'))
    else:
        form = SettingsForm(request.user.profile)

    context = _get_default_context(request)
    context.update({'form': form})

    return render_to_response('services/settings_edit',
                              context,
                              context_instance=RequestContext(request),
                              response_format=response_format)
Exemple #6
0
def settings_form( request, template = 'settings_form.html' ):
    context = {}
    user = request.user

    if request.method == 'POST':
        form = SettingsForm(request.POST.copy())
        if form.is_valid():
            # Cycle through the settings and save them
            data = form.cleaned_data
            for setting in USER_SETTINGS:
                name = setting['name']
                set_setting(user, name, data[name])
            context['saved'] = True
    else:
        # Read user settings and build the form
        settings = {}
        for setting in USER_SETTINGS:
            name = setting['name']
            settings[name] = get_setting(user, name)
        form = SettingsForm(settings)

    context['form'] = form

    return render_to_response(template,
        context, context_instance=RequestContext(request))
Exemple #7
0
def settings(request):
    if request.POST:
        settingsForm = SettingsForm(request.POST, instance=request.user)
        if settingsForm.is_valid():
            settingsForm.save()
            messages.info(request, 'User settings saved.')
            return redirect('dashboard')
    else:
        settingsForm = SettingsForm(instance=request.user)
    return render(request, 'settings.html', {'settingsForm': settingsForm})
Exemple #8
0
def settings(request):
    if request.method == "POST":
        form = SettingsForm(request.POST)
        if form.is_valid():
            request.user.topic_set = form.cleaned_data["topics"]
            return HttpResponseRedirect("/")
    else:
        form = SettingsForm()

    return render(request, "settings.html", {"form": form})
Exemple #9
0
def settings(request):
    if request.POST:
        settingsForm = SettingsForm(request.POST, instance=request.user)
        if settingsForm.is_valid():
            settingsForm.save()
            messages.info(request, 'User settings saved.')
            return redirect('dashboard')
    else:
        settingsForm = SettingsForm(instance=request.user)
    return render(request, 'settings.html', {'settingsForm': settingsForm})
Exemple #10
0
def settings(request, user_id):
    user = get_object_or_404(User, id=user_id)
    if request.user != user and not request.user.is_superuser:
        return HttpResponseForbidden("Forbidden operation.")
    form = SettingsForm(data=request.POST or None,
                        initial={"email": user.email, "intro": user.get_profile().intro})
    if request.method == "POST" and form.is_valid():
        form.save(user)
        return redirect(reverse("user_profile", kwargs={"user_id": user_id}))
    return render(request, "settings.html",
                  {"form": form, "settings_user": user})
Exemple #11
0
	def post(self):
		args = self.request.arguments()
		post_data = {}
		for arg in args:
			d = self.request.get(arg)
			post_data[arg] = d

		form = SettingsForm(post_data)
		if form.is_valid():
			form.save()

		self.get(form=form)
Exemple #12
0
def edit_settings(request):
    context = {}
    settings = Settings.get_by_user(request.user)

    if request.method == "POST":
        form = SettingsForm(request.POST, instance=settings)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/settings")
    else:
        form = SettingsForm(instance=settings)

    context["form"] = form
    return r2r(request, "edit_settings", context)
Exemple #13
0
def edit_settings(request):
    context = {}
    settings = Settings.get_by_user(request.user)

    if request.method == "POST":
        form = SettingsForm(request.POST, instance=settings)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/settings")
    else:
        form = SettingsForm(instance=settings)

    context["form"] = form
    return r2r(request, "edit_settings", context)
Exemple #14
0
def settings(request):
	if request.method == 'POST':
		form = SettingsForm(request.POST)
		if form.is_valid():
			try:
				Alert.objects.get(user=request.user).delete()
			except:
				pass

			data = form.cleaned_data

			client_t = data['user_time']
			server_t = datetime.now().strftime('%H')
			tz_diff = int(server_t) - int(client_t)
			as_time = datetime(2013, 1, 1, data['time'].hour, data['time'].minute)			
			as_time = as_time + timedelta(hours=tz_diff)

			a = Alert(
				user=request.user,
				alert_server_time=as_time,
				start=data['start'],
				finish=data['finish'],
				period=data['period'],
				time=data['time'],
				alert_email=data['alert_email'],
				email=data['email'],
				alert_sms=data['alert_sms'],
				phone=data['phone']
			)

			alert = {}

			try:
				a.save()
				alert['txt'] = 'Настройки сохранены'
				alert['cls'] = 'alert-success'
			except:
				alert['txt'] = 'Не удалось сохранить настройки, попробуйте повторить позже'
				alert['cls'] = 'alert-danger'

			return render_to_response('settings.html', {'form': form, 'alert': alert}, RequestContext(request))
	else:
		try:
			a = Alert.objects.get(user=request.user)
			form = SettingsForm(instance=a)
		except: 
			form = SettingsForm()

	return render_to_response('settings.html', {'form': form}, RequestContext(request))
Exemple #15
0
def settings(request, user_id):
    user = get_object_or_404(User, id=user_id)
    if request.user != user and not request.user.is_superuser:
        return HttpResponseForbidden("Forbidden operation.")
    form = SettingsForm(data=request.POST or None,
                        initial={
                            "email": user.email,
                            "intro": user.get_profile().intro
                        })
    if request.method == "POST" and form.is_valid():
        form.save(user)
        return redirect(reverse("user_profile", kwargs={"user_id": user_id}))
    return render(request, "settings.html", {
        "form": form,
        "settings_user": user
    })
Exemple #16
0
def settings_edit(request, response_format='html'):
    "Settings"

    if request.POST:
        form = SettingsForm(request.user.profile, request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('changes_settings_view'))
    else:
        form = SettingsForm(request.user.profile)

    context = _get_default_context(request)
    context.update({'form': form})

    return render_to_response('changes/settings_edit', context,
                              context_instance=RequestContext(request), response_format=response_format)
Exemple #17
0
def profile(request):
    if request.method == 'POST':
        form = SettingsForm(request.POST, request.FILES)
        if form.is_valid():
            if request.user.check_password(request.POST['old_pass']):
                if request.POST['username'] != '':
                    request.user.username = request.POST['username']
                if request.POST['email'] != '':
                    request.user.email = request.POST['email']
                if request.POST['pass_new'] != '':
                    request.user.password = request.POST['pass_new']
                    request.user.set_password(request.user.password)
                request.user.save()
                return home(request)
    form = SettingsForm()
    return render(request, 'external/profile.html', {'form': form})
Exemple #18
0
def settings(request):

    context_vars = {}
    context_vars.update(csrf(request))

    if request.method == 'POST':
        form = SettingsForm(request.POST, request.FILES, instance=request.user.profile)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('profile', kwargs={"username": request.user.username}))
    else:
        form = SettingsForm(instance=request.user.profile)

    context_vars.update({'form': form})
    template = 'settings.html'
    context = RequestContext(request)
    return render_to_response(template, context_vars, context_instance=context)
Exemple #19
0
def index(request):
    # Get course id from session
    try:
        courseid = request.session['LTI_LAUNCH']['custom_canvas_course_id']
    except:
        logger.error("Missing custom_canvas_course_id in LTI launch")
        raise Http404("Course ID not found")

    # Get content via API calls
    syllabus = fetch_syllabus(courseid)
    (dated, undated) = fetch_allevents(courseid)
    groups = fetch_assigngroups(courseid)

    # Check for initial load of page through presence of hidden field
    if 'hidden_field' in request.GET:
        form = SettingsForm(request.GET)
        if form.is_valid():
            settings = form.cleaned_data
    else:
        form = SettingsForm()
        settings = {
            'syllabus': True,
            'dated_events': True,
            'undated_events': False,
            'descriptions': False,
            'times': True,
            'weights': False,
            'hidden_field': "viewed"
        }

    # Populate events array based on toggled options
    events = []
    if settings['dated_events']:
        events += dated
    if settings['undated_events']:
        events += undated

    context = {
        'syllabus': syllabus,
        'events': events,
        'groups': groups,
        'form': form,
        'settings': settings
    }
    return render(request, 'syllabuspdf/index.html', context)
Exemple #20
0
def settings_edit(request, response_format='html'):
    "Settings"

    if request.POST:
        form = SettingsForm(request.user.profile, request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('changes_settings_view'))
    else:
        form = SettingsForm(request.user.profile)

    context = _get_default_context(request)
    context.update({'form': form})

    return render_to_response('changes/settings_edit',
                              context,
                              context_instance=RequestContext(request),
                              response_format=response_format)
Exemple #21
0
def settings(request):
    settings_form = SettingsForm()
    next = request.REQUEST.get('next')
    if request.method == 'POST':
        settings_form = SettingsForm(request.POST)
        if settings_form.is_valid():
            username = settings_form.save()
            request.session['username'] = username
            if next:
                return HttpResponseRedirect(next)
            return HttpResponseRedirect('/')

    context = {
        'settings_form': settings_form,
        'next': next,
    }
    return render_to_response('settings.html', context,
        context_instance=RequestContext(request))
Exemple #22
0
def settings_edit(request, response_format='html'):
    "Settings edit"

    if request.POST:
        if 'cancel' not in request.POST:
            form = SettingsForm(request.user.profile, request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(reverse('account_settings_view'))
        else:
            return HttpResponseRedirect(reverse('account_settings_view'))
    else:
        form = SettingsForm(request.user.profile)

    return render_to_response('account/settings_edit',
                              {'form': Markup(form.as_ul())},
                              context_instance=RequestContext(request),
                              response_format=response_format)
Exemple #23
0
def save_settings(request, cid):
	print 'update_settings request.method = %s' % request.method
	if request.method == 'POST':
		con = get_construct(request.user, cid)
		if not con:
			return JsonResponse({
				'errors': {
					'all':"Construct with id '%s' not found",
					},} % cid, ERROR)
		form = SettingsForm(request.POST, instance=con.settings)
		if form.is_valid():
			form.save()
			con.reset()
			data = {}
			for key,value in form.cleaned_data.items():
				data[key] = str(value);
			return JsonResponse({'modified': con.last_modified(), 'fields': data})
		return JsonResponse({'errors': form.errors,}, ERROR)
	raise Http404
Exemple #24
0
def settings(request):
    settings_form = SettingsForm()
    next = request.REQUEST.get('next')
    if request.method == 'POST':
        settings_form = SettingsForm(request.POST)
        if settings_form.is_valid():
            username = settings_form.save()
            request.session['username'] = username
            if next:
                return HttpResponseRedirect(next)
            return HttpResponseRedirect('/')

    context = {
        'settings_form': settings_form,
        'next': next,
    }
    return render_to_response('settings.html',
                              context,
                              context_instance=RequestContext(request))
Exemple #25
0
def update_settings(request):
	if request.method == 'POST':
		form = SettingsForm(request.POST)
		
		if form.is_valid():
			show_on_rankings = form.cleaned_data['show_on_rankings']
			
			user = UserProfile.objects.get(user = request.user)
			if show_on_rankings:
				user.show_on_rankings = True
			else:
				user.show_on_rankings = False
			
			user.save()
			
			messages.add_message(request, messages.SUCCESS, 'Your profile has been successfully updated.')
		else:
			messages.add_message(request, messages.ERROR, message = 'Error occured when trying to update your settings.')
		
	return render_to_response('other/message.html', {}, context_instance = RequestContext(request))
Exemple #26
0
def settings_edit(request, response_format='html'):
    "Settings edit"

    if request.POST:
        if 'cancel' not in request.POST:
            form = SettingsForm(
                request.user.profile, request.POST, request.FILES)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(reverse('core_settings_view'))
        else:
            return HttpResponseRedirect(reverse('core_settings_view'))

    else:
        form = SettingsForm(request.user.profile)

    return render_to_response('core/administration/settings_edit',
                              {
                                  'form': form,
                              },
                              context_instance=RequestContext(request), response_format=response_format)
def index(request):
	# Get course id from session
	try:
		courseid = request.session['LTI_LAUNCH']['custom_canvas_course_id']
	except:
		logger.error("Missing custom_canvas_course_id in LTI launch")
		raise Http404("Course ID not found")

	# Get content via API calls
	syllabus = fetch_syllabus(courseid)
	(dated, undated) = fetch_allevents(courseid)
	groups = fetch_assigngroups(courseid)

	# Check for initial load of page through presence of hidden field
	if 'hidden_field' in request.GET:
		form = SettingsForm(request.GET)
		if form.is_valid():
			settings = form.cleaned_data
	else:
		form = SettingsForm()
		settings = {
			'syllabus':True,
			'dated_events':True,
			'undated_events':False,
			'descriptions':False,
			'times':True,
			'weights':False,
			'hidden_field':"viewed"
		}

	# Populate events array based on toggled options
	events = []
	if settings['dated_events']:
		events += dated
	if settings['undated_events']:
		events += undated

	context = {'syllabus': syllabus, 'events': events, 'groups': groups, 'form': form, 'settings': settings}
	return render(request,'syllabuspdf/index.html', context)
Exemple #28
0
def cms_settings(request):
    config = None
    message = get_messages(request)
    config = lookup_settings(request)
    
    if request.method == 'POST':
        form = SettingsForm(request.POST)
        if form.is_valid():
            email = request.user.email
            delete_settings(email=email)
            config = form.save()
            config.email = request.user.email
            config.save()
            message = "Settings saved."
            request.session['cms_email'] = config.email
            return HttpResponseRedirect(settings.ROOT_URL+'options/')
    else:
        form = SettingsForm(instance=config)
    
    
    return direct_to_template(request, 'settings.html', 
        {'config': config, 'message': message, 'form': form, })
Exemple #29
0
def settings(request):
    # if user is not logged in raise 404
    if not request.session.has_key("user_id"): raise Http404
    user_id = request.session["user_id"]
    user_data = redis_ob.hgetall("user:%s" %user_id)
    if not user_data: raise Http404
    if request.method == "POST":
        form = SettingsForm(request.POST)
        if form.is_valid():
            user_email = redis_ob.hget("user:%s" %user_id, "email")
            redis_pipe = redis_ob.pipeline()
            if user_email != form.cleaned_data['email']:
                if redis_ob.exists("user:email:%s" %md5_constructor(form.cleaned_data['email']).hexdigest()):
                    message = "Another account is already associated with that email"
                    return render_to_response('settings.html', {'form': form, 'user_data': user_data, 'message': message}, context_instance=RequestContext(request))
                redis_pipe.rename("user:email:%s" %md5_constructor(user_email).hexdigest(), "user:email:%s" %md5_constructor(form.cleaned_data['email']).hexdigest()).hset("user:%s" %user_id, "email", form.cleaned_data['email'])
            salt, hsh = generate_password(form.cleaned_data['password'])
            if form.cleaned_data['custom_domain']:
                custom_domain = form.cleaned_data['custom_domain']
                if not custom_domain.startswith('http'): custom_domain = "http://"+custom_domain
                if not custom_domain.endswith('/'): custom_domain = custom_domain+"/"
                redis_pipe.hset("user:%s" %user_id, "custom_domain", custom_domain)
            redis_pipe.hset("user:%s" %user_id, "password", "%s$%s" %(salt, hsh))
            redis_pipe.execute()
            messages.add_message(request, messages.INFO, 'Your account settings are updated!')
            return HttpResponseRedirect("/")
    elif request.method =="DELETE":
        # delete user related data from redis
        user_data = redis_ob.hgetall("user:%s" %user_id)
        url_ids = redis_ob.lrange("user:urls:%s" %str(user_id), 0, -1)
        redis_ob.delete("user:email:%s" %md5_constructor(user_data.get("email")).hexdigest(), "user:%s" %user_id, "user:urls:%s" %user_id, "user:api_key:%s" %user_data.get("api_key"))
        
        # logout the user
        request.session.flush()
        return HttpResponse("success", mimetype="application/javascript")
    else:
        form = SettingsForm(initial={'email': user_data.get("email")})
    return render_to_response('settings.html', {'form': form, 'user_data': user_data}, context_instance=RequestContext(request))
Exemple #30
0
def settings_edit(request, response_format='html'):
    "Settings"

    if not request.user.profile.is_admin('anaf.services'):
        return user_denied(request,
                           message="You don't have administrator access to the Service Support module")

    if request.POST:
        if 'cancel' not in request.POST:
            form = SettingsForm(request.user.profile, request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(reverse('services_settings_view'))
        else:
            return HttpResponseRedirect(reverse('services_settings_view'))
    else:
        form = SettingsForm(request.user.profile)

    context = _get_default_context(request)
    context.update({'form': form})

    return render_to_response('services/settings_edit', context,
                              context_instance=RequestContext(request), response_format=response_format)
Exemple #31
0
def site_settings(request, template_name="account/settings.html"):
    if request.method == "POST":

        form = SettingsForm(request.POST)
        form.user = request.user

        if form.is_valid():
            request.user.cc_messages_to_email = form.cleaned_data["cc_email"]
            request.user.email_address = form.cleaned_data["email"]
            request.user.first_name = form.cleaned_data["first_name"]
            request.user.last_name = form.cleaned_data["last_name"]
            request.user.save()
            request.user.message_set.create(message=_("""Your settings were successfully updated.""") % {})
    else:
        form = SettingsForm(
            initial={
                "email": request.user.email_address,
                "cc_email": request.user.cc_messages_to_email,
                "first_name": request.user.first_name,
                "last_name": request.user.last_name,
            }
        )
    return render_to_response(template_name, {"form": form}, context_instance=RequestContext(request))
Exemple #32
0
def user_settings(request):
    if request.method == 'POST':
        form = SettingsForm(request.POST, request.FILES)

        if form.is_valid():
            im = Image.open(request.FILES['profile_pic'])
            im = ImageOps.fit(im, (120, 120), Image.ANTIALIAS)
            if not os.path.exists(os.path.join(settings.MEDIA_ROOT,
                                               "profile")):
                os.makedirs(os.path.join(settings.MEDIA_ROOT, "profile"))
            im.save(
                os.path.join(settings.MEDIA_ROOT,
                             "profile/{}.png".format(request.user.netid)))
            request.user.photo = "png"
            request.user.save()
            messages.success(request, 'Votre profil a été mis à jour.')
            return render(request, "settings.html", {'form': SettingsForm()})

    else:
        form = SettingsForm()

    return render(request, 'settings.html', {
        'form': form,
    })
Exemple #33
0
def site_settings(request, template_name='account/settings.html'):
    if request.method == 'POST':

        form = SettingsForm(request.POST)
        form.user = request.user

        if form.is_valid():
            request.user.cc_messages_to_email = form.cleaned_data['cc_email']
            request.user.email_address = form.cleaned_data['email']
            request.user.first_name = form.cleaned_data['first_name']
            request.user.last_name = form.cleaned_data['last_name']
            request.user.save()
            request.user.message_set.create(
                message=_("""Your settings were successfully updated.""") % {})
    else:
        form = SettingsForm(
            initial={
                'email': request.user.email_address,
                'cc_email': request.user.cc_messages_to_email,
                'first_name': request.user.first_name,
                'last_name': request.user.last_name,
            })
    return render_to_response(template_name, {'form': form},
                              context_instance=RequestContext(request))
Exemple #34
0
def render_settings(request):
    user = User.objects.get(pk=request.user.id)
    delete_account_request = False
    try:
        delete_request = DeleteAccountRequest.objects.filter(user=user).first()
        if delete_request:
            delete_account_request = True
    except ObjectDoesNotExist:
        delete_account_request = False
    try:
        settings = UserProfile.objects.get(user=user)
        user_groups = user.groups.all()
        group_list = []
        for g in user_groups:
            group_list.append({
                'id': g.id,
                'name': g.name,
                'receive_updates': settings.get_group_notification_preference(g.id)
            })
    except UserProfile.DoesNotExist:
        settings = None
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=user)
        if settings:
            settings_form = SettingsForm(request.POST, instance=settings)
        else:
            settings_form = SettingsForm(request.POST)
        if user_form.is_valid() and settings_form.is_valid():
            user = user_form.save()
            settings = settings_form.save(commit=False)
            settings.user_id = request.user.id
            settings.save()
            settings_form.save_m2m()
            # update the interface language
            if settings.interface_lang:
                translation.activate(settings.interface_lang)
                request.LANGUAGE_CODE = translation.get_language()

            # get group update settings
            for g in group_list:
                gets_notif = True if request.POST.get('group_notif_' + str(g.get('id'))) else False
                settings.set_group_notification_preference(g.get('id'), gets_notif)
                g['receive_updates'] = gets_notif

            # check for delete account requests
            if request.POST.get('delete_account_option') == 'delete':
                DeleteAccountRequest.objects.create(user=user)
                delete_account_request = True
                settings.set_active(False)
                ctx = {
                    "user": user,
                }
                html = render_to_string('emails/delete_account_request.html', ctx)
                email = EmailMessage('Delete user account request',
                                     html,
                                     constance.config.NO_REPLY_EMAIL,
                                     [config.ACTIVATE_USER_EMAIL])
                email.content_subtype = "html"
                email.send()
            else:
                if delete_account_request:
                    DeleteAccountRequest.objects.filter(user=user).delete()
                    delete_account_request = False
                    settings.set_active(True)
            messages.add_message(request, messages.SUCCESS, 'Profile Update Successful.')
    else:
        user_form = UserForm(instance=request.user)
        settings_form = SettingsForm(instance=settings)

    errors = dict(user_form.errors)
    errors.update(settings_form.errors)

    interest_types = {'languages': [(lang.id, lang.name) for lang in Language.objects.all()],
                      'interests': [(interest.id, interest.name) for interest in Interest.objects.all()],
                      'regions': [(region.id, region.name) for region in Region.objects.all()]}

    return render_to_response('users/user_settings_v2.html',
                              {
                                'settings_form': settings_form,
                                'user_form': user_form,
                                'group_list': group_list,
                                'interest_types': interest_types,
                                'has_password': user.has_usable_password(),
                                'errors': errors,
                                'delete_account_request': delete_account_request,
                              },
                              context_instance=RequestContext(request))
Exemple #35
0
def settings(request):
    did_post_pun = ""
    did_save_details = False
    user = request.user
    profile = UserProfile.objects.get(user=user)
    new_pun_form = PunForm()
    if request.method == "POST":
        if request.POST.get("puntext"):  # if this a post with a new pun
            new_pun_form, did_post_pun = process_pun_form(request)
        else:
            form = SettingsForm(request.POST)
            tt = form["title"]
            if form.is_valid():
                if "picture" in request.FILES:
                    profile.picture = request.FILES["picture"]  # check if the user actually uploaded a file
                user.first_name = form.cleaned_data["firstname"]
                user.last_name = form.cleaned_data["lastname"]
                user.email = form.cleaned_data["email"]
                profile.selected_title = Title.objects.get(title=form.cleaned_data["title"])
                profile.show_nsfw = form.cleaned_data["show_nsfw"]
                profile.save()
                user.save()
                did_save_details = True
    context_dict = {"new_pun_form": new_pun_form, "search_form": SearchForm()}
    settings_form = SettingsForm(
        initial={
            "username": user.username,
            "email": user.email,
            "firstname": user.first_name,
            "lastname": user.last_name,
            "title": profile.selected_title,
            "show_nsfw": profile.show_nsfw,
        },
        user=user,
    )
    settings_form.fields["username"].widget.attrs[
        "readonly"
    ] = True  # although an html/javascript wizard could override this, we're not atually storing any data anyhow
    user_attr = get_user_title_attributes(user)
    # checking what titles this user meets requirements for
    settings_form.fields["title"].choices = [
        (t.title, t.title)
        for t in Title.objects.filter(
            min_number_days__lte=user_attr["time_in_days"].days,
            min_score__lte=user_attr["score"],
            min_number_posts__lte=user_attr["posts_num"],
        )
    ]
    context_dict["settings_form"] = settings_form
    context_dict["user"] = user
    context_dict["user_profile"] = profile

    response = render(request, "punny/user-settings.html", context_dict)
    if did_post_pun is True:
        response.set_cookie("success", "pun posted!", max_age=3)
    elif did_post_pun is False:
        response.set_cookie("failed", "post failed", max_age=3)
    if did_save_details:
        response.set_cookie("saved", "profile saved!", max_age=2)
    if (
        user.last_login - user.date_joined
    ).seconds < 60:  # user registered less than sixty seconds ago. Display message for help
        response.set_cookie("virgin", "this is a first time user", max_age=4)

    return response
Exemple #36
0
def render_settings(request):
    user = User.objects.get(pk=request.user.id)
    delete_account_request = False
    try:
        delete_request = DeleteAccountRequest.objects.filter(user=user).first()
        if delete_request:
            delete_account_request = True
    except ObjectDoesNotExist:
        delete_account_request = False
    try:
        settings = UserProfile.objects.get(user=user)
        user_groups = user.groups.all()
        group_list = []
        for g in user_groups:
            group_list.append({
                'id':
                g.id,
                'name':
                g.name,
                'receive_updates':
                settings.get_group_notification_preference(g.id)
            })
    except UserProfile.DoesNotExist:
        settings = None
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=user)
        if settings:
            settings_form = SettingsForm(request.POST, instance=settings)
        else:
            settings_form = SettingsForm(request.POST)
        if user_form.is_valid() and settings_form.is_valid():
            user = user_form.save()
            settings = settings_form.save(commit=False)
            settings.user_id = request.user.id
            settings.save()
            settings_form.save_m2m()
            # update the interface language
            if settings.interface_lang:
                translation.activate(settings.interface_lang)
                request.LANGUAGE_CODE = translation.get_language()

            # get group update settings
            for g in group_list:
                gets_notif = True if request.POST.get(
                    'group_notif_' + str(g.get('id'))) else False
                settings.set_group_notification_preference(
                    g.get('id'), gets_notif)
                g['receive_updates'] = gets_notif

            # check for delete account requests
            if request.POST.get('delete_account_option') == 'delete':
                DeleteAccountRequest.objects.create(user=user)
                delete_account_request = True
                settings.set_active(False)
                ctx = {
                    "user": user,
                }
                html = render_to_string('emails/delete_account_request.html',
                                        ctx)
                email = EmailMessage('Delete user account request', html,
                                     constance.config.NO_REPLY_EMAIL,
                                     [config.ACTIVATE_USER_EMAIL])
                email.content_subtype = "html"
                email.send()
            else:
                if delete_account_request:
                    DeleteAccountRequest.objects.filter(user=user).delete()
                    delete_account_request = False
                    settings.set_active(True)
            messages.add_message(request, messages.SUCCESS,
                                 'Profile Update Successful.')
    else:
        user_form = UserForm(instance=request.user)
        settings_form = SettingsForm(instance=settings)

    errors = dict(user_form.errors)
    errors.update(settings_form.errors)

    interest_types = {
        'languages': [(lang.id, lang.name) for lang in Language.objects.all()],
        'interests':
        [(interest.id, interest.name) for interest in Interest.objects.all()],
        'regions':
        [(region.id, region.name) for region in Region.objects.all()]
    }

    return render_to_response('users/user_settings_v2.html', {
        'settings_form': settings_form,
        'user_form': user_form,
        'group_list': group_list,
        'interest_types': interest_types,
        'has_password': user.has_usable_password(),
        'errors': errors,
        'delete_account_request': delete_account_request,
    },
                              context_instance=RequestContext(request))