def parse_row(self, line, row): """ Method called by :meth:`import_csv` for each row. """ from openPLM.plmapp.forms import get_creation_form type_, reference, revision = self.get_values(row, "type", "reference", "revision") cls = models.get_all_plmobjects()[type_] group = models.GroupInfo.objects.get(name=self.get_value(row, "group")) lifecycle = models.Lifecycle.objects.get(name=self.get_value(row, "lifecycle")) form = get_creation_form(self.user, cls) data = { "type" : type_, "group" : str(group.id), "reference" : reference, "revision" : revision, } for field in form.fields: if field not in data and field in self.headers_dict: data[field] = self.get_value(row, field) form = get_creation_form(self.user, cls, data) if not form.is_valid(): items = (mark_safe(u"%s: %s" % item) for item in form.errors.iteritems()) self.store_errors(line, *items) else: obj = PLMObjectController.create_from_form(form, self.user, True, True) self.objects.append(obj)
def parse_row(self, line, row): """ Method called by :meth:`import_csv` for each row. """ from openPLM.plmapp.forms import get_creation_form type_, reference, revision = self.get_values(row, "type", "reference", "revision") cls = models.get_all_plmobjects()[type_] group = models.GroupInfo.objects.get(name=self.get_value(row, "group")) lifecycle = models.Lifecycle.objects.get(name=self.get_value(row, "lifecycle")) form = get_creation_form(self.user, cls, inbulk_cache=self.inbulk_cache) data = { "type" : type_, "group" : str(group.id), "reference" : reference, "revision" : revision, "auto" : False, } for field in form.fields: if field not in data and field in self.headers_dict: data[field] = self.get_value(row, field) form = get_creation_form(self.user, cls, data, inbulk_cache=self.inbulk_cache) if not form.is_valid(): items = (mark_safe(u"%s: %s" % item) for item in form.errors.iteritems()) self.store_errors(line, *items) else: obj = PLMObjectController.create_from_form(form, self.user, True, True) self.objects.append(obj)
def ajax_creation_form(request): """ Simple view which returns the html of a creation form with the data of :attr:`request.GET` as initial values. The request must contains a get parameter *type* with a valid type, otherwise, a :class:`.HttpResponseForbidden` is returned. """ tf = forms.TypeForm(request.GET) if tf.is_valid(): type_ = tf.cleaned_data["type"] request.session["type"] = type_ request.session.save() cls = models.get_all_users_and_plmobjects()[type_] view = get_creation_view(cls) if view is not None: return {"reload" : True} initial = dict(request.GET.iteritems()) if "pfiles" in request.GET: initial["pfiles"] = request.GET.getlist("pfiles") if "reference" in initial: # gets a new reference if the type switches from a part to a document # and vice versa, see ticket #99 ref = initial["reference"] if (ref.startswith("DOC_") and type_ in models.get_all_parts()) or \ (ref.startswith("PART_") and type_ in models.get_all_documents()): del initial["reference"] form = forms.get_creation_form(request.user, cls, initial=initial) return {"reload" : False, "form" : form.as_table(), "type" : type_, "form_media": form.media.render(), } else: return HttpResponseForbidden()
def test_create_from_form(self): form = get_creation_form(self.user, GroupInfo, {"name" : "grname", "description" :"desc" }) gr = self.CONTROLLER.create_from_form(form, self.user) self.assertEqual(self.user.username, gr.owner.username) self.assertEqual("grname", gr.name) self.assertTrue(self.user.groups.get(id=gr.id))
def get_gdoc_creation_form(user, client, data=None, start=0): form = get_creation_form(user, GoogleDocument, data, start) gdocs = get_gdocs(client) form.gdocs = dict(gdocs) form.fields["resource_id"] = forms.ChoiceField(choices=gdocs, required=True) form.clean = lambda:clean_gdoc(form) return form
def test_create_from_form(self): form = get_creation_form(self.user, GroupInfo, { "name": "grname", "description": "desc" }) gr = self.CONTROLLER.create_from_form(form, self.user) self.assertEqual(self.user.username, gr.owner.username) self.assertEqual("grname", gr.name) self.assertTrue(self.user.groups.get(id=gr.id))
def get_gdoc_creation_form(user, client, data=None, start=0): form = get_creation_form(user, GoogleDocument, data, start) gdocs = get_gdocs(client) form.gdocs = dict(gdocs) form.fields["resource_id"] = forms.ChoiceField(choices=gdocs, required=True) del form.fields.keyOrder[-1] form.fields.keyOrder.insert(0, "resource_id") old_clean = form.clean form.clean = lambda: old_clean() and clean_gdoc(form) return form
def ajax_part_creation_form(request, prefix): """ It updates the form of an assembly determined by **prefix** without recharging the whole page and respecting the information introduced up to the moment The attributes can change depending on the type of part selected """ tf = forms.Doc_Part_type_Form(request.GET, prefix=prefix) if tf.is_valid(): cls = pmodels.get_all_parts()[tf.cleaned_data["type_part"]] cf = pforms.get_creation_form(request.user, cls, prefix=prefix+"-part", data=dict(request.GET.iteritems())) return r2r("extra_attributes.html", {"creation_form" : cf}, request) return HttpResponseForbidden()
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 clone(request, obj_type, obj_ref, obj_revi,creation_form=None): """ Manage html page to display the cloning form of the selected object (part or document) or clone it. :url: :samp:`/object/{obj_type}/{obj_ref}/{obj_revi}/clone/` .. include:: views_params.txt **Template:** :file:`clone.html` :param creation_form: the creation form that will be used to clone the object If the object is a part : :post params: a valid :class:`.SelectDocumentFormset` Only required if *is_linked* is True, see below. a valid :class:`.SelectChildFormset` Only required if *is_linked* is True, see below. A cloned part may be attached to some documents. These documents are given by :meth:`.PartController.get_suggested_documents`. A cloned part may also have some children from the original revision. If the object is a document : :post params: a valid :class:`.SelectPartFormset` Only required if *is_linked* is True, see below. A cloned document may be attached to some parts, given by :meth:`.DocumentController.get_suggested_parts`. **Context:** ``RequestContext`` ``is_linked`` True if the object is linked (attached) to other object , at least one. ``creation_form`` form to clone the object. Fields in this form are set according to the current object. ``doc_formset`` a :class:`.SelectDocmentFormset` of documents that the new object, if it is a part, may be attached to. Only set if *is_linked* is True. ``children_formset`` a :class:`.SelectChildFormset` of parts that the new object, if it is a part, may be linked with. Only set if *is_linked* is True. ``parts_formset`` a :class:`.SelectPartFormset` of parts that the new object, if it is a document, may be attached to. Only set if *is_linked* is True. """ obj, ctx = get_generic_data(request, obj_type, obj_ref, obj_revi) obj.check_clone() cls = models.get_all_users_and_plmobjects()[obj_type] is_linked = True if issubclass(cls, models.Part): children = [c.link for c in obj.get_children(1)] documents = obj.get_suggested_documents() is_linked = ctx['is_linked'] = bool(children or documents) else: parts = obj.get_suggested_parts() is_linked = ctx['is_linked'] = bool(parts) formsets ={} if request.method == 'GET': # generate and fill the creation form not_auto_cloned_fields = ['reference','revision', 'group','lifecycle', 'auto', 'pfiles', 'template'] creation_form = forms.get_creation_form(request.user, cls, template=False) if bool(request.user.groups.filter(id=obj.group.id)): creation_form.fields["group"].initial = obj.group.id if not obj.is_cancelled: creation_form.initial["lifecycle"] = obj.lifecycle for f in creation_form.fields: if f not in not_auto_cloned_fields: creation_form.fields[f].initial = getattr(obj, f) # generate the links form if issubclass(cls, models.Part) and is_linked: initial = [dict(link=link) for link in children] formsets["children_formset"] = forms.SelectChildFormset(prefix="children", initial=initial) initial = [dict(document=d) for d in documents] formsets["doc_formset"] = forms.SelectDocumentFormset(prefix="documents", initial=initial) else: if issubclass(cls, models.Document) and is_linked : formsets["part_formset"] = forms.SelectPartFormset(queryset=parts) elif request.method == 'POST': if issubclass(cls, models.Part) and is_linked: formsets.update({ "children_formset":forms.SelectChildFormset(request.POST, prefix="children"), "doc_formset": forms.SelectDocumentFormset(request.POST, prefix="documents"), }) elif is_linked: formsets["part_formset"]=forms.SelectPartFormset(request.POST) if creation_form is None: creation_form = forms.get_creation_form(request.user, cls, request.POST) if creation_form.is_valid(): if is_linked : valid_forms = False if issubclass(cls, models.Part): valid_forms, selected_children, selected_documents = clone_part(request.user, request.POST, children, documents) if valid_forms : new_ctrl = obj.clone(creation_form, request.user, selected_children, selected_documents) return HttpResponseRedirect(new_ctrl.plmobject_url) else : formsets.update({ "children_formset":forms.SelectChildFormset(request.POST, prefix="children"), "doc_formset": forms.SelectDocumentFormset(request.POST, prefix="document"), }) elif issubclass(cls, models.Document) and is_linked: valid_forms, selected_parts = clone_document(request.user, request.POST, parts) if valid_forms: new_ctrl = obj.clone(creation_form, request.user, selected_parts) return HttpResponseRedirect(new_ctrl.plmobject_url) else : formsets["part_formset"]=forms.SelectPartFormset(request.POST) else: if issubclass(cls, models.Part): new_ctrl = obj.clone(creation_form, request.user, [], []) else: new_ctrl = obj.clone(creation_form, request.user, []) return HttpResponseRedirect(new_ctrl.plmobject_url) ctx['creation_form'] = creation_form ctx.update(formsets) return r2r('clone.html', ctx, request)
def generate_part_doc_links(request,product, parent_ctrl,instances,doc3D, inbulk_cache): """ :param product: :class:`.Product` that represents the arborescense :param parent_ctrl: :class:`.Part` from which we want to realize the decomposition :param instances: Use to trace the items to update Parses forms and generates: - The bom-child of Parts (in relation to the **product**) - For every :class:`.ParentChildLink` generated in the previous condition we attach all the :class:`.Location_link` relatives - To every generated :class:`.Part` a :class:`.Document3D` has been attached and Document3D has been set like the attribute PartDecompose of the Part - The attribute doc_id of every node of the arborescense(**product**) is now the relative id of :class:`.DocumentFile` generated in the previous condition - To every generated :class:`.Document3D` has been added a new empty(locked) :class:`.DocumentFile` STP ( :meth:`.generateGhostDocumentFile` ) - The attribute doc_path of every node of the arborescense(**product**) is now the path of :class:`.DocumentFile` STP generated in the previous condition """ to_delete=[] user = parent_ctrl._user company = pmodels.User.objects.get(username=settings.COMPANY) other_files = list(doc3D.files.exclude(models.is_stp)) for link in product.links: try: oq=forms.Order_Quantity_Form(request.POST,prefix=link.visited) oq.is_valid() options=oq.cleaned_data order=options["order"] quantity=options["quantity"] unit=options["unit"] if not link.product.part_to_decompose: part_ctype=forms.Doc_Part_type_Form(request.POST,prefix=link.product.visited) part_ctype.is_valid() options = part_ctype.cleaned_data cls = get_all_plmobjects()[options["type_part"]] part_form = pforms.get_creation_form(user, cls, request.POST, inbulk_cache=inbulk_cache, prefix=str(link.product.visited)+"-part") part_ctrl = parent_ctrl.create_from_form(part_form, user, True, True) instances.append((part_ctrl.object._meta.app_label, part_ctrl.object._meta.module_name, part_ctrl.object._get_pk_val())) c_link = parent_ctrl.add_child(part_ctrl.object,quantity,order,unit) models.generate_extra_location_links(link, c_link) doc_form = pforms.get_creation_form(user, models.Document3D, request.POST, inbulk_cache=inbulk_cache, prefix=str(link.product.visited)+"-document") doc_ctrl = models.Document3DController.create_from_form(doc_form, user, True, True) link.product.part_to_decompose=part_ctrl.object to_delete.append(generateGhostDocumentFile(link.product, doc_ctrl.object, company)) instances.append((doc_ctrl.object._meta.app_label, doc_ctrl.object._meta.module_name, doc_ctrl.object._get_pk_val())) part_ctrl.attach_to_document(doc_ctrl.object) new_Doc3D = doc_ctrl.object new_Doc3D.PartDecompose = part_ctrl.object new_Doc3D.no_index = True new_Doc3D.save() for doc_file in other_files: filename, ext = os.path.splitext(doc_file.filename) # add files with the same name (for example a .sldXXX # or.CATXXX file) if filename == link.product.name: f = File(doc_file.file) f.name = doc_file.filename f.size = doc_file.size df = doc_ctrl.add_file(f, False, False) if doc_file.thumbnail: doc_ctrl.add_thumbnail(df, File(doc_file.thumbnail)) instances.append((df._meta.app_label, df._meta.module_name, df.pk)) instances.append((doc_file._meta.app_label, doc_file._meta.module_name, doc_file.pk)) doc_file.no_index = True doc_file.deprecated = True doc_file.save() generate_part_doc_links(request,link.product, part_ctrl,instances,doc3D, inbulk_cache) else: c_link = parent_ctrl.add_child(link.product.part_to_decompose,quantity,order,unit) models.generate_extra_location_links(link, c_link) except Exception: raise models.Document_Generate_Bom_Error(to_delete,link.product.name)
def initialize_assemblies(assemblies,product,group,user,index, obj_type, inbulk_cache): """ :param assemblies: will be refill whit the information necessary the generate the forms :param product: :class:`.Product` that represents the arborescense of the :class:`~django.core.files.File` .stp contained in a :class:`.DocumentFile` :param index: Use to mark and to identify the **product** s that already have been visited :param obj_type: Type of the :class:`.Part` from which we want to realize the decomposition :param group: group by default from which we want to realize the decomposition Returns in assemblies a list initialized with the different assemblies of the file step For every Assembly we have the next information: - Name of assembly - Visited , If assembly is sub-assembly of more than an assembly, this attribute will be **False** for all less one of the occurrences If visited is **False**, we will be able to modify only the attributes **Order** , **Quantity** and **Unit** refered to the :class:`.ParentChildLinkin` in the form If visited is not **False** , it will be a new id acording to **index** (>=1) generated to identify the assembly - Depth of assembly - **obj_type** , type of :class:`.Part` of Assembly - A list with the products that compose the assembly for each element in the list: - part_type contains the form to select the type of :class:`.Part` - ord_quantity contains the forms to select Order , Quantity and Unit refered to the :class:`.ParentChildLink` - creation_formset contains the form for the creation of the part selected in part_type and of one :class:`.Document3D` - name_child_assemblies contains the name of the element - is_assembly determine if the element is a single product or another assembly - prefix contains the **index** of the assembly if he is visited for first time , else is False - ref contains the **index** of the assembly if he was visited previously, else False """ if product.links: part_docs = [] for order, link in enumerate(product.links): prefix = index[0] oq=forms.Order_Quantity_Form(prefix=index[0]) oq.fields["order"].initial = (order + 1)*10 oq.fields["quantity"].initial = link.quantity is_assembly = link.product.is_assembly name = link.product.name if not link.product.visited: link.product.visited = index[0] part_type = forms.Doc_Part_type_Form(prefix=index[0]) part_cform = pforms.get_creation_form(user, pmodels.Part, None, index[1], inbulk_cache) # index[0].initial=1 -> -1 part_cform.prefix = str(index[0])+"-part" part_cform.fields["group"].initial = group part_cform.fields["name"].initial = link.product.name doc_cform = pforms.get_creation_form(user, models.Document3D, None, index[1], inbulk_cache) doc_cform.prefix = str(index[0])+"-document" doc_cform.fields["name"].initial = link.product.name doc_cform.fields["group"].initial = group prefix = index[0] part_docs.append(PartDoc(part_type, oq, (part_cform, doc_cform), name, is_assembly, prefix, None)) index[0]+=1 index[1]+=1 initialize_assemblies(assemblies,link.product,group,user,index, "Part", inbulk_cache) else: index[0]+=1 part_docs.append(PartDoc(False, oq, False, name, is_assembly, None, link.product.visited)) assemblies.append(Assembly(part_docs, product.name, product.visited, product.deep, obj_type))
def clean_form(request, assemblies, product, index, obj_type, inbulk_cache): """ :param assemblies: will be refill whit the information necessary the generate the forms :param product: :class:`.Product` that represents the arborescense of the :class:`~django.core.files.File` .stp contained in a :class:`.DocumentFile` :param index: Use to mark and to identify the **product** s that already have been visited :param obj_type: Type of the :class:`.Part` from which we want to realize the decomposition It checks the validity of the forms contained in **request** If the forms are not valid, it returns the information to refill the new forms contained in **assemblies**. Refill **assemblies** with the different assemblies of the file step , we use **index** to mark and to identify the **products** that already have been visited For every Assembly we have the next information: - Name of assembly - Visited , If assembly is sub-assembly of more than one assembly, this attribute will be **False** for all less one of the occurrences If visited is **False**, we will be able to modify only the attributes **Order** , **Quantity** and **Unit** refered to the :class:`.ParentChildLink` in the form If visited is not **False** , it will be a new id acording to **index** (>=1) generated to identify the assembly - Depth of assembly - **obj_type** , type of :class:`.Part` of Assembly - A list with the products that compose the assembly for each element in the list: - part_type contains the form to select the type of :class:`.Part` - ord_quantity contains the forms to select Order , Quantity and Unit refered to the :class:`.ParentChildLink` - creation_formset contains the form for the creation of the part selected in part_type and of one :class:`.Document3D` - name_child_assemblies contains the name of the element - is_assembly determine if the element is a single product or another assembly - prefix contains the **index** of the assembly if he is visited for first time , else is False - ref contains the **index** of the assembly if he was visited previously, else False """ valid=True if product.links: part_docs = [] for link in product.links: link.visited=index[0] oq = forms.Order_Quantity_Form(request.POST,prefix=index[0]) if not oq.is_valid(): valid=False is_assembly = link.product.is_assembly name = link.product.name if not link.product.visited: link.product.visited = index[0] part_type = forms.Doc_Part_type_Form(request.POST, prefix=index[0]) if not part_type.is_valid(): valid = False part = part_type.cleaned_data["type_part"] cls = get_all_plmobjects()[part] part_cform = pforms.get_creation_form(request.user, cls, request.POST, inbulk_cache=inbulk_cache, prefix=str(index[0])+"-part") doc_cform = pforms.get_creation_form(request.user, models.Document3D, request.POST, inbulk_cache=inbulk_cache, prefix=str(index[0])+"-document") if not part_cform.is_valid(): valid = False if not doc_cform.is_valid(): valid = False prefix = index[0] part_docs.append(PartDoc(part_type, oq, (part_cform, doc_cform), name, is_assembly, prefix, None)) index[0]+=1 if not clean_form(request, assemblies, link.product,index, part, inbulk_cache): valid = False else: index[0]+=1 part_docs.append(PartDoc(False, oq, False, name, is_assembly, None, link.product.visited)) assemblies.append(Assembly(part_docs, product.name , product.visited , product.deep, obj_type)) return valid
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 clone(request, obj_type, obj_ref, obj_revi,creation_form=None): """ Manage html page to display the cloning form of the selected object (part or document) or clone it. :url: :samp:`/object/{obj_type}/{obj_ref}/{obj_revi}/clone/` .. include:: views_params.txt **Template:** :file:`clone.html` :param creation_form: the creation form that will be used to clone the object If the object is a part : :post params: a valid :class:`.SelectDocumentFormset` Only required if *is_linked* is True, see below. a valid :class:`.SelectChildFormset` Only required if *is_linked* is True, see below. A cloned part may be attached to some documents. These documents are given by :meth:`.PartController.get_suggested_documents`. A cloned part may also have some children from the original revision. If the object is a document : :post params: a valid :class:`.SelectPartFormset` Only required if *is_linked* is True, see below. A cloned document may be attached to some parts, given by :meth:`.DocumentController.get_suggested_parts`. **Context:** ``RequestContext`` ``is_linked`` True if the object is linked (attached) to other object , at least one. ``creation_form`` form to clone the object. Fields in this form are set according to the current object. ``doc_formset`` a :class:`.SelectDocmentFormset` of documents that the new object, if it is a part, may be attached to. Only set if *is_linked* is True. ``children_formset`` a :class:`.SelectChildFormset` of parts that the new object, if it is a part, may be linked with. Only set if *is_linked* is True. ``parts_formset`` a :class:`.SelectPartFormset` of parts that the new object, if it is a document, may be attached to. Only set if *is_linked* is True. """ obj, ctx = get_generic_data(request, obj_type, obj_ref, obj_revi) obj.check_clone() cls = models.get_all_users_and_plmobjects()[obj_type] is_linked = True if issubclass(cls, models.Part): children = [c.link for c in obj.get_children(1)] documents = obj.get_suggested_documents() is_linked = ctx['is_linked'] = bool(children or documents) else: parts = obj.get_suggested_parts() is_linked = ctx['is_linked'] = bool(parts) formsets ={} if request.method == 'GET': # generate and fill the creation form not_auto_cloned_fields = ['reference','revision', 'group','lifecycle', 'auto', 'pfiles'] creation_form = forms.get_creation_form(request.user, cls) if bool(request.user.groups.filter(id=obj.group.id)): creation_form.fields["group"].initial = obj.group.id if not obj.is_cancelled: creation_form.initial["lifecycle"] = obj.lifecycle for f in creation_form.fields: if f not in not_auto_cloned_fields: creation_form.fields[f].initial = getattr(obj, f) # generate the links form if issubclass(cls, models.Part) and is_linked: initial = [dict(link=link) for link in children] formsets["children_formset"] = forms.SelectChildFormset(prefix="children", initial=initial) initial = [dict(document=d) for d in documents] formsets["doc_formset"] = forms.SelectDocumentFormset(prefix="documents", initial=initial) else: if issubclass(cls, models.Document) and is_linked : formsets["part_formset"] = forms.SelectPartFormset(queryset=parts) elif request.method == 'POST': if issubclass(cls, models.Part) and is_linked: formsets.update({ "children_formset":forms.SelectChildFormset(request.POST, prefix="children"), "doc_formset": forms.SelectDocumentFormset(request.POST, prefix="documents"), }) elif is_linked: formsets["part_formset"]=forms.SelectPartFormset(request.POST) if creation_form is None: creation_form = forms.get_creation_form(request.user, cls, request.POST) if creation_form.is_valid(): if is_linked : valid_forms = False if issubclass(cls, models.Part): valid_forms, selected_children, selected_documents = clone_part(request.user, request.POST, children, documents) if valid_forms : new_ctrl = obj.clone(creation_form, request.user, selected_children, selected_documents) return HttpResponseRedirect(new_ctrl.plmobject_url) else : formsets.update({ "children_formset":forms.SelectChildFormset(request.POST, prefix="children"), "doc_formset": forms.SelectDocumentFormset(request.POST, prefix="document"), }) elif issubclass(cls, models.Document) and is_linked: valid_forms, selected_parts = clone_document(request.user, request.POST, parts) if valid_forms: new_ctrl = obj.clone(creation_form, request.user, selected_parts) return HttpResponseRedirect(new_ctrl.plmobject_url) else : formsets["part_formset"]=forms.SelectPartFormset(request.POST) else: if issubclass(cls, models.Part): new_ctrl = obj.clone(creation_form, request.user, [], []) else: new_ctrl = obj.clone(creation_form, request.user, []) return HttpResponseRedirect(new_ctrl.plmobject_url) ctx['creation_form'] = creation_form ctx.update(formsets) return r2r('clone.html', ctx, request)