def get(self, request, pk=None): """ Return creation or edition form if pk is provided """ if pk is None: default_data = { 'app_page_type': CTA().get_for_names("page_text", "pageapp_text") } if 'parent' in request.GET and request.GET['parent'] != '0': default_data['parent'] = request.GET['parent'] form = PageWAForm(initial=default_data) html = render_to_string('administration/page/page-create.html', { 'form': form, }, context_instance=RequestContext(request)) response = Response(status.HTTP_200_OK, {"html": html}) return self.render(response) else: page = get_object_or_404(request.website.pages, pk=pk) form = PageWAForm(instance=page) html = render_to_string('administration/page/page-edit.html', { 'form': form, 'page': page }, context_instance=RequestContext(request)) response = Response(status.HTTP_200_OK, {"html": html}) return self.render(response)
def post(self, request, contact_id): ################# # Setup ################# headers = { "Content-Type": "application/json", "Allow": "", } ################# # Validation ################# try: account_id = int(request.session["_auth_user_id"]) except KeyError: return Response(status=status.HTTP_401_UNAUTHORIZED) try: account = Account.objects.get(user_id=account_id) except Account.DoesNotExist: return Response(status=status.HTTP_401_UNAUTHORIZED) if account.type is not 'administrator': return Response(status=status.HTTP_401_UNAUTHORIZED) errors = { "header_request_method": "This endpoint only supports GET, PUT and DELETE requests." } return Response(content=errors, headers=headers, status=status.HTTP_405_METHOD_NOT_ALLOWED)
def put(self, request, pk=None): post_values = self.DATA.copy() post_values['website'] = request.website.id form = PageWAForm(post_values) if form.is_valid(): page = form.save() # Add the new page on auto_display PluginRelation plugins_relation = PluginRelation.objects.filter( display_on_new_pages=True, pages__website=request.website) for plugin_relation in plugins_relation: plugin_relation.pages.add(page) response = Response( status.HTTP_202_ACCEPTED, { "msg": MESSAGES.get('redirection', ""), 'location': page.get_absolute_url() }) else: content = render_to_string( 'administration/page/page-create.html', { 'form': form, }, context_instance=RequestContext(request)) response = Response(status.HTTP_400_BAD_REQUEST, { "html": content, "msg": MESSAGES.get('default_error', "") }) return self.render(response)
def delete(self, request, pk): page = get_object_or_404(request.website.pages, pk=pk) url_home_page = request.website.get_url_home_page() # We can't delete the home page if page.get_absolute_url() == url_home_page: response = Response( status.HTTP_400_BAD_REQUEST, {"msg": MESSAGES.get('delete_home_page_error', "")}) return self.render(response) # Need redirection if page is currently displayed if request.page == page: redirection = True else: redirection = False # Deleting page page.delete() # Make response if redirection: response = Response(status.HTTP_202_ACCEPTED, {'location': url_home_page}) else: # Refresh Menu navigation: navigation_html = RenderingContext(request).html_navigation response = Response( status.HTTP_200_OK, { "id": pk, "navigation_html": navigation_html, "msg": MESSAGES.get('page_delete_success', "") }) # Send response return self.render(response)
def post(self, request, test_id): try: test = Test.objects.get(id=test_id) except ObjectDoesNotExist: return Response(status.HTTP_404_NOT_FOUND) if request.user == test.teacher: if self.CONTENT["answer_id"].test != test: return Response( status.HTTP_400_BAD_REQUEST, "This answer isn't associated with the current test.") try: checkedAnswer = CheckedAnswers.objects.create( **{ "answer": self.CONTENT["answer_id"], "list": self.CONTENT["list"], "note": self.CONTENT["note"], }) except IntegrityError: return Response(status.HTTP_400_BAD_REQUEST, "These answers have already been checked.") else: return reverse("test_checked_answer", kwargs={ "test_id": test_id, "answer_id": checkedAnswer.answer.student.id }) else: return Response(status.HTTP_401_UNAUTHORIZED)
def get(self, request, test_id, answer_id): try: checkedAnswer = CheckedAnswers.objects.get( answer__student=answer_id) except ObjectDoesNotExist: return Response(status.HTTP_404_NOT_FOUND) if request.user in (checkedAnswer.answer.student, checkedAnswer.answer.test.teacher): return { "list": checkedAnswer.list, "note": checkedAnswer.note, "answer": reverse("test_answer", kwargs={ "test_id": test_id, "student_id": answer_id }), "url": reverse("test_checked_answer", kwargs={ "test_id": test_id, "answer_id": answer_id }), } else: return Response(status.HTTP_401_UNAUTHORIZED)
def post(self, request, account_id): ################# # Setup ################# headers = { "Content-Type": "application/json", "Allow": "GET, PUT, DELETE", } ################# # Validation ################# try: request.session["_auth_user_id"] except KeyError: return Response(status=status.HTTP_401_UNAUTHORIZED) errors = { "header_request_method": "This endpoint only supports GET, PUT and DELETE requests." } return Response(content=errors, headers=headers, status=status.HTTP_405_METHOD_NOT_ALLOWED)
def delete(self, request): ################# # Setup ################# headers = { "Content-Type": "application/json", "Allow": "POST", } try: request.session["_auth_user_id"] except KeyError: return Response(status=status.HTTP_401_UNAUTHORIZED) ################# # Validation ################# errors = { "header_request_method": "This endpoint only supports POST requests." } return Response(content=errors, headers=headers, status=status.HTTP_405_METHOD_NOT_ALLOWED)
def dispatch(self, request, *args, **kwargs): self.request = request self.args = args self.kwargs = kwargs self.headers = {} try: self.initial(request, *args, **kwargs) # Authenticate and check request has the relevant permissions self._check_permissions() # Get the appropriate handler method if self.method.lower() in self.http_method_names: handler = getattr(self, self.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed response_obj = handler(request, *args, **kwargs) # Allow return value to be either HttpResponse, Response, or an object, or None if isinstance(response_obj, HttpResponse): return response_obj elif isinstance(response_obj, Response): response = response_obj elif response_obj is not None: response = Response(status.HTTP_200_OK, response_obj) else: response = Response(status.HTTP_204_NO_CONTENT) # Pre-serialize filtering (eg filter complex objects into natively serializable types) response.cleaned_content = self.filter_response(response.raw_content) except ErrorResponse, exc: response = exc.response
def get(self, request, test_id): try: test = Test.objects.get(id=test_id) except ObjectDoesNotExist: return Response(status.HTTP_404_NOT_FOUND) result = { "id": test.id, "teacher": reverse("user", kwargs={"id": test.teacher.id}), "url": reverse("test", kwargs={"test_id": test_id}), "students": reverse("test_students", kwargs={"test_id": test_id}), "groups": reverse("test_groups", kwargs={"test_id": test_id}), "answers": reverse("test_answers", kwargs={"test_id": test_id}), "checked_answers": reverse("test_checked_answers", kwargs={"test_id": test_id}), } if request.user == test.teacher: result["list"] = test.list return result elif request.user.has_perm('do_test', test): result["list"] = self._strip_answers(test.list) return result else: return Response(status.HTTP_401_UNAUTHORIZED)
def post(self, request): """ Handle POST requests, managing the user authentication. """ try: user = User.objects.get(email=request.POST['email']) user = authenticate(username=user.username, password=request.POST['password']) if user is not None: if user.is_active: login(request, user) response = Response(status.HTTP_200_OK, {"msg": MESSAGES.get('user_authenticated', "")}) else: response = Response(status.HTTP_400_BAD_REQUEST, {"msg": MESSAGES.get('inactive_user', "")}) else: response = Response(status.HTTP_400_BAD_REQUEST, {"msg": MESSAGES.get('bad_login_pwd', "")}) except User.DoesNotExist: response = Response(status.HTTP_400_BAD_REQUEST, {"msg": MESSAGES.get('bad_login_pwd', "")}) return self.render(response)
def post(self, request, pk): domain = get_object_or_404(request.website.ndds, pk=pk) if 'primary' in request.POST: request.website.domain = domain request.website.save() response = Response( status.HTTP_202_ACCEPTED, { 'location': 'http://%s%s#admin' % (domain.domain, request.page.get_absolute_url()) }) else: form = DomainWAForm(request.POST, instance=domain) if form.is_valid(): form.save() response = Response( status.HTTP_200_OK, {'msg': MESSAGES.get('item_edit_success', "")}) else: html = render_to_string( 'administration/website/domain.html', { 'form': form, 'edit': True }, context_instance=RequestContext(request)) response = Response(status.HTTP_400_BAD_REQUEST, { "html": html, 'msg': MESSAGES.get('default_error', "") }) return self.render(response)
def delete(self, request, id): if role(request) == "admin": try: User.objects.get(id=id).delete() except ObjectDoesNotExist: return Response(status.HTTP_404_NOT_FOUND) else: return reverse("users") else: return Response(status.HTTP_401_UNAUTHORIZED)
def delete(self, request, group_id): try: group = Group.objects.get(id=group_id) except ObjectDoesNotExist: return Response(status.HTTP_404_NOT_FOUND) if role(request) == "admin": group.delete() return reverse("groups") else: return Response(status.HTTP_401_UNAUTHORIZED)
def delete(self, request, test_id): try: test = Test.objects.get(id=test_id) except ObjectDoesNotExist: return Response(status.HTTP_404_NOT_FOUND) if request.user == test.teacher: test.delete() return reverse("tests") else: return Response(status.HTTP_401_UNAUTHORIZED)
def post(self, request): if role(request) == "admin": try: group = Group.objects.create(name=self.CONTENT["name"]) except IntegrityError: return Response(HTTP_400_BAD_REQUEST, "Group name already in use.") return reverse("group", kwargs={"group_id": group.id}) else: return Response(status.HTTP_401_UNAUTHORIZED)
def delete(self, request, test_id, answer_id): try: checkedAnswer = CheckedAnswers.objects.get( answer__student=answer_id) except ObjectDoesNotExist: return Response(status.HTTP_404_NOT_FOUND) if checkedAnswer.answer.test.teacher == request.user: checkedAnswer.delete() return reverse("test_checked_answers", kwargs={"test_id": test_id}) else: return Response(status.HTTP_401_UNAUTHORIZED)
def put(self, request): ################# # Setup ################# headers = { "Content-Type": "application/json", "Allow": "GET, POST", } # Check content-type header if not self.content_type.startswith('application/json'): errors = { "header_content_type": "Content-Type must be 'application/json'. Your Content-Type is " + str(self.content_type) } return Response(content=errors, headers=headers, status=status.HTTP_400_BAD_REQUEST) try: action = self.CONTENT['action'] except KeyError: error = {"action": "Missing action."} return Response(content=error, headers=headers, status=status.HTTP_400_BAD_REQUEST) ################# # Validation ################# # Request to reset user's password if action == 'request_password_reset': try: email = self.CONTENT['email'] except KeyError: error = {"email": "Missing email address."} return Response(content=error, headers=headers, status=status.HTTP_400_BAD_REQUEST) result = Account.request_reset_password(email) else: result = {"action": "Invalid action."} if isinstance(result, dict): return Response(content=result, headers=headers, status=status.HTTP_400_BAD_REQUEST) return Response(content={}, headers=headers, status=status.HTTP_200_OK)
def post(self, request, poll_id): poll = get_object_or_404(Poll.objects.all(), pk=poll_id) form = PollForm(request.POST, instance=poll) if form.is_valid(): form.save() else: return Response(content=form.errors, status=400) return Response( status=303, headers={'Location': reverse('polls_api_results', args=[poll_id])})
def delete(self, request, pk): domain = get_object_or_404(request.website.ndds, pk=pk) # You cannot delete the primary domain if request.website.domain == domain: response = Response(status.HTTP_400_BAD_REQUEST, {'msg': MESSAGES.get('default_error', "")}) else: domain.delete() response = Response( status.HTTP_200_OK, {"msg": MESSAGES.get('item_delete_success', "")}) # Send response return self.render(response)
def get(self, request): key = request.GET.get('api_key', None) account_id = -1 if key: userprofile = None try: userprofile = UserProfile.objects.get(api_key=key) account_id = userprofile.user_id except: pass if userprofile: user = None try: user = User.objects.get(pk=account_id) except: pass if user: if is_allowed(user): videos = Video.objects.filter( uploader__id=account_id).order_by('-created')[:1:] json_videos = [] for video in videos: channel_name = None if video.channel: channel_name = video.channel.name json_videos.append({ 'id': video.id, 'channel': channel_name, 'url': video.get_absolute_url(), 'title': video.title, 'embed_code': video.get_embed_code() }) response = Response(200, { 'success': True, 'videos': json_videos }) else: response = Response(401) else: response = Response(401) else: response = Response(401) else: response = Response(400) return self.render(response)
def delete(self, request, group_id, student_id): try: group = Group.objects.get(id=group_id) except ObjectDoesNotExist: return Response(status.HTTP_404_NOT_FOUND) try: user = User.objects.get(id=student_id) except ObjectDoesNotExist: return Response(status.HTTP_404_NOT_FOUND) if role(request) == "admin": user.groups.remove(group) return reverse("group", kwargs={"group_id": group_id}) else: return Response(status.HTTP_401_UNAUTHORIZED)
def delete(self, request, test_id, student_id): try: test = Test.objects.get(id=test_id) except ObjectDoesNotExist: return Response(status.HTTP_404_NOT_FOUND) if test.teacher == request.user: try: student = User.objects.get(id=student_id) except ObjectDoesNotExist: return Response(status.HTTP_404_NOT_FOUND) remove_perm('do_test', student, test) return reverse("test_students", kwargs={"test_id": test_id}) else: return Response(status.HTTP_401_UNAUTHORIZED)
def post(self, request, test_id): try: test = Test.objects.get(id=test_id) except ObjectDoesNotExist: return Response(status.HTTP_404_NOT_FOUND) if test.teacher == request.user: student = self.CONTENT["student_id"] assign('do_test', student, test) return reverse("test_student", kwargs={ "test_id": test_id, "student_id": student.id }) else: return Response(status.HTTP_401_UNAUTHORIZED)
def post(self, request, *args, **kwargs): model = self.resource.model # Copy the dict to keep self.CONTENT intact content = dict(self.CONTENT) m2m_data = {} for field in model._meta.many_to_many: if field.name in content: m2m_data[field.name] = (field.m2m_reverse_field_name(), content[field.name]) del content[field.name] instance = model( **self.get_instance_data(model, content, *args, **kwargs)) instance.save() for fieldname in m2m_data: manager = getattr(instance, fieldname) if hasattr(manager, 'add'): manager.add(*m2m_data[fieldname][1]) else: data = {} data[manager.source_field_name] = instance for related_item in m2m_data[fieldname][1]: data[m2m_data[fieldname][0]] = related_item manager.through(**data).save() headers = {} if hasattr(instance, 'get_absolute_url'): headers['Location'] = self.resource(self).url(instance) return Response(status.HTTP_201_CREATED, instance, headers)
def render_to_response_with_refresh(self, relation_id, app_obj, msg=None): id_items = check_object_html_id(relation_id, types=[settings.SLUG_PLUGIN, settings.SLUG_APP]) # APP rendering if id_items[0] == settings.SLUG_APP: # Get placeholder slug in page placeholder_slug = app_obj.page.get().placeholder_slug # Plugin Rendering else: # Get placeholder_slug in relation placeholder_slug = app_obj.pages.get(pages=self.request.page).placeholder_slug placeholder_slug_items = check_placeholder_html_id(placeholder_slug) layout_section_slug = placeholder_slug_items[0] placeholder_id = placeholder_slug_items[2] rendering_context = RenderingContext(self.request) html = rendering_context.get_html_placeholder(layout_section_slug, placeholder_id, context=RequestContext(self.request)) datas = {'html': html, 'placeholder_slug': placeholder_slug} if msg: datas['msg'] = msg response = Response(status.HTTP_200_OK, datas) return self.render(response)
def post(self, request, relation_id, plugin, action_pk=None): links_html_id = request.POST.getlist('links_id[]') if links_html_id: # New ordering items order = 1 for link_id in map(lambda s: s.split('-')[1], links_html_id): try: obj = Link.objects.get(pk=link_id) if obj.plugin == plugin: obj.order = order obj.save() order += 1 except Link.DoesNotExist: pass # Rendering new content html = request.page.render_page(request).content if isinstance(html, HTMLRendering): html = html.content response = Response( status.HTTP_200_OK, { 'msg': MESSAGES.get('items_edit_success', ""), 'html': html, 'placeholder_type': placeholder_type, 'html_id': relation_id }) return self.render(response) else: raise ErrorResponse(status.HTTP_400_BAD_REQUEST, {'msg': MESSAGES.get('default_error', "")})
def post(self, request, group_id): try: group = Group.objects.get(id=group_id) except ObjectDoesNotExist: return Response(status.HTTP_404_NOT_FOUND) student = self.CONTENT["student_id"] if role(request) == "admin": student.groups.add(group) return reverse("group_member", kwargs={ "group_id": group_id, "student_id": student.id }) else: return Response(status.HTTP_401_UNAUTHORIZED)
def get(self, request): # Render HTML quota = render_quota_html(request) response = Response(status.HTTP_200_OK, {"quota": quota}) return self.render(response)
def get(self, request, pk=None): current_theme = request.website.theme.split('/')[0] try: current_style = request.website.theme.split('/')[1] except: current_style = None # Render HTML if not pk: pk = current_theme theme = themes_info(pk)[0] html = render_to_string('administration/design/styles_list.html', { 'theme': theme, 'current_theme': current_theme, 'current_style': current_style }, context_instance=RequestContext(request)) response = Response(status.HTTP_200_OK, { "html": html, 'current': current_theme }) return self.render(response)
def dispatch(self, request, *args, **kwargs): self.request = request self.args = args self.kwargs = kwargs self.headers = {} # Calls to 'reverse' will not be fully qualified unless we set the scheme/host/port here. orig_prefix = get_script_prefix() if not (orig_prefix.startswith('http:') or orig_prefix.startswith('https:')): prefix = '%s://%s' % (request.is_secure() and 'https' or 'http', request.get_host()) set_script_prefix(prefix + orig_prefix) try: self.initial(request, *args, **kwargs) # Authenticate and check request has the relevant permissions self._check_permissions() # Get the appropriate handler method if self.method.lower() in self.http_method_names: handler = getattr(self, self.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed response_obj = handler(request, *args, **kwargs) # Allow return value to be either HttpResponse, Response, or an object, or None if isinstance(response_obj, HttpResponse): return response_obj elif isinstance(response_obj, Response): response = response_obj elif response_obj is not None: response = Response(status.HTTP_200_OK, response_obj) else: response = Response(status.HTTP_204_NO_CONTENT) if request.method == 'OPTIONS': # do not filter the response for HTTP OPTIONS, else the response fields are lost, # as they do not correspond with model fields response.cleaned_content = response.raw_content else: # Pre-serialize filtering (eg filter complex objects into natively serializable types) response.cleaned_content = self.filter_response(response.raw_content) except ErrorResponse, exc: response = exc.response