def edit(request, document_id): document = get_object_or_404(Document, pk=document_id, status__in=[0, 1]) if not is_company_staff(request, document.company.pk): return redirect('mypage_home') if request.method == 'POST': form = DocumentForm(request.POST, request.FILES, instance=document) if form.is_valid(): document = form.save() if form.cleaned_data['status'] == 2: messages.add_message(request, messages.SUCCESS, '資料を削除しました') else: messages.add_message(request, messages.SUCCESS, '資料を保存しました') return redirect('document_edit_index') else: form = DocumentForm(instance=document) return render_to_response( 'documents/add_edit.html', { 'document': document, 'action': 'edit', 'form': form, }, context_instance=RequestContext(request) )
def create(request): from django.utils import simplejson if request.method == 'POST': # If the form has been submitted... data = request.POST form = DocumentForm(data) # A form bound to the POST data if form.is_valid(): # All validation rules pass d = Document() d.data = form.cleaned_data d.title = form.cleaned_data['title'] d.description = form.cleaned_data['description'] d.public = form.cleaned_data['public'] #d.author = request.user d.save() # Process the data in form.cleaned_data # ... #return HttpResponse(sections) #return HttpResponse(simplejson.dumps(form.cleaned_data)) exercises = simplejson.dumps(get_exercises(data['exercises'])) else: d = {} exercises = False form = DocumentForm() return render_to_response('documents/document_edit.jade', { 'form': form, 'exercises':exercises, },RequestContext(request))
def create(request): from django.utils import simplejson if request.method == 'POST': # If the form has been submitted... data = request.POST form = DocumentForm(data) # A form bound to the POST data if form.is_valid(): # All validation rules pass d = Document() d.data = form.cleaned_data d.title = form.cleaned_data['title'] d.description = form.cleaned_data['description'] d.public = form.cleaned_data['public'] #d.author = request.user d.save() # Process the data in form.cleaned_data # ... #return HttpResponse(sections) #return HttpResponse(simplejson.dumps(form.cleaned_data)) exercises = simplejson.dumps(get_exercises(data['exercises'])) else: d = {} exercises = False form = DocumentForm() return render_to_response('documents/document_edit.jade', { 'form': form, 'exercises': exercises, }, RequestContext(request))
def Document_edit(request, id_documento): if userDocs(request) != True: return render(request, template_no_valid) doc_for_dept = Document.objects.filter( departament=request.session['departament']['active_id']) data = {'model': Document.objects.get(id=id_documento)} if request.method == "GET": form = DocumentForm(instance=data['model']) else: form = DocumentForm(request.POST, instance=data['model']) print(form) if form.is_valid(): form.save() else: print(form.is_valid()) print(form.errors) form = DocumentForm(request.POST) return redirect('document:documento_list') date = Current_date() if Document.objects.filter(id=data['model'].previous).count() > 0: data['previous'] = Document.objects.get(id=data['model'].previous) data['doc_for_dept'] = doc_for_dept data['remittent'] = Remittent.objects.filter(active=True).order_by('id') data['receiver'] = Receiver.objects.filter(active=True).order_by('id') data['type'] = Document_type.objects.all().order_by('id') data['form'] = form data['date'] = date data['editdoc'] = True data['edit'] = True return render(request, 'document/form.html', data)
def test_form_validates_document_field_types(self): form = DocumentForm(data={"field2": "NaN"}, user=DocumentFormTests.u, document_template=DocumentFormTests.dt) self.assertFalse(form.is_valid()) assert_that(form.errors, has_key("field2")) assert_that(form.errors["field2"].as_text(), contains_string("Enter a whole number"))
def handle(self, *args, **options): for path in args: for fname in listdir(path): upload_file = open(join(path, fname), 'rb') post_dict = {'title': fname, 'author': "Auto Test"} file_dict = { 'file': SimpleUploadedFile(upload_file.name, upload_file.read())} form = DocumentForm(post_dict, file_dict) if form.is_valid(): form.save()
def handle(self, *args, **options): for path in args: for fname in listdir(path): upload_file = open(join(path, fname), "rb") post_dict = {"title": fname, "author": "Auto Test"} file_dict = {"file": SimpleUploadedFile(upload_file.name, upload_file.read())} form = DocumentForm(post_dict, file_dict) if form.is_valid(): form.save() file = form.cleaned_data["file"] form.instance.set_file(file=file, filename=file.name)
def test_form_requires_user_owned_unit(self): form = DocumentForm(data={"unit": DocumentFormTests.unit2.id}, user=DocumentFormTests.u, document_template=DocumentFormTests.dt) self.assertFalse(form.is_valid()) assert_that(form.errors, has_key("unit")) assert_that( form.errors["unit"].as_text(), contains_string( "Select a valid choice. That choice is not one of the available choices." ), )
def __upload_core(request): form = DocumentForm(request.POST, request.FILES) if form.is_valid(): u = request.user doc = Document(owner=u) file = request.FILES['file'] doc.filename = request.FILES['file'].name doc.save() doc.file.save('file_' + str(doc.id), file) return doc else: return Exception()
def test_form_requires_required_document_fields(self): form = DocumentForm(data={}, user=DocumentFormTests.u, document_template=DocumentFormTests.dt) self.assertFalse(form.is_valid()) # Fields from base form assert_that(form.errors, has_key("sender_first_name")) assert_that(form.errors, has_key("sender_last_name")) assert_that(form.errors, has_key("unit")) assert_that(form.errors, has_key("sender_address_1")) # Required field from document template assert_that(form.errors, has_key("field1"))
class ProjectView(LoginRequiredMixin, TemplateView): template_name = 'project.html' def get_context_data(self, **kwargs): documents = Document.objects.active().filter(project=self.project) if hasattr(self, 'sort_order'): if self.sort_order == 'AZ': documents = documents.order_by('name') if hasattr(self, 'category'): mimes = get_mimes_for_category(self.category) documents = documents.filter(mime__in=mimes) return { 'categories_form': self.categories_form, 'company_form': self.company_form, 'documents': documents, 'form': self.form, 'project': self.project, 'sort_form': self.sort_form, } def dispatch(self, request, pk, *args, **kwargs): self.project = get_object_or_404(Project.objects.active(), pk=pk) person = Person.objects.get(pk=self.request.user.pk) self.form = DocumentForm(request.POST or None, request.FILES or None, person=person, project=self.project) self.categories_form = CategoryForm(request.GET or None, project=self.project) self.company_form = CompanyForm(request.POST or None, project=self.project) self.sort_form = SortForm(request.GET or None) if 'search' in request.GET: self.sort_order = request.GET.get('search') if 'category' in request.GET and request.GET.get('category'): self.category = request.GET.get('category') return super(ProjectView, self).dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): if 'delete' in request.POST and request.user.is_admin: self.project.set_active(False) messages.success(request, 'The project has been deleted') return redirect(reverse('projects')) if 'move' in request.POST and request.user.is_admin and self.company_form.is_valid(): self.company_form.save() return redirect(reverse('project', args=[self.project.pk])) if 'upload' in request.POST and self.form.is_valid(): self.form.save() messages.success(request, 'The document has been created') return redirect(reverse('project', args=[self.project.pk])) return self.render_to_response(self.get_context_data())
def post(self, request, *args, **kwargs): """Handles the file upload""" form = DocumentForm(request.POST, request.FILES) if form.is_valid(): file = form.save(commit=False) file.user = request.user file.save() messages.success( request, 'El documento "{}" se subió correctamente, ¡muchas gracias!'. format(form.files['file'])) return self.form_valid(form) else: for error in form.errors['file']: messages.error(request, error) return redirect('documents:home')
def test_form_works_with_required_document_fields(self): form = DocumentForm( data={ "sender_first_name": "Eleanor", "sender_last_name": "Shellstrop", "sender_address_1": "123 Main", "sender_city": "Louisville", "sender_state": "KY", "sender_zip_code": "40202", "unit": DocumentFormTests.unit.id, "field1": "F1Value", "field2": 1, }, user=DocumentFormTests.u, document_template=DocumentFormTests.dt, ) self.assertTrue(form.is_valid())
def post(self,request,*args,**kwargs): form = DocumentForm(request.POST or None, request.FILES or None) data = { 'form': form, } file_name = request.POST.get("files") if str(file_name).endswith('.pdf'): type = request.POST.get("type") documentsModel.type = type documentsModel.type = 1 else: type = request.POST.get("type") documentsModel.type = type documentsModel.type = 5 if form.is_valid(): form.save(commit=True) return render(request,self.template_name,data) else: return render(request,self.template_name,data)
def add(request): if not is_company_staff(request): return redirect('mypage_home') user = request.user company = user.customer_company if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): document = form.save(commit=False) document.user = user document.company = company document.save() form.save_m2m() messages.add_message(request, messages.SUCCESS, '資料を保存しました') return redirect('document_edit', document_id=document.pk) else: form = DocumentForm() return render_to_response( 'documents/add_edit.html', { 'action': 'add', 'form': form, }, context_instance=RequestContext(request) )
def dispatch(self, request, pk, *args, **kwargs): self.project = get_object_or_404(Project.objects.active(), pk=pk) person = Person.objects.get(pk=self.request.user.pk) self.form = DocumentForm(request.POST or None, request.FILES or None, person=person, project=self.project) self.categories_form = CategoryForm(request.GET or None, project=self.project) self.company_form = CompanyForm(request.POST or None, project=self.project) self.sort_form = SortForm(request.GET or None) if 'search' in request.GET: self.sort_order = request.GET.get('search') if 'category' in request.GET and request.GET.get('category'): self.category = request.GET.get('category') return super(ProjectView, self).dispatch(request, *args, **kwargs)
def edit(request,pk=False): from django.utils import simplejson if not(pk): doc = Document() else: doc = Document.objects.get(id=pk) if request.method == 'POST': # If the form has been submitted... data = request.POST form = DocumentForm(data) # A form bound to the POST data if form.is_valid(): # All validation rules pass doc.data = form.cleaned_data doc.title = form.cleaned_data['title'] doc.description = form.cleaned_data['description'] #doc.public = form.cleaned_data['public'] doc.author = request.user doc.save() return redirect('document_detail', pk=doc.pk) # Process the data in form.cleaned_data # ... #return HttpResponse(sections) #return HttpResponse(simplejson.dumps(form.cleaned_data)) #doc.data = form.cleaned_data exercises = simplejson.dumps(doc.exercises()) elif not(pk): exercises = False form = DocumentForm() else: d = doc.data if type(d) != dict: d = {} exercises = simplejson.dumps(doc.exercises()) form = DocumentForm(d) # An unbound form #return HttpResponse(simplejson.dumps(get_exercises(d['exercises']))) return render_to_response('documents/document_edit.jade', { 'form': form, 'exercises':exercises, },RequestContext(request))
def test_use_unit_address_uses_unit_address_for_sender_info(self): form = DocumentForm( data={ "sender_first_name": "Eleanor", "sender_last_name": "Shellstrop", "use_unit_address": True, "unit": DocumentFormTests.unit.id, "field1": "F1Value", "field2": 1, }, user=DocumentFormTests.u, document_template=DocumentFormTests.dt, ) self.assertTrue(form.is_valid()) assert_that(form.cleaned_data["sender_address_1"], equal_to(DocumentFormTests.unit.unit_address_1)) assert_that(form.cleaned_data["sender_address_2"], equal_to(DocumentFormTests.unit.unit_address_2)) assert_that(form.cleaned_data["sender_city"], equal_to(DocumentFormTests.unit.unit_city)) assert_that(form.cleaned_data["sender_state"], equal_to(DocumentFormTests.unit.unit_state)) assert_that(form.cleaned_data["sender_zip_code"], equal_to(DocumentFormTests.unit.unit_zip_code))
def add(request): if not is_company_staff(request): return redirect('mypage_home') user = request.user company = user.customer_company if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): document = form.save(commit=False) document.user = user document.company = company document.save() form.save_m2m() messages.add_message(request, messages.SUCCESS, '資料を保存しました') return redirect('document_edit', document_id=document.pk) else: form = DocumentForm() return render_to_response('documents/add_edit.html', { 'action': 'add', 'form': form, }, context_instance=RequestContext(request))
def process_submission(request, group_id): try: group = request.user.group_set.get(id=group_id) except Group.DoesNotExist: return Http404('Requested Group does Not exist') if group.status == 'ACCEPTED': form = DocumentForm(initial={'group_id': group_id}) return render(request, 'documents/submission.html', {'form': form}) elif group.status == 'REQUESTED': messages.info( request, "Your permission for paper submission request is Pending." "To submit your paper, please visit again after the request has been accepted." ) else: group.status = 'REQUESTED' group.save() messages.info( request, "Request to Approve Submission had been sent to your Instructor." "To submit your paper, please visit again after the request has been accepted." ) return redirect('users:dashboard')
def edit(request, pk=False): from django.utils import simplejson if not (pk): doc = Document() else: doc = Document.objects.get(id=pk) if request.method == 'POST': # If the form has been submitted... data = request.POST form = DocumentForm(data) # A form bound to the POST data if form.is_valid(): # All validation rules pass doc.data = form.cleaned_data doc.title = form.cleaned_data['title'] doc.description = form.cleaned_data['description'] #doc.public = form.cleaned_data['public'] doc.author = request.user doc.save() return redirect('document_detail', pk=doc.pk) # Process the data in form.cleaned_data # ... #return HttpResponse(sections) #return HttpResponse(simplejson.dumps(form.cleaned_data)) #doc.data = form.cleaned_data exercises = simplejson.dumps(doc.exercises()) elif not (pk): exercises = False form = DocumentForm() else: d = doc.data if type(d) != dict: d = {} exercises = simplejson.dumps(doc.exercises()) form = DocumentForm(d) # An unbound form #return HttpResponse(simplejson.dumps(get_exercises(d['exercises']))) return render_to_response('documents/document_edit.jade', { 'form': form, 'exercises': exercises, }, RequestContext(request))
def edit(request, document_id): document = get_object_or_404(Document, pk=document_id, status__in=[0, 1]) if not is_company_staff(request, document.company.pk): return redirect('mypage_home') if request.method == 'POST': form = DocumentForm(request.POST, request.FILES, instance=document) if form.is_valid(): document = form.save() if form.cleaned_data['status'] == 2: messages.add_message(request, messages.SUCCESS, '資料を削除しました') else: messages.add_message(request, messages.SUCCESS, '資料を保存しました') return redirect('document_edit_index') else: form = DocumentForm(instance=document) return render_to_response('documents/add_edit.html', { 'document': document, 'action': 'edit', 'form': form, }, context_instance=RequestContext(request))
def workspace(request): logger = logging.getLogger('documents') # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): existing_versioned = Document.objects.order_by('-version') origname = request.FILES['docfile'].name existing = [] for item in existing_versioned: if item.filename and origname.startswith( item.filename.split(".")[0]): existing.append(item) newdoc = Document(docfile=request.FILES['docfile'], author=request.user, filename=request.FILES['docfile'].name, abstract=request.POST['abstract'], keywords=request.POST['keywords'], requires_signature=request.POST.get( 'signature_required', 'off') == 'on') if existing and existing[0].status == 0: newdoc.filename = existing[0].filename newdoc.version = existing[0].version + 0.1 for existing_doc in existing: existing_doc.last_modified = newdoc.last_modified existing_doc.stale = False existing_doc.save() newdoc.save() elif existing and existing[0].status == 1: newdoc.filename = existing[0].filename if existing[0].author == request.user: newdoc.status = 1 newdoc.version = existing[0].version + 1 else: newdoc.status = 2 newdoc.version = existing[0].version + 0.1 newdoc.save() elif existing and existing[0].status == 2: newdoc.filename = existing[0].filename newdoc.status = 2 newdoc.version = existing[0].version + 0.1 newdoc.save() elif existing and existing[0].status == 3: newdoc.filename = existing[0].filename for file in existing: file.filename = "_" + file.filename newdoc.status = 0 newdoc.version = 0.1 newdoc.save() elif not existing: newdoc.version = 0.1 newdoc.save() logger.info('User {} added version {} of Document {}'.format( request.user, newdoc.version, newdoc.filename)) # Redirect to the document list after POST return HttpResponseRedirect(reverse('workspace')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page # status 0 means draft items = Document.objects.filter(status__in=[0, 1, 2], author=request.user).exclude(status=3) import pudb pu.db # Render list page with the documents and the form items2, item_ids = [], [] for item in items: if item.filename not in item_ids: items2.append(item) item_ids.append(item.filename) return render(request, 'documents.html', { 'documents': items2, 'form': form })
def Document_create(request): if userDocs(request) != True: return render(request, template_no_valid) depto = Departament.objects.get( id=request.session['departament']['active_id']) doc_for_dept = Document.objects.filter( departament=request.session['departament']['active_id']) date = Current_date() date_str = date['nday'] + ", " + str( date['day']) + " de " + date['month'] + " del " + str(date['year']) data = {} if request.method == 'POST': form = DocumentForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.user = request.user obj.departament = depto valdos = 0 if doc_for_dept.count() > 0: type = doc_for_dept.filter(type=obj.type) last_document = type.last() data['change'] = last_document.change obj.number = int(last_document.number) + 1 if obj.remittent != last_document.remittent: valdos = valdos + 1 if obj.receiver != last_document.receiver: valdos = valdos + 1 if obj.body != last_document.body: valdos = valdos + 1 if obj.footer != last_document.footer: valdos = valdos + 1 if obj.matter != last_document.matter: valdos = valdos + 1 if obj.change != last_document.change: valdos = valdos + 1 if obj.previous != last_document.previous: valdos = valdos + 1 if valdos < 2: act = Document.objects.get(id=last_document.id) act.number = last_document.number act.matter = obj.matter act.remittent = obj.remittent act.receiver = obj.receiver act.body = obj.body act.footer = obj.footer act.previous = obj.previous act.save() obj.id = last_document.id if valdos > 0: request.session[ 'alert'] = 'Se a modificado el documento. ' + str( obj.id) else: obj.year = date['year'] form.save() else: obj.number = 1 #obj.creacion = date_str obj.year = date['year'] obj.type_id = 1 form.save() return redirect('document:documento_detalle', obj.id) else: print(form.is_valid()) print(form.errors) form = DocumentForm(request.POST) else: form = DocumentForm() data['doc_for_dept'] = doc_for_dept data['edit'] = True #Para activar texto enriquesido data['remittent'] = Remittent.objects.filter(active=True).order_by('id') data['receiver'] = Receiver.objects.filter(active=True).order_by('id') data['type'] = Document_type.objects.all().order_by('id') data['form'] = form data['date'] = date data['model'] = doc_for_dept.last() print(data['model'].change) return render(request, 'document/form.html', data)