def ajax_attach(request, plmobject_id): plmobject = get_obj_by_id(plmobject_id, request.user) data = {} if request.GET: form = forms.PLMObjectForm(initial=request.GET) else: form = forms.PLMObjectForm(request.POST) if form.is_valid(): attached = get_obj_from_form(form, request.user) if hasattr(plmobject, "attach_to_document"): plmobject.attach_to_document(attached) elif hasattr(plmobject, "attach_to_part"): plmobject.attach_to_part(attached) return {"result": "ok"} else: data["result"] = "error" data["error"] = "invalid form" for field in ("type", "reference", "revision"): form.fields[field].widget.attrs['readonly'] = 'on' data.update({ "plmobject": { "id": plmobject.id, "type": plmobject.type, "reference": plmobject.reference, "revision": plmobject.revision, }, "form": form.as_table() }) return data
def add_zip_file(request, doc_id, unlock, thumbnail_extension="False", thumbnail=False): """ """ doc = get_obj_by_id(doc_id, request.user) zip_file = zipfile.ZipFile(request.FILES["filename"]) files = zip_file.namelist() for filename in zip_file.namelist(): if not filename.endswith(thumbnail_extension): tmp_file = zip_file.open(filename) dummy_file = File(tmp_file) try: dummy_file.name = filename.decode("utf-8") except UnicodeError: # WinZIP always decode filename as cp437, dummy_file.name = filename.decode("cp437") dummy_file.size = zip_file.getinfo(filename).file_size dummy_file.file = tmp_file df = doc.add_file(dummy_file, thumbnail=True) if unlock == "False" or unlock == "false": doc.lock(df) th = df.filename + "." + thumbnail_extension if thumbnail and th in files: tmp_file = zip_file.open(th) dummy_file = File(tmp_file) dummy_file.name = th dummy_file.size = zip_file.get_info(th).file_size dummy_file.file = tmp_file doc.add_thumbnail(df, dummy_file) return {}
def add_zip_file(request, doc_id, unlock, thumbnail_extension="False" , thumbnail=False ): """ """ doc = get_obj_by_id(doc_id, request.user) zip_file = zipfile.ZipFile(request.FILES["filename"]) files = zip_file.namelist() for filename in zip_file.namelist(): if not filename.endswith(thumbnail_extension): tmp_file = zip_file.open(filename) dummy_file = File(tmp_file) try: dummy_file.name = filename.decode("utf-8") except UnicodeError: # WinZIP always decode filename as cp437, dummy_file.name = filename.decode("cp437") dummy_file.size = zip_file.getinfo(filename).file_size dummy_file.file = tmp_file df = doc.add_file(dummy_file,thumbnail=True) if unlock == "False" or unlock == "false": doc.lock(df) th = df.filename + "." + thumbnail_extension if thumbnail and th in files: tmp_file = zip_file.open(th) dummy_file = File(tmp_file) dummy_file.name = th dummy_file.size = zip_file.get_info(th).file_size dummy_file.file = tmp_file doc.add_thumbnail(df, dummy_file) return {}
def attach_to_part(request, doc_id, part_id): """ Links the :class:`.Document` identified by *doc_id* with the :class:`.Part` identified by *part_id*. :implements: :func:`http_api.attach_to_part` :param request: the request :param doc_id: id of a :class:`.Document` :param part_id: id of a :class:`.Part` :returned fields: None """ doc = get_obj_by_id(doc_id, request.user) part = get_obj_by_id(part_id, request.user) doc.attach_to_part(part) return {}
def revise(request, doc_id): """ Makes a new revision of the :class:`.Document` identified by *doc_id*. :implements: :func:`http_api.revise` :param request: the request :param doc_id: id of a :class:`.Document` :returned fields: * doc, the new document (see :ref:`http-api-object`) * files, a list of files (see :ref:`http-api-file`) """ doc = get_obj_by_id(doc_id, request.user) form = forms.AddRevisionForm(doc, request.user, request.POST) if form.is_valid(): rev = doc.revise(form.cleaned_data["revision"], group=form.cleaned_data["group"]) ret = {"doc": object_to_dict(rev)} files = [] for df in rev.files: files.append(dict(id=df.id, filename=df.filename, size=df.size)) ret["files"] = files return ret else: return {"result": 'error'}
def revise(request, doc_id): """ Makes a new revision of the :class:`.Document` identified by *doc_id*. :implements: :func:`http_api.revise` :param request: the request :param doc_id: id of a :class:`.Document` :returned fields: * doc, the new document (see :ref:`http-api-object`) * files, a list of files (see :ref:`http-api-file`) """ doc = get_obj_by_id(doc_id, request.user) form = forms.AddRevisionForm(doc, request.user, request.POST) if form.is_valid(): rev = doc.revise(form.cleaned_data["revision"], group=form.cleaned_data["group"]) ret = {"doc" : object_to_dict(rev)} files = [] for df in rev.files: files.append(dict(id=df.id, filename=df.filename, size=df.size)) ret["files"] = files return ret else: return {"result" : 'error'}
def lock_files(request): """ .. versionadded:: 2.0 Locks several files in one transactional block. Files are set by a POST parameter, ``files`` which must be a json list of ids of :class:`.DocumentFile` to be locked. If one file can not be locked, no files are locked. :implements: :func:`http_api.lock_files` """ try: files = map(int, json.loads(request.POST["files"])) except (KeyError, ValueError): return {"result": "error", "error": "invalid POST parameter ('files')"} docfiles = models.DocumentFile.objects.filter(deprecated=False, locked=False, id__in=files) if len(docfiles) == len(files): with transaction.commit_on_success(): for df in docfiles: doc = get_obj_by_id(df.document.id, request.user) doc.lock(df) else: return {"result": "error", "error": "files already locked or deprecated"} return {"result": "ok"}
def ajax_add_child(request, part_id): part = get_obj_by_id(part_id, request.user) data = {} if request.GET: form = forms.AddChildForm(part.object, initial=request.GET) else: form = forms.AddChildForm(part.object, request.POST) if form.is_valid(): child = get_obj_from_form(form, request.user) part.add_child(child, form.cleaned_data["quantity"], form.cleaned_data["order"], form.cleaned_data["unit"], **form.extensions) return {"result": "ok"} else: data["result"] = "error" data["error"] = "invalid form" form.fields["type"].widget = widgets.TextInput() for field in ("type", "reference", "revision"): form.fields[field].widget.attrs['readonly'] = 'on' data.update({ "parent": { "id": part.id, "type": part.type, "reference": part.reference, "revision": part.revision, }, "form": form.as_table() }) return data
def lock_files(request): """ .. versionadded:: 2.0 Locks several files in one transactional block. Files are set by a POST parameter, ``files`` which must be a json list of ids of :class:`.DocumentFile` to be locked. If one file can not be locked, no files are locked. :implements: :func:`http_api.lock_files` """ try: files = map(int, json.loads(request.POST["files"])) except (KeyError, ValueError): return {"result": "error", "error": "invalid POST parameter ('files')"} docfiles = models.DocumentFile.objects.filter(deprecated=False, locked=False, id__in=files) if len(docfiles) == len(files): with transaction.commit_on_success(): for df in docfiles: doc = get_obj_by_id(df.document.id, request.user) doc.lock(df) else: return { "result": "error", "error": "files already locked or deprecated" } return {"result": "ok"}
def ajax_can_add_child(request, part_id): part = get_obj_by_id(part_id, request.user) data = {"can_add": False} if part.is_part and request.GET: form = forms.AddPartForm(request.GET) if form.is_valid(): child = get_obj_from_form(form, request.user) data["can_add"] = part.can_add_child(child) return data
def _get_part(self, node): part_id = node["part"]["id"] try: part = self._parts[part_id] except KeyError: part = get_obj_by_id(part_id, self.controller._user) part.check_readable() # indexed content is up to date, indexed attributes are not modified part.object.no_index = True self._parts[part_id] = part return part
def download(request, docfile_id): """ View to download a document file. :param request: :class:`django.http.QueryDict` :param docfile_id: :attr:`.DocumentFile.id` :type docfile_id: str :return: a :class:`django.http.HttpResponse` """ doc_file = models.DocumentFile.objects.get(id=docfile_id) ctrl = get_obj_by_id(int(doc_file.document.id), request.user) ctrl.check_readable() return serve(ctrl, doc_file, "view" in request.GET)
def is_revisable(request, doc_id): """ Returns True if the :class:`.Document` identified by *doc_id* can be revised. :implements: :func:`http_api.is_revisable` :param request: the request :param doc_id: id of a :class:`.Document` :returned fields: revisable, True if it can be revised """ doc = get_obj_by_id(doc_id, request.user) return {"revisable" : doc.is_revisable()}
def _get_doc(self, node): doc_id = node["document"]["id"] try: doc = self._documents["id"] except KeyError: doc = get_obj_by_id(doc_id, self.controller._user) if doc.type != "Document3D": raise ValueError("invalid document") doc.check_readable() # indexed content is up to date, indexed attributes are not modified doc.object.no_index = True self._documents[doc_id] = doc return doc
def is_revisable(request, doc_id): """ Returns True if the :class:`.Document` identified by *doc_id* can be revised. :implements: :func:`http_api.is_revisable` :param request: the request :param doc_id: id of a :class:`.Document` :returned fields: revisable, True if it can be revised """ doc = get_obj_by_id(doc_id, request.user) return {"revisable": doc.is_revisable()}
def ajax_can_attach(request, plmobject_id): plmobject = get_obj_by_id(plmobject_id, request.user) data = {"can_attach" : False} if isinstance(plmobject, PLMObjectController) and request.GET: form = forms.PLMObjectForm(request.GET) if form.is_valid(): attached = get_obj_from_form(form, request.user) if attached.check_readable(False): if hasattr(plmobject, "can_attach_document"): data["can_attach"] = plmobject.can_attach_document(attached) elif hasattr(plmobject, "can_attach_part"): data["can_attach"] = plmobject.can_attach_part(attached) return data
def get_object(request, obj_id): """ .. versionadded:: 2.0 Returns basic fields of the :class:`.PLMObject` identified by *obj_id*. :implements: :func:`http_api.get` :param request: the request :param obj_id: id of a :class:`.PLMObject` :returned fields: object, a dictionary of object fields """ obj = get_obj_by_id(obj_id, request.user) obj.check_readable() return {"object": object_to_dict(obj)}
def add_file(request, doc_id, thumbnail=False): """ Adds a file to the :class:`.Document` identified by *doc_id*. :implements: :func:`http_api.add_file` :param request: the request :param doc_id: id of a :class:`.Document` :returned fields: doc_file, the file that has been had, see :ref:`http-api-file`. """ doc = get_obj_by_id(doc_id, request.user) form = forms.AddFileForm(request.POST, request.FILES) df = doc.add_file(request.FILES["filename"], thumbnail=thumbnail) return {"doc_file": dict(id=df.id, filename=df.filename, size=df.size)}
def add_file(request, doc_id, thumbnail=False): """ Adds a file to the :class:`.Document` identified by *doc_id*. :implements: :func:`http_api.add_file` :param request: the request :param doc_id: id of a :class:`.Document` :returned fields: doc_file, the file that has been had, see :ref:`http-api-file`. """ doc = get_obj_by_id(doc_id, request.user) form = forms.AddFileForm(request.POST, request.FILES) df = doc.add_file(request.FILES["filename"], thumbnail=thumbnail) return {"doc_file" : dict(id=df.id, filename=df.filename, size=df.size)}
def is_locked(request, doc_id, df_id): """ Returns True if the :class:`.DocumentFile` identified by *df_id* from the :class:`.Document` identified by *doc_id* is locked. :implements: :func:`http_api.is_locked` :param request: the request :param doc_id: id of a :class:`.Document` :param df_id: id of a :class:`.DocumentFile` :returned fields: locked, True if the file is locked. """ doc = get_obj_by_id(doc_id, request.user) df = models.DocumentFile.objects.get(id=df_id) return {"locked" : df.locked}
def check_out(request, doc_id, df_id): """ Locks the :class:`.DocumentFile` identified by *df_id* from the :class:`.Document` identified by *doc_id*. :implements: :func:`http_api.lock` :param request: the request :param doc_id: id of a :class:`.Document` :param df_id: id of a :class:`.DocumentFile` :returned fields: None """ doc = get_obj_by_id(doc_id, request.user) df = models.DocumentFile.objects.get(id=df_id) doc.lock(df) return {}
def next_revision(request, doc_id): """ Returns a possible new revision for the :class:`.Document` identified by *doc_id*. :implements: :func:`http_api.next_revision` :param request: the request :param doc_id: id of a :class:`.Document` :returned fields: revision, the new revision (may be an empty string) .. seealso:: :func:`.utils.get_next_revision` for possible results """ doc = get_obj_by_id(doc_id, request.user) return {"revision": get_next_revision(doc.revision)}
def is_locked(request, doc_id, df_id): """ Returns True if the :class:`.DocumentFile` identified by *df_id* from the :class:`.Document` identified by *doc_id* is locked. :implements: :func:`http_api.is_locked` :param request: the request :param doc_id: id of a :class:`.Document` :param df_id: id of a :class:`.DocumentFile` :returned fields: locked, True if the file is locked. """ doc = get_obj_by_id(doc_id, request.user) df = models.DocumentFile.objects.get(id=df_id) return {"locked": df.locked}
def next_revision(request, doc_id): """ Returns a possible new revision for the :class:`.Document` identified by *doc_id*. :implements: :func:`http_api.next_revision` :param request: the request :param doc_id: id of a :class:`.Document` :returned fields: revision, the new revision (may be an empty string) .. seealso:: :func:`.utils.get_next_revision` for possible results """ doc = get_obj_by_id(doc_id, request.user) return {"revision" : get_next_revision(doc.revision)}
def delete_doc_cad(request, obj_type, obj_ref, obj_revi): """ View to detach a document referred by the POST parameter ``plmobject``. :url: :samp:`/object/{obj_type}/{obj_ref}/{obj_revi}/doc-cad/delete/` .. include:: views_params.txt """ obj, ctx = get_generic_data(request, obj_type, obj_ref, obj_revi) if request.POST: doc_id = int(request.POST["plmobject"]) doc = get_obj_by_id(doc_id, request.user) obj.detach_document(doc) msg = _("The document {doc.type}/{doc.reference}/{doc.revision} has been detached.") messages.info(request, msg.format(doc=doc)) return HttpResponseRedirect(obj.plmobject_url + "doc-cad/")
def delete_part(request, obj_type, obj_ref, obj_revi): """ View to detach a part referred by the POST parameter ``plmobject``. :url: :samp:`/object/{obj_type}/{obj_ref}/{obj_revi}/parts/delete/` .. include:: views_params.txt """ obj, ctx = get_generic_data(request, obj_type, obj_ref, obj_revi) if request.POST: part_id = int(request.POST["plmobject"]) part = get_obj_by_id(part_id, request.user) obj.detach_part(part) msg = _("The part {part.type}/{part.reference}/{part.revision} has been detached.") messages.info(request, msg.format(part=part)) return HttpResponseRedirect(obj.plmobject_url + "parts/")
def add_thumbnail(request, doc_id, df_id): """ Adds a thumbnail to the :class:`.DocumentFile` identified by *df_id* from the :class:`.Document` identified by *doc_id*. :implements: :func:`http_api.add_thumbnail` :param request: the request :param doc_id: id of a :class:`.Document` :param df_id: id of a :class:`.DocumentFile` :returned fields: None """ doc = get_obj_by_id(doc_id, request.user) form = forms.AddFileForm(request.POST, request.FILES) df = models.DocumentFile.objects.get(id=df_id) doc.add_thumbnail(df, request.FILES["filename"]) return {}
def get_attached_documents(request, part_id): """ .. versionadded:: 2.0 Returns documents attached to the :class:`.Part` identified by *part_id*. :implements: :func:`http_api.attached_documents` :param request: the request :param part_id: id of a :class:`.Part` :returned fields: documents, a list of dictionaries describing attached documents """ part = get_obj_by_id(part_id, request.user) part.check_readable() docs = [] for link in part.get_attached_documents(): docs.append(object_to_dict(link.document)) return {"documents": docs}
def check_in(request, doc_id, df_id, thumbnail=False): """ Checks-in the :class:`.DocumentFile` identified by *df_id* from the :class:`.Document` identified by *doc_id* :implements: :func:`http_api.check_in` :param request: the request :param doc_id: id of a :class:`.Document` :param df_id: id of a :class:`.DocumentFile` :returned fields: None """ doc = get_obj_by_id(doc_id, request.user) df = models.DocumentFile.objects.get(id=df_id) form = forms.AddFileForm(request.POST, request.FILES) if form.is_valid(): doc.checkin(df, request.FILES['filename'], thumbnail=thumbnail) return {}
def get_attached_parts(request, doc_id): """ .. versionadded:: 2.0 Returns parts attached to the :class:`.Document` identified by *doc_id*. :implements: :func:`http_api.attached_parts` :param request: the request :param doc_id: id of a :class:`.Document` :returned fields: parts, a list of dictionaries describing attached parts """ doc = get_obj_by_id(doc_id, request.user) doc.check_readable() parts = [] for link in doc.get_attached_parts(): parts.append(object_to_dict(link.part)) return {"parts": parts}
def delete_doc_cad(request, obj_type, obj_ref, obj_revi): """ View to detach a document referred by the POST parameter ``plmobject``. :url: :samp:`/object/{obj_type}/{obj_ref}/{obj_revi}/doc-cad/delete/` .. include:: views_params.txt """ obj, ctx = get_generic_data(request, obj_type, obj_ref, obj_revi) if request.POST: doc_id = int(request.POST["plmobject"]) doc = get_obj_by_id(doc_id, request.user) obj.detach_document(doc) msg = _( "The document {doc.type}/{doc.reference}/{doc.revision} has been detached." ) messages.info(request, msg.format(doc=doc)) return HttpResponseRedirect(obj.plmobject_url + "doc-cad/")
def public_3d_js(request, obj_id): obj = get_obj_by_id(int(obj_id), request.user) if not obj.is_document and not obj.type == "Document3D": raise Http404 if not obj.published and request.user.is_anonymous(): return redirect_to_login(request.get_full_path()) elif not obj.published and not obj.check_restricted_readable(False): raise Http404 try: doc_file = obj.files.filter(models.is_stp)[0] except IndexError: js_files = [] else: js_files = obj.get_all_geometry_files(doc_file) if not js_files: return HttpResponse("") f = fileinput.FileInput(os.path.join(settings.MEDIA_ROOT, "3D", p) for p in js_files) response = StreamingHttpResponse(f, content_type="text/script") return response
def public_download(request, docfile_id): """ View to download a published document file. It returns an :class: `HttpResponseForbidden` if the document is not published. :param request: :class:`django.http.QueryDict` :param docfile_id: :attr:`.DocumentFile.id` :type docfile_id: str :return: a :class:`django.http.HttpResponse` """ doc_file = models.DocumentFile.objects.get(id=docfile_id) ctrl = get_obj_by_id(int(doc_file.document.id), request.user) if request.user.is_authenticated(): if not ctrl.published and not ctrl.check_restricted_readable(False): raise Http404 elif not ctrl.published: return HttpResponseForbidden() return serve(ctrl, doc_file)
def create_object(request, from_registered_view=False, creation_form=None): """ View to create a :class:`.PLMObject` or a :class:`.GroupInfo`. :url: ``/object/create/`` Requests (POST and GET) must contain a ``type`` variable that validates a :class:`.TypeForm`. POST requests must validate the creation form, fields depend on the given type. If the creation form is valid, an object is created and in case of success, this view redirects to the created object. Requests may contain a ``__next__`` variable. A successful creation will redirect to this URL. Some special strings are replaced: * ``##type##`` with the created object's type * ``##ref##`` with the created object's reference * ``##rev##`` with the created object's reference Requests may also contain other special variables (at most one of them): ``related_doc`` Id of a document. The created part will be attached to this document. Object's type is restricted to part types. Two context variables (``related_doc`` and ``related``) are set to the document controller. ``related_part`` Id of a part. The created document will be attached to this part. Object's type is restricted to document types. Two context variables (``related_part`` and ``related``) are set to the part controller. ``related_parent`` Id of a part. Object's type is restricted to part types. Two context variables (``related_parent`` and ``related``) are set to the part controller. .. note:: If *from_registered_view* is False, this view delegates its treatment to a registered view that handles creation of objects of the given type. (see :func:`.get_creation_view` and :func:`.register_creation_view`) :param from_registered_view: True if this function is called by another creation view :param creation_form: a creation form that will be used instead of the default one **Template:** :file:`create.html` **Context:** ``RequestContext`` ``creation_form`` ``creation_type_form`` :class:`.TypeForm` to select the type of the created object ``object_type`` type of the created object ``next`` value of the ``__next__`` request variable if given """ obj, ctx = get_generic_data(request) Form = forms.TypeForm # it is possible that the created object must be attached to a part # or a document # related_doc and related_part should be a plmobject id # If the related_doc/part is not a doc/part, we let python raise # an AttributeError, since a user should not play with the URL # and openPLM must be smart enough to produce valid URLs attach = related = None if "related_doc" in request.REQUEST: Form = forms.PartTypeForm doc = get_obj_by_id(int(request.REQUEST["related_doc"]), request.user) attach = doc.attach_to_part ctx["related_doc"] = request.REQUEST["related_doc"] related = ctx["related"] = doc elif "related_part" in request.REQUEST: Form = forms.DocumentTypeForm part = get_obj_by_id(int(request.REQUEST["related_part"]), request.user) attach = part.attach_to_document ctx["related_part"] = request.REQUEST["related_part"] related = ctx["related"] = part elif "related_parent" in request.REQUEST: Form = forms.PartTypeForm parent = get_obj_by_id(int(request.REQUEST["related_parent"]), request.user) ctx["related_parent"] = request.REQUEST["related_parent"] related = ctx["related"] = parent if "pfiles" in request.REQUEST: Form = forms.Document2TypeForm if "__next__" in request.REQUEST: redirect_to = request.REQUEST["__next__"] ctx["next"] = redirect_to else: # will redirect to the created object redirect_to = None type_form = Form(request.REQUEST) if type_form.is_valid(): type_ = type_form.cleaned_data["type"] cls = models.get_all_users_and_plmobjects()[type_] if not from_registered_view: view = get_creation_view(cls) if view is not None: # view has been registered to create an object of type 'cls' return view(request) else: ctx["creation_type_form"] = type_form return r2r('create.html', ctx, request) if request.method == 'GET' and creation_form is None: creation_form = forms.get_creation_form(request.user, cls, template="pfiles" not in request.GET) if related is not None: creation_form.fields["group"].initial = related.group creation_form.initial["lifecycle"] = related.lifecycle if "pfiles" in request.GET: pfiles = request.GET.getlist("pfiles") creation_form.initial["pfiles"] = pfiles try: name = filename_to_name(obj.files.get(id=int(pfiles[0])).filename) creation_form.initial["name"] = name except Exception: pass elif request.method == 'POST': if creation_form is None: creation_form = forms.get_creation_form(request.user, cls, request.POST) if creation_form.is_valid(): ctrl_cls = get_controller(type_) ctrl = ctrl_cls.create_from_form(creation_form, request.user) message = _(u"The %(Object_type)s has been created") % dict(Object_type = type_) messages.info(request, message) if attach is not None: try: attach(ctrl) message = _(u"The %(Object_type)s has been attached") % dict(Object_type = type_) messages.info(request, message) except (ControllerError, ValueError) as e: # crtl cannot be attached (maybe the state of the # related object as changed) # alerting the user using the messages framework since # the response is redirected message = _(u"Error: %(details)s") % dict(details=unicode(e)) messages.error(request, message) # redirecting to the ctrl page that lists its attached # objects if ctrl.is_document: return HttpResponseRedirect(ctrl.plmobject_url + "parts/") else: return HttpResponseRedirect(ctrl.plmobject_url + "doc-cad/") if redirect_to: redirect_to = redirect_to.replace("##ref##", ctrl.reference) redirect_to = redirect_to.replace("##rev##", ctrl.revision) redirect_to = redirect_to.replace("##type##", ctrl.type) return HttpResponseRedirect(redirect_to or ctrl.plmobject_url) ctx.update({ 'creation_form' : creation_form, 'object_type' : type_, 'creation_type_form' : type_form, }) return r2r('create.html', ctx, request)
def get_document3D(request, doc_id): doc = get_obj_by_id(doc_id, request.user) if doc.type != "Document3D": raise ValueError("Document must be a Document3D") doc.check_readable() return doc
def create_object(request, from_registered_view=False, creation_form=None): """ View to create a :class:`.PLMObject` or a :class:`.GroupInfo`. :url: ``/object/create/`` Requests (POST and GET) must contain a ``type`` variable that validates a :class:`.TypeForm`. POST requests must validate the creation form, fields depend on the given type. If the creation form is valid, an object is created and in case of success, this view redirects to the created object. Requests may contain a ``__next__`` variable. A successful creation will redirect to this URL. Some special strings are replaced: * ``##type##`` with the created object's type * ``##ref##`` with the created object's reference * ``##rev##`` with the created object's reference Requests may also contain other special variables (at most one of them): ``related_doc`` Id of a document. The created part will be attached to this document. Object's type is restricted to part types. Two context variables (``related_doc`` and ``related``) are set to the document controller. ``related_part`` Id of a part. The created document will be attached to this part. Object's type is restricted to document types. Two context variables (``related_part`` and ``related``) are set to the part controller. ``related_parent`` Id of a part. Object's type is restricted to part types. Two context variables (``related_parent`` and ``related``) are set to the part controller. .. note:: If *from_registered_view* is False, this view delegates its treatment to a registered view that handles creation of objects of the given type. (see :func:`.get_creation_view` and :func:`.register_creation_view`) :param from_registered_view: True if this function is called by another creation view :param creation_form: a creation form that will be used instead of the default one **Template:** :file:`create.html` **Context:** ``RequestContext`` ``creation_form`` ``creation_type_form`` :class:`.TypeForm` to select the type of the created object ``object_type`` type of the created object ``next`` value of the ``__next__`` request variable if given """ obj, ctx = get_generic_data(request) Form = forms.TypeForm # it is possible that the created object must be attached to a part # or a document # related_doc and related_part should be a plmobject id # If the related_doc/part is not a doc/part, we let python raise # an AttributeError, since a user should not play with the URL # and openPLM must be smart enough to produce valid URLs attach = related = None if "related_doc" in request.REQUEST: Form = forms.PartTypeForm doc = get_obj_by_id(int(request.REQUEST["related_doc"]), request.user) attach = doc.attach_to_part ctx["related_doc"] = request.REQUEST["related_doc"] related = ctx["related"] = doc elif "related_part" in request.REQUEST: Form = forms.DocumentTypeForm part = get_obj_by_id(int(request.REQUEST["related_part"]), request.user) attach = part.attach_to_document ctx["related_part"] = request.REQUEST["related_part"] related = ctx["related"] = part elif "related_parent" in request.REQUEST: Form = forms.PartTypeForm parent = get_obj_by_id(int(request.REQUEST["related_parent"]), request.user) ctx["related_parent"] = request.REQUEST["related_parent"] related = ctx["related"] = parent if "pfiles" in request.REQUEST: Form = forms.Document2TypeForm if "__next__" in request.REQUEST: redirect_to = request.REQUEST["__next__"] ctx["next"] = redirect_to else: # will redirect to the created object redirect_to = None type_form = Form(request.REQUEST) if type_form.is_valid(): type_ = type_form.cleaned_data["type"] cls = models.get_all_users_and_plmobjects()[type_] if not from_registered_view: view = get_creation_view(cls) if view is not None: # view has been registered to create an object of type 'cls' return view(request) else: ctx["creation_type_form"] = type_form return r2r('create.html', ctx, request) if request.method == 'GET' and creation_form is None: creation_form = forms.get_creation_form(request.user, cls, template="pfiles" not in request.GET) if related is not None: creation_form.fields["group"].initial = related.group creation_form.initial["lifecycle"] = related.lifecycle if "pfiles" in request.GET: pfiles = request.GET.getlist("pfiles") creation_form.initial["pfiles"] = pfiles try: name = filename_to_name( obj.files.get(id=int(pfiles[0])).filename) creation_form.initial["name"] = name except Exception: pass elif request.method == 'POST': if creation_form is None: creation_form = forms.get_creation_form(request.user, cls, request.POST) if creation_form.is_valid(): ctrl_cls = get_controller(type_) ctrl = ctrl_cls.create_from_form(creation_form, request.user) message = _(u"The %(Object_type)s has been created") % dict( Object_type=type_) messages.info(request, message) if attach is not None: try: attach(ctrl) message = _(u"The %(Object_type)s has been attached" ) % dict(Object_type=type_) messages.info(request, message) except (ControllerError, ValueError) as e: # crtl cannot be attached (maybe the state of the # related object as changed) # alerting the user using the messages framework since # the response is redirected message = _(u"Error: %(details)s") % dict( details=unicode(e)) messages.error(request, message) # redirecting to the ctrl page that lists its attached # objects if ctrl.is_document: return HttpResponseRedirect(ctrl.plmobject_url + "parts/") else: return HttpResponseRedirect(ctrl.plmobject_url + "doc-cad/") if redirect_to: redirect_to = redirect_to.replace("##ref##", ctrl.reference) redirect_to = redirect_to.replace("##rev##", ctrl.revision) redirect_to = redirect_to.replace("##type##", ctrl.type) return HttpResponseRedirect(redirect_to or ctrl.plmobject_url) ctx.update({ 'creation_form': creation_form, 'object_type': type_, 'creation_type_form': type_form, }) return r2r('create.html', ctx, request)