0% found this document useful (0 votes)
294 views44 pages

Office File Management System

The document discusses the proposed Office Document Management System. It describes the existing manual system as time-consuming and difficult to manage documents. The proposed system would allow users to check documents in and out, track versions automatically, and search by filename or metadata. A feasibility analysis found the technical requirements could be met using existing hardware and software. The system would improve efficiency over the current manual process and save costs in the long run.

Uploaded by

atozdhiyanes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
294 views44 pages

Office File Management System

The document discusses the proposed Office Document Management System. It describes the existing manual system as time-consuming and difficult to manage documents. The proposed system would allow users to check documents in and out, track versions automatically, and search by filename or metadata. A feasibility analysis found the technical requirements could be met using existing hardware and software. The system would improve efficiency over the current manual process and save costs in the long run.

Uploaded by

atozdhiyanes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

1.

INTRODUCTION

1.1 ABOUT THE PROJECT

Office Document Management System is an efficient, time saving and easy way to
report, view and control the version of a file. It is now an easy task and managing it is much
easier. DMS, a suite of programs that automates away most of the drudgery involved in
keeping an annotated history of your project and avoiding modification conflicts. Most DMS
s shares the same basic logic. To use one, start by registering a collection of source files that
is, telling your DMS to start archive files describing their change histories. Thereafter, when
you want to edit one of these files, you have to check out the file assert an exclusive lock on
it. When you're done, you check in the file, adding your changes to the archive, releasing the
lock, and entering a change comment explaining what you did.

1
2. SYSTEM ANALYSIS

2.1 FEASIBILTY STUDY


A feasibility analysis usually involves a thorough assessment of the operational(need),
financial and technical aspects of a proposal. Feasibility study is the test of the system
proposal made to identify whether the user needs may be satisfied using the current software
and hardware technologies, whether the system will be cost effective from a business point of
view and whether it can be developed with the given budgetary constraints. A feasibility
study should be relatively cheap and done at the earliest possible time. Depending on the
study, the decision is made whether to go ahead with a more detailed analysis.
When a new project is proposed, it normally goes through feasibility assessment.
Feasibility study is carried out to determine whether the proposed system is possible to
develop with available resources and what should be the cost consideration. Facts considered
in the feasibility analysis were.
 Technical Feasibility
 Economic Feasibility
 Behavioral Feasibility

Technical Feasibility
Technical Feasibility deals with the hardware as well as software requirements.
Technology is not a constraint to type system development. To find out whether the
necessary technology, the proposed equipments have the capacity to hold the data, which is
used in the project, should be checked to carry out this technical feasibility.
The technical feasibility issues usually raised during the feasibility stage of
investigation includes these
 This software is running in windows 7 Operating System, which can be easily
installed.
 The hardware required is Pentium based server.
 The system can be expanded.

2
Economical Feasibility
This feasibility study present tangible and intangible benefits from the prefect by
comparing the development and operational cost. The technique of cost benefit analysis is
often used as a basis for assessing economic feasibility. This system needs some more initial
investment than the existing system, but it can be justifiable that it will improve quality of
service.
Thus feasibility study should center along the following points:
 Improvement resulting over the existing method in terms of accuracy,
timeliness.
 Cost comparison
 Estimate on the life expectancy of the hardware
 Overall objective
Our project is economically feasible. It does not require much cost to be involved in the
overall process. The overall objectives are in easing out the requirement processes.

Behavioral/ Operational Feasibility


This analysis involves how it will work when it is installed and the assessment of
political and managerial environment in which it is implemented. People are inherently
resistant to change and computers have been known to facilitate change. The new proposed
system is very much useful to the useful to the users and there for it will accept broad
audience from around the world.

3
2.2 EXISTING SYSTEM
The first problem is that there are loads of hard copied documents are being
generated. Keeping the information in the form of hard copied documents lead to many
problems. All the process done manually at the centers and all the records are maintained
on the papers. So the maintenance of the record is very difficult in the departments as well as
it is very difficult for the staff to check the record. The existing system is monotonous, time
consuming, less flexible and provides a very hectic working schedule. The chance of loss of
record is very high and also record searching is very difficult. Maintenance of the system is
also very difficult and take a lot of time. Result processing is slow due to paper work and
requirement of staff.
Disadvantages:
• Highly Expensive.
• Storing data and retrieval becomes very difficult.
• It is not computerized and hence not systematic.
• Lack of database security.
• Same data are stored in more than one location.
• Access speed is less for searching and modifying data.
• products, offers, change in prices.

4
2.3 PROPOSED SYSTEM

In the proposed system rights to the groups and files were separately given. The
members in a particular project group cannot work in another project at the same time. Along
with this right file accessing privileges are also set for each member in the project. Two
different histories are maintained along the project. The file manipulating process is
controlled by a centralized controlling system. The version numbering process is done
automatically. When a particular user access a file and update it and when uploading the to
the server its version number automatically increases and the latest version of the file will be
stored in server. The searching process is done in two ways. One is filename and the other is
by metadata search.

5
3. SYSTEM ENVIRONMENT

3.1 HARDWARE REQUIREMENTS

The hardware used for the development of the project is:


Processor : Intel Core i3

RAM capacity : 4 GB

Hard disk drive : 1TB

Keyboard : Multi Media

Mouse : Optical

Monitor : 17” Color

3.2 SOFTWARE REQUIREMENTS

The software used for the development of the project is:


Operating System : Windows

Front end used : Python

Back end used : SQLite

Framework : Django

6
3.3 SOFTWARE SPECIFICATION

FRONT END

Python is an interpreter, object-oriented, high-level programming language with


dynamic semantics. Its high-level built in data structures, combined with dynamic typing and
dynamic binding, make it very attractive for Rapid Application Development, as well as for
use as a scripting or glue language to connect existing components together. Python's simple,
easy to learn syntax emphasizes readability and therefore reduces the cost of program
maintenance. Python supports modules and packages, which encourages program modularity
and code reuse. The Python interpreter and the extensive standard library are available in
source or binary form without charge for all major platforms, and can be freely distributed.

Often, programmers fall in love with Python because of the increased productivity it
provides. Since there is no compilation step, the edit-test-debug cycle is incredibly fast.
Debugging Python programs is easy: a bug or bad input will never cause a segmentation
fault. Instead, when the interpreter discovers an error, it raises an exception. When the
program doesn't catch the exception, the interpreter prints a stack trace. A source level
debugger allows inspection of local and global variables, evaluation of arbitrary expressions,
setting breakpoints, stepping through the code a line at a time, and so on. The debugger is
written in Python itself, testifying to Python's introspective power. On the other hand, often
the quickest way to debug a program is to add a few print statements to the source: the fast
edit-test-debug cycle makes this simple approach very effective.

Python is a multi-paradigm programming language. Object-oriented programming


and structured programming are fully supported, and many of its features support functional
programming and aspect-oriented programming (including by meta programming and meta
objects (magic methods)). Many other paradigms are supported via extensions, including
design by contract and logic programming.

Python uses dynamic typing and a combination of reference counting and a cycle-
detecting garbage collector for memory management. It also features dynamic name
resolution (late binding), which binds method and variable names during program execution.

7
Python's design offers some support for functional programming in the Lisp tradition.
It has filter, map, and reduce functions; list comprehensions, dictionaries, sets, and
generator expressions. The standard library has two modules (itertools and functools) that
implement functional tools borrowed from Haskell and Standard ML.[56]

The language's core philosophy is summarized in the document The Zen of Python
(PEP 20), which includes aphorisms such as:

 Beautiful is better than ugly.


 Explicit is better than implicit.
 Simple is better than complex.
 Complex is better than complicated.
 Readability counts.

Rather than having all of its functionality built into its core, Python was designed to
be highly extensible. This compact modularity has made it particularly popular as a means of
adding programmable interfaces to existing applications. Van Rossum's vision of a small core
language with a large standard library and easily extensible interpreter stemmed from his
frustrations with ABC, which espoused the opposite approach.

Python strives for a simpler, less-cluttered syntax and grammar while giving
developers a choice in their coding methodology. In contrast to Perl's "there is more than one
way to do it" motto, Python embraces a "there should be one—and preferably only one—
obvious way to do it" design philosophy. Alex Martelli, a Fellow at the Python Software
Foundation and Python book author, writes that "To describe something as 'clever' is not
considered a compliment in the Python culture."

Python's developers strive to avoid premature optimization, and reject patches to non-
critical parts of the C Python reference implementation that would offer marginal increases in
speed at the cost of clarity.[59] When speed is important, a Python programmer can move time-
critical functions to extension modules written in languages such as C, or use PyPy, a just-in-
time compiler. Cython is also available, which translates a Python script into C and makes
direct C-level API calls into the Python interpreter.

8
An important goal of Python's developers is keeping it fun to use. This is reflected in
the language's name—a tribute to the British comedy group Monty Python[60]—and in
occasionally playful approaches to tutorials and reference materials, such as examples that
refer to spam and eggs (from a famous Monty Python sketch) instead of the standard foo and
bar.[61][62]

A common neologism in the Python community is pythonic, which can have a wide
range of meanings related to program style. To say that code is pythonic is to say that it uses
Python idioms well, that it is natural or shows fluency in the language, that it conforms with
Python's minimalist philosophy and emphasis on readability. In contrast, code that is difficult
to understand or reads like a rough transcription from another programming language is
called unpythonic.

Users and admirers of Python, especially those considered knowledgeable or


experienced, are often referred to as Pythonistas

Statements and control flow

Python's statements include (among others):

 The assignment statement (token '=', the equals sign). This operates differently than in
traditional imperative programming languages, and this fundamental mechanism
(including the nature of Python's version of variables) illuminates many other features
of the language. Assignment in C, e.g., x = 2, translates to "typed variable name x
receives a copy of numeric value 2". The (right-hand) value is copied into an allocated
storage location for which the (left-hand) variable name is the symbolic address. The
memory allocated to the variable is large enough (potentially quite large) for the
declared type. In the simplest case of Python assignment, using the same example, x
= 2, translates to "(generic) name x receives a reference to a separate, dynamically
allocated object of numeric (int) type of value 2." This is termed binding the name to
the object. Since the name's storage location doesn't contain the indicated value, it is
improper to call it a variable. Names may be subsequently rebound at any time to
objects of greatly varying types, including strings, procedures, complex objects with
data and methods, etc. Successive assignments of a common value to multiple names,
e.g., x = 2; y = 2; z = 2 result in allocating storage to (at most) three names and

9
one numeric object, to which all three names are bound. Since a name is a generic
reference holder it is unreasonable to associate a fixed data type with it. However at a
given time a name will be bound to some object, which will have a type; thus there is
dynamic typing.
 The if statement, which conditionally executes a block of code, along with else and
elif (a contraction of else-if).
 The for statement, which iterates over an iterable object, capturing each element to a
local variable for use by the attached block.
 The while statement, which executes a block of code as long as its condition is true.
 The try statement, which allows exceptions raised in its attached code block to be
caught and handled by except clauses; it also ensures that clean-up code in a
finally block will always be run regardless of how the block exits.
 The raise statement, used to raise a specified exception or re-raise a caught
exception.
 The class statement, which executes a block of code and attaches its local namespace
to a class, for use in object-oriented programming.
 The def statement, which defines a function or method.
 The with statement, from Python 2.5 released in September 2006, which encloses a
code block within a context manager (for example, acquiring a lock before the block
of code is run and releasing the lock afterwards, or opening a file and then closing it),
allowing Resource Acquisition Is Initialization (RAII)-like behavior and replaces a
common try/finally idiom.[68]
 The break statement, exits from the loop.
 The continue statement, skips this iteration and continues with the next item.
 The pass statement, which serves as a NOP. It is syntactically needed to create an
empty code block.
 The assert statement, used during debugging to check for conditions that ought to
apply.
 The yield statement, which returns a value from a generator function. From Python
2.5, yield is also an operator. This form is used to implement coroutines.
 The import statement, which is used to import modules whose functions or variables
can be used in the current program. There are three ways of using import: import
<module name> [as <alias>] or from <module name> import * or from

10
<module name> import <definition 1> [as <alias 1>], <definition 2>

[as <alias 2>], ....

 The print statement was changed to the print() function in Python 3.

Python does not support tail call optimization or first-class continuations, and,
according to Guido van Rossum, it never will. However, better support for coroutine-like
functionality is provided in 2.5, by extending Python's generators. Before 2.5, generators
were lazy iterators; information was passed unidirectionally out of the generator. From
Python 2.5, it is possible to pass information back into a generator function, and from Python
3.3, the information can be passed through multiple stack levels.

Libraries

Python's large standard library, commonly cited as one of its greatest strengths,[101]
provides tools suited to many tasks. For Internet-facing applications, many standard formats
and protocols such as MIME and HTTP are supported. It includes modules for creating
graphical user interfaces, connecting to relational databases, generating pseudorandom
numbers, arithmetic with arbitrary-precision decimals,[102] manipulating regular expressions,
and unit testing.

Some parts of the standard library are covered by specifications (for example, the
Web Server Gateway Interface (WSGI) implementation wsgiref follows PEP 333[103]), but
most modules are not. They are specified by their code, internal documentation, and test
suites. However, because most of the standard library is cross-platform Python code, only a
few modules need altering or rewriting for variant implementations.

As of November 2019, the Python Package Index (PyPI), the official repository for
third-party Python software, contains over 200,000 packages with a wide range of
functionality, including:

 Automation  Machine learning


 Data analytics  Mobile App
 Databases  Multimedia
 Documentation  Networking
 Graphical user interfaces  Scientific computing
 Image processing  System administration
11
 Test frameworks
 Text processing
 Web frameworks
 Web scraping

12
Cross-compilers to other languages

 Cython compiles Python to C and C++.


 Google's Grumpy compiles Python to Go.
 IronPython follows a similar approach in order to run Python programs on the .NET
Common Language Runtime.
 Jython enables the use of the Java class library from a Python program.
 MyHDL compiles Python to VHDL.
 Nuitka compiles Python into C++.
 Numba uses LLVM to compile Python to machine code.
 Pyjs compiles Python to JavaScript.
 Pyrex (latest release in 2010) and Shed Skin (latest release in 2013) compile to C and C++
respectively.
 Pythran compiles Python to C++.
 RPython can be compiled to C, and is used to build the PyPy interpreter of Python.

Languages influenced by Python

 Boo uses indentation, a similar syntax, and a similar object model.


 Cobra uses indentation and a similar syntax, and its Acknowledgements document lists
Python first among languages that influenced it.
 CoffeeScript, a programming language that cross-compiles to JavaScript, has Python-
inspired syntax.
 ECMAScript/JavaScript borrowed iterators and generators from Python.
 GDScript, a scripting language very similar to Python, built-in to the Godot game engine.
 Go is designed for the "speed of working in a dynamic language like Python" and shares
the same syntax for slicing arrays.
 Groovy was motivated by the desire to bring the Python design philosophy to Java.
 Julia was designed to be "as usable for general programming as Python".
 Nim uses indentation and a similar syntax.
 Ruby's creator, Yukihiro Matsumoto, has said: "I wanted a scripting language that was
more powerful than Perl, and more object-oriented than Python. That's why I decided to
design my own language."Swift, a programming language developed by Apple, has some
Python-inspired syntax.

13
BACK END

SQLite
INTRODUCTON
SQLite is a relational database management system contained in a C programming
library. In contrast to many other database management systems, SQLite is not a client–server
database engine. Rather, it is embedded into the end program.SQLite is ACID-compliant and
implements most of the SQL standard, using a dynamically and weakly typed SQL syntax
that does not guarantee the domain integrity.

DESIGN
Unlike client–server database management systems, the SQLite engine has no standalone
processes with which the application program communicates. Instead, the SQLite library is
linked in and thus becomes an integral part of the application program. The library can also
be called dynamically. Due to the server-less design, SQLite applications require fewer
configurations than client-server databases. SQLite is called zero-conf[7]because it does not
require service management (such as startup scripts) or access control based on GRANT and
passwords. Several computer processes or threads may access the same database
concurrently. Several read accesses can be satisfied in parallel. A write access can only be
satisfied if no other accesses are currently being serviced. Otherwise, the write access fails
with an error code (or can automatically be retried until a configurable timeout expires). This
concurrent access situation would change when dealing with temporary tables. This
restriction is relaxed in version 3.7 when write-ahead logging (WAL) is turned on enabling
concurrent reads and writes.

14
4. SYSTEM DESIGN
4.1 INPUT DESIGN
In the input design, user-oriented inputs are converted into a computer based system
format. It also includes determining the record media, method of input, speed of capture and
entry on to the screen. Online data entry accepts commands and data through a keyboard. The
major approach to input design is the menu and the prompt design. In each alternative, the user’s
options are predefined. The data flow diagram indicates logical data flow, data stores, source and
destination. Input data are collected and organized into a group of similar data. Once identified
input media are selected for processing.
In this software, importance is given to develop Graphical User Interface (GUI), which is
an important factor in developing efficient and user-friendly software. For inputting user data,
attractive forms are designed. User can also select desired options from the menu, which provides
all possible facilities.
Also the important input format is designed in such a way that accidental errors are
avoided. The user has to input only just the minimum data required, which also helps in avoiding
the errors that the users may make. Accurate designing of the input format is very important in
developing efficient software. The goal or input design is to make entry as easy, logical and free
from errors.

4.2 OUTPUT DESIGN


In the output design, the emphasis is on producing a hard copy of the information
requested or displaying the output on the CRT screen in a predetermined format. Two of the most
output media today are printers and the screen. Most users now access their reports from a hard
copy or screen display. Computer’s output is the most important and direct source of information
to the user, efficient, logical, output design should improve the systems relations with the user
and help in decision-making.
As the outputs are the most important source of information to the user, better design
should improve the system’s relation and also should help in decision-making. The output
device’s capability, print capability, print capability, response time requirements etc should also
be considered form design elaborates the way output is presented and layout available for
capturing information. It’s very helpful to produce the clear, accurate and speedy information for
end users.
15
4.3 DATABASE DESIGN

Database design is the process of producing a detailed data model of a database. logical
data model contains all the needed logical and physical design choices and physical storage
parameters needed a design in a Definition Language, Which can then be used to create a
database. A fully attributed data model contains detailed attributes for each entity.

4.4 DATA FLOW DIAGRAM


A Data Flow Diagram (DFD) is a diagram that describes the flow of data and the
processes that change data throughout a system. It’s a structured analysis and design tool that can
be used for flowcharting in place of or in association with information. Oriented and process
oriented system flowcharts. When analysts prepare the Data Flow Diagram, they specify the user
needs at a level of detail that virtually determines the information flow into and out of the system
and the required data resources. This network is constructed by using a set of symbols that do not
imply physical implementations. The Data Flow Diagram reviews the current physical system,
prepares input and output specification, specifies the implementation plan etc.
Four basic symbols are used to construct data flow diagrams. They are symbols that
represent data source, data flows, and data transformations and data storage. The points at which
data are transformed are represented by enclosed figures, usually circles, which are called nodes.
DATA FLOW DIAGRAM SYMBOLS:-

- Source or Destination of data

- Data Flow

- Process

- Storage

16
DATA FLOW DIAGRAMS

17
Level1 : Administrator

18
User

19
DATA DICTIONARY
4.1 DATABASE DESIGN (TABLE STRUCTURES)

20
21
22
SYSTEM SPECIFICATION
5.1 MODULES
MODULE DESCRIPTION
This DMS consists of mainly 5 modules. They are:

 Administrator
 Version control
 Registration
 User
 Search

Administrator

Administrator is the main module of this DMS. The main function of the administrator
is user approval. Administrator has full authority on this system. Administrator has the provision
for deleting the files. He can also provide function of maintain the category of different files.

Visual Source Control

It is another important module. The main function is to control the version of each and
every file. All the information about the files is stored in this module.

Registration
All types of users must be a registered user. In this module all the users are registering
and creating a folder to download the file and store in their directories.

User

Another important module is users. A special feature is only users can download or
upload files. For this purpose it provides a user authentication mechanism. Users are allowed
to create folders in their login. Users can implement various security measures on the files they
upload.

23
Search

In this module searching for a file is possible. The searching option can be done in two
ways. One is by filename and the other is metadata search.

24
6. SYSTEM IMPLEMENTATION

Implementation is the stage of the project when the theoretical design is turned into a
working system. Implementation means converting a new or revised system design into an
operational condition. In this project Bug Tracking maintains NPR Arts and Science College,
Dindigul, implementation includes all these activities that the place to convert the new system.
The purpose of test plan is preparing it helps us to think through the efforts needed to
validate the acceptability of a software product. It will help people outside the test group to
understand the why and how of product validation and regulated environments, we have to have a
written test plan. The general testing process includes the creation of a test plan .We want a
document that describes the objectives, scope, approach and focus of the software testing effort.
It includes test cases, conditions, the test environment, a list of related tasks, pass/fail criteria, and
risk assessment. One of the outputs for creating a test strategy is an approved and signed off test
plan document. The software testing methodology a three step process and one of the steps is the
creation of a test plan. We want an opportunity to review the test plan with the project team. Test
plans should be documented, so that they are repeatable.
The purpose of training is to ensure that all the personal who are associate with the system
should possess the basic knowledge and skills. The end user must know in detail what their rules
will be how they can use the system and what the system will or will not do before the
initialization of the training the programmer materials are prepared for the users with description.
The users are instructed first, how to operate the system. User training also instructs individuals
in trouble shooting system determining whether problem arise due to any system failure or
software failure or something that they had one in using the system. The system will be
implemented as soon as possible.

25
7. SYSTEM TESTING

Software testing is an important element of software quality assurance and represents the
ultimate review of specification, design and coding. It increasing visibility of software as a
system element and the costs associates with a software failure are motivating forces for all well
planned through testing .The system is tested with giving wrong information. Cascade deletion
and, the software developer checks updating. Testing and debugging are different activities, but
debugging must be accommodated in any testing strategy.

TYPES OF TESTING

UNIT TESTING
Unit testing is the important and major part of the project. So errors can be rectified easily
in each module and program clarity can be increased. In this project, the entire system is divided
into several modules and is developed individually. Hence, unit testing is conducted to individual
modules.

INTEGRATION TESTING
Integration testing is the systematic technique for constructing the program structure
while conducting tests to uncover errors associated with integrating. After the unit test, each
module is gradually integrated to form one final system. All the modules when unit tested will
work properly but after integrating the data can cause error one module can have an inadvertent,
adverse effect on another; sub functions when combined may not produce the desired major
function; global data structures can cause problems, etc. In this project the integration testing is
performed by combing login, civil registration and status modules are generated the report.

26
PERFORMANCE TESTING
A type of Physical test covering a wide range of engineering or functional evaluations
where a material, product, or system is not specified by detailed material or component
specifications: rather, emphasis is on the final measurable performance characteristics. Testing
can be a qualitative or quantitative procedure.

ACCEPTANCE TESTING

The User Acceptance testing focuses mainly on the functionality thereby validating the
fitness-for-use of the system by the business user. The user acceptance test is performed by the
users and application managers.

Test Results
All the test cases mentioned above passed successfully. No defects encountered.

27
8. CONCLUSION

The project entitled OFFICE DOCUMENT MANAGEMENT SYSTEM is done in an


effective manner. Document Management System is an efficient, time saving and easy way to
report, view and control the version of a file. All the operations are done efficiently. To use one,
start by registering a collection of source files that is, telling your DMS to start archive files
describing their change histories. Thereafter, when you want to edit one of these files, you
have to check out the file assert an exclusive lock on it. When you're done, you check in
the file, adding your changes to the archive, releasing the lock, and entering a change
comment explaining what you did.

28
9. FUTURE ENHANCEMENT

The following section discusses the work that will be implemented with future releases of
the software.
1. Detailed categories: Future work could involve adding more categories which are more
detailed and have additional items.
2. Watch/Wish List: Work can add a watch list or wish list so that users can add an item to a list
to watch for item prices to go down or to see when there is a sale on any of that items.
3. Enhanced User Interface: Work on enhancing the user interface by adding more user-
interactive features.
7. Recent History: Display the user’s recently browsed items in the recent-history tab

29
10. BIBILIOGRAPHY

Reference Books

 Python Crash Course. 'Python Crash Course' by Eric Matthews is a fast-paced and
comprehensive introduction to Python language for beginners who wish to learn Python
programming and write useful ...

 Automate the Boring Stuff with Python, 2nd Edition: Practical Programming for Total
Beginners. ...

 Learning Python, 5th Edition. The author of the book, Mark Lutz, gives a comprehensive,
in-depth introduction to the core Python language based on his training course.

 Head-First Python (2nd edition) Head-First Python by Paul Barry is the best book to learn
python, a quick and easy fix for you if you wish to learn the ...

 Elements of Programming Interviews in Python: The Insiders' Guide. The book


challenges you with a collection of 250 problems to test your Python skills

Reference Websites

 www.python.org

 www.microsoft.com

 www.codeproject.com

 www.programmersheaven.com

 www.w3schools.com

30
11. APPENDIX
SCREEN SHOTS

31
32
33
34
35
SOURCE CODE

from django import forms
from django.contrib.auth.forms import UserCreationForm,PasswordChangeForm, UserCh
angeForm

from django.contrib.auth.models import User
from .models import Post

class UserRegistration(UserCreationForm):
    email = forms.EmailField(max_length=250,help_text="The email field is require
d.")
    first_name = forms.CharField(max_length=250,help_text="The First Name field i
s required.")
    last_name = forms.CharField(max_length=250,help_text="The Last Name field is 
required.")

    class Meta:
        model = User
        fields = ('email', 'username', 'password1', 'password2', 'first_name', 'l
ast_name')
    

    def clean_email(self):
        email = self.cleaned_data['email']
        try:
            user = User.objects.get(email = email)
        except Exception as e:
            return email
        raise forms.ValidationError(f"The {user.email} mail is already exists/
taken")

    def clean_username(self):
        username = self.cleaned_data['username']
        try:
            user = User.objects.get(username = username)
        except Exception as e:
            return username
        raise forms.ValidationError(f"The {user.username} mail is already exists/
taken")

class UpdateProfile(UserChangeForm):
    username = forms.CharField(max_length=250,help_text="The Username field is re
quired.")
    email = forms.EmailField(max_length=250,help_text="The Email field is require
d.")
    first_name = forms.CharField(max_length=250,help_text="The First Name field i
s required.")

36
    last_name = forms.CharField(max_length=250,help_text="The Last Name field is 
required.")
    current_password = forms.CharField(max_length=250)

    class Meta:
        model = User
        fields = ('email', 'username','first_name', 'last_name')

    def clean_current_password(self):
        if not self.instance.check_password(self.cleaned_data['current_password']
):
            raise forms.ValidationError(f"Password is Incorrect")

    def clean_email(self):
        email = self.cleaned_data['email']
        try:
            user = User.objects.exclude(id=self.cleaned_data['id']).get(email = e
mail)
        except Exception as e:
            return email
        raise forms.ValidationError(f"The {user.email} mail is already exists/
taken")

    def clean_username(self):
        username = self.cleaned_data['username']
        try:
            user = User.objects.exclude(id=self.cleaned_data['id']).get(username 
= username)
        except Exception as e:
            return username
        raise forms.ValidationError(f"The {user.username} mail is already exists/
taken")

class UpdatePasswords(PasswordChangeForm):
    old_password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'for
m-control form-control-sm rounded-0'}), label="Old Password")
    new_password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'fo
rm-control form-control-sm rounded-0'}), label="New Password")
    new_password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'fo
rm-control form-control-sm rounded-0'}), label="Confirm New Password")
    class Meta:
        model = User
        fields = ('old_password','new_password1', 'new_password2')

class SavePost(forms.ModelForm):
    user = forms.IntegerField(help_text = "User Field is required.")
    title = forms.CharField(max_length=250,help_text = "Title Field is required."
)
    description = forms.Textarea()
37
    class Meta:
        model= Post
        fields = ('user','title','description','file_path')
    
    def clean_title(self):
        id = self.instance.id if not self.instance == None else 0
        try:
            if id.isnumeric():
                 post = Post.objects.exclude(id = id).get(title = self.cleaned_da
ta['title'])
            else:
                 post = Post.objects.get(title = self.cleaned_data['title'])
        except:
            return self.cleaned_data['title']
        raise forms.ValidationError(f'{post.title} post Already Exists.')

    def clean_user(self):
        user_id = self.cleaned_data['user']
        print("USER: "+ str(user_id))
        try:
            user = User.objects.get(id = user_id)
            return user
        except:
            raise forms.ValidationError("User ID is unrecognize.")

from turtle import title
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.urls import reverse
from cryptography.fernet import Fernet
from django.conf import settings
import base64, os
from django.dispatch import receiver

# Create your models here.

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=250)
    description = models.TextField(blank=True, null=True)
    file_path = models.FileField(upload_to='uploads/',blank=True, null=True)
    date_created = models.DateTimeField(default=timezone.now)
    date_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.user.username + '-' + self.title

38
    def get_share_url(self):
        fernet = Fernet(settings.ID_ENCRYPTION_KEY)
        value = fernet.encrypt(str(self.pk).encode())
        value = base64.urlsafe_b64encode(value).decode()
        return reverse("share-file-id", kwargs={"id": (value)})

@receiver(models.signals.post_delete, sender=Post)
def auto_delete_file_on_delete(sender, instance, **kwargs):
    if instance.file_path:
        if os.path.isfile(instance.file_path.path):
            os.remove(instance.file_path.path)

@receiver(models.signals.pre_save, sender=Post)
def auto_delete_file_on_change(sender, instance, **kwargs):
    if not instance.pk:
        return False

    try:
        old_file = sender.objects.get(pk=instance.pk).file_path
    except sender.DoesNotExist:
        return False

    new_file = instance.file_path
    if not old_file == new_file:
        if os.path.isfile(old_file.path):
            os.remove(old_file.path)
    
from django.contrib import admin
from django.urls import path
from django.conf.urls.static import static
from . import views
from django.contrib.auth import views as auth_views
from django.views.generic.base import RedirectView

urlpatterns = [
    path('redirect-admin', RedirectView.as_view(url="/admin"),name="redirect-
admin"),
    path('login',auth_views.LoginView.as_view(template_name="login.html",redirect
_authenticated_user = True),name='login'),
    path('userlogin', views.login_user, name="login-user"),
    path('user-register', views.registerUser, name="register-user"),
    path('logout',views.logoutuser,name='logout'),
    path('profile',views.profile,name='profile'),
    path('update-profile',views.update_profile,name='update-profile'),
    # path('update-avatar',views.update_avatar,name='update-avatar'),
    path('update-password',views.update_password,name='update-password'),
    path('', views.home, name='home-page'),
    path('my_posts', views.posts_mgt, name='posts-page'),
    path('manage_post', views.manage_post, name='manage-post'),
39
    path('manage_post/<int:pk>', views.manage_post, name='manage-post'),
    path('save_post', views.save_post, name='save-post'),
    path('delet_post', views.delete_post, name='delete-post'),
    path(r'shareF/<str:id>', views.shareF, name='share-file-id'),
    path('shareF/', views.shareF, name='share-file'),
]

from django.shortcuts import render,redirect
from django.contrib.auth import authenticate, login, logout, update_session_auth_
hash
from django.contrib.auth.decorators import login_required
from fms_django.settings import MEDIA_ROOT, MEDIA_URL
import json
from django.contrib import messages
from django.contrib.auth.models import User
from django.http import HttpResponse
from fmsApp.forms import UserRegistration, SavePost, UpdateProfile, UpdatePasswor
ds
from fmsApp.models import Post
from cryptography.fernet import Fernet
from django.conf import settings
import base64
# Create your views here.

context = {
    'page_title' : 'File Management System',
}
#login
def login_user(request):
    logout(request)
    resp = {"status":'failed','msg':''}
    username = ''
    password = ''
    if request.POST:
        username = request.POST['username']
        password = request.POST['password']

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                resp['status']='success'
            else:
                resp['msg'] = "Incorrect username or password"
        else:
            resp['msg'] = "Incorrect username or password"
    return HttpResponse(json.dumps(resp),content_type='application/json')

#Logout
40
def logoutuser(request):
    logout(request)
    return redirect('/')

@login_required
def home(request):
    context['page_title'] = 'Home'
    if request.user.is_superuser:
        posts = Post.objects.all()
    else:
        posts = Post.objects.filter(user = request.user).all()
    context['posts'] = posts
    context['postsLen'] = posts.count()
    print(request.build_absolute_uri())
    return render(request, 'home.html',context)

def registerUser(request):
    user = request.user
    if user.is_authenticated:
        return redirect('home-page')
    context['page_title'] = "Register User"
    if request.method == 'POST':
        data = request.POST
        form = UserRegistration(data)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            pwd = form.cleaned_data.get('password1')
            loginUser = authenticate(username= username, password = pwd)
            login(request, loginUser)
            return redirect('home-page')
        else:
            context['reg_form'] = form

    return render(request,'register.html',context)

@login_required
def profile(request):
    context['page_title'] = 'Profile'
    return render(request, 'profile.html',context)

@login_required
def posts_mgt(request):
    context['page_title'] = 'Uploads'

    posts = Post.objects.filter(user = request.user).order_by('title', '-
date_created').all()
    context['posts'] = posts
    return render(request, 'posts_mgt.html', context)
41
@login_required
def manage_post(request, pk=None):
    context['page_title'] = 'Manage Post'
    context['post'] = {}
    if not pk is None:
        post = Post.objects.get(id = pk)
        context['post'] = post
    return render(request,'manage_post.html',context)

@login_required
def save_post(request):
    resp = {'status':'failed', 'msg':''}
    if request.method == 'POST':
        if not request.POST['id'] == '':
            post = Post.objects.get(id=request.POST['id'])
            form = SavePost(request.POST,request.FILES,instance=post)
        else:
            form = SavePost(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            messages.success(request,'File has been saved successfully.')
            resp['status'] = 'success'
        else:
            for fields in form:
                for error in fields.errors:
                    resp['msg'] += str( error +'<br/>')
            form = SavePost(request.POST,request.FILES)
            
    else:
        resp['msg'] = "No Data sent."
    print(resp)
    return HttpResponse(json.dumps(resp),content_type="application/json")

@login_required
def delete_post(request):
    resp = {'status':'failed', 'msg':''}
    if request.method == 'POST':
        try:
            post = Post.objects.get(id = request.POST['id'])
            post.delete()
            resp['status'] = 'success'
            messages.success(request, 'Post has been deleted successfully')
        except:
           resp['msg'] = "Undefined Post ID"
    return HttpResponse(json.dumps(resp),content_type="application/json")

def shareF(request,id=None):
    # print(str("b'UdhnfelTxqj3q6BbPe7H86sfQnboSBzb0irm2atoFUw='").encode())
42
    context['page_title'] = 'Shared File'
    if not id is None:
        key = settings.ID_ENCRYPTION_KEY
        fernet = Fernet(key)
        id = base64.urlsafe_b64decode(id)
        id = fernet.decrypt(id).decode()
        post = Post.objects.get(id = id)
        context['post'] = post
        context['page_title'] += str(" - " + post.title)
   
    return render(request, 'share-file.html',context)

@login_required
def update_profile(request):
    context['page_title'] = 'Update Profile'
    user = User.objects.get(id = request.user.id)
    if not request.method == 'POST':
        form = UpdateProfile(instance=user)
        context['form'] = form
        print(form)
    else:
        form = UpdateProfile(request.POST, instance=user)
        if form.is_valid():
            form.save()
            messages.success(request, "Profile has been updated")
            return redirect("profile")
        else:
            context['form'] = form
            
    return render(request, 'manage_profile.html',context)

@login_required
def update_password(request):
    context['page_title'] = "Update Password"
    if request.method == 'POST':
        form = UpdatePasswords(user = request.user, data= request.POST)
        if form.is_valid():
            form.save()
            messages.success(request,"Your Account Password has been updated succ
essfully")
            update_session_auth_hash(request, form.user)
            return redirect("profile")
        else:
            context['form'] = form
    else:
        form = UpdatePasswords(request.POST)
        context['form'] = form
    return render(request,'update_password.html',context)

43
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys

def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fms_django.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

if __name__ == '__main__':
    main()

44

You might also like