def change_level(request): try: level = UserExperienceLevel.objects.get(user__id=request.user.id) initial = {'experience_level': level.experience_level} except UserExperienceLevel.DoesNotExist: level = None initial = {} if request.method == 'POST': form = ExperienceForm(request.POST, initial=initial) if form.is_valid(): data = form.cleaned_data if level: level.experience_level = data['experience_level'] else: level = UserExperienceLevel(experience_level=data['experience_level'], user=request.user) level.save() try: set_flair(level) message = 'Successfully set experience level to %s.' % level.experience_level success = True except urllib2.HTTPError: message = 'Whoops! There was an error setting your experience level. This usually happens when reddit\'s API is down. Try again later and if you continue to have problems, please contact the moderators.' success = False except RedditRateLimitingError: message = 'Whoops! There was an error setting your experience level. It appears that reddit\'s servers are not accepting requests at the moment. Please try again in a couple of minutes.' success = False if 'application/json' in request.META.get('HTTP_ACCEPT', ''): return HttpResponse(json.dumps({'success': success, 'message': message}), content_type='application/json') else: messages.success(request, message) if success: return HttpResponseRedirect('/profile/') else: form = ExperienceForm(initial=initial) return render(request, 'experiencelevel/edit.html', { 'current_level': level, 'experience_levels': ExperienceLevel.objects.all(), 'form': form, })
def test_set_flair(self): session = reddit.RedditSession(modhash='t0t0t0') def urlopen_mock(request): self.assert_(request.get_full_url() == 'http://www.reddit.com/api/flair') data = request.get_data() self.assert_('uh=t0t0t0' in data) self.assert_('r=homebrewing' in data) self.assert_('name=patrick' in data) self.assert_('css_class=advanced' in data) self.assert_(request.has_header('User-agent')) return MockResponse("") reddit.urllib2.urlopen = urlopen_mock reddit.set_flair(UserExperienceLevel(user=self.user, experience_level=ExperienceLevel.objects.get(pk=3)), session) self.assert_(session.has_been_used)