Added container copy function
This commit is contained in:
@@ -36,6 +36,42 @@ class ContainerCreateView(LoginRequiredMixin, generic.CreateView):
|
||||
return super().form_valid(form)
|
||||
|
||||
|
||||
def suggest_named_id(existing_id):
|
||||
result = re.search(r'\d{0,9}$', existing_id)
|
||||
number_part = int(result.group()) + 1
|
||||
number_digits = result.span()[1] - result.span()[0]
|
||||
prefix_part = existing_id[0:result.span()[0]]
|
||||
id_candidate = prefix_part + str(number_part).zfill(number_digits)
|
||||
while Container.objects.filter(named_id=id_candidate).exists():
|
||||
number_part = number_part + 1
|
||||
id_candidate = prefix_part + str(number_part).zfill(number_digits)
|
||||
|
||||
return id_candidate
|
||||
|
||||
|
||||
class ContainerCopyView(LoginRequiredMixin, generic.CreateView):
|
||||
model = Container
|
||||
fields = ['named_id', 'description', 'color', 'container_type']
|
||||
success_url = '/container/'
|
||||
|
||||
def form_valid(self, form):
|
||||
if not form.instance.named_id.startswith('C-'):
|
||||
form.instance.named_id = 'C-' + form.instance.named_id
|
||||
form.instance.changed_by = self.request.user
|
||||
form.instance.created_by = self.request.user
|
||||
return super().form_valid(form)
|
||||
|
||||
def get_initial(self, *args, **kwargs):
|
||||
initial = super(ContainerCopyView, self).get_initial(**kwargs)
|
||||
copy_source = Container.objects.get(pk=self.kwargs['pk'])
|
||||
initial['container_type'] = copy_source.container_type
|
||||
initial['color'] = copy_source.color
|
||||
initial['description'] = copy_source.description
|
||||
# strategy to find a new named_id by using the numbers at the end and trying to increment
|
||||
initial['named_id'] = suggest_named_id(existing_id=copy_source.named_id)
|
||||
return initial
|
||||
|
||||
|
||||
class ContainerImportView(LoginRequiredMixin, generic.TemplateView):
|
||||
template_name = 'container_import.html'
|
||||
|
||||
|
||||
Reference in New Issue
Block a user