Skip to content

Commit

Permalink
feat: initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
pradishb committed Dec 22, 2023
0 parents commit d149f22
Show file tree
Hide file tree
Showing 12 changed files with 458 additions and 0 deletions.
27 changes: 27 additions & 0 deletions .github/workflows/python-publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Upload Python Package
on:
push:
branches:
- release
permissions:
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v3
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install build
- name: Build package
run: python -m build
- name: Publish package
uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
with:
user: __token__
password: ${{ secrets.PYPI_API_TOKEN }}
136 changes: 136 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
.vscode

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/
dist

# example project
example/
example_app/
manage.py
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2018 The Python Packaging Authority

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 2 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
include LICENSE
include README.md
60 changes: 60 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# django-form-button

Django admin extra buttons with form

## Screenshots

![changelist](docs/changelist.png)

![form](docs/form.png)

## Installation

You can install the package via pip:

```bash
pip install django-form-button
```

## Usage

```python
from django.contrib import admin
from django.forms import FileField
from django.forms import Form
from django.http import HttpRequest
from django.http import HttpResponse

from django_form_button import FormButtonMixin
from django_form_button import form_button

from .models import Account


class UploadForm(Form):
file = FileField()


@form_button("Upload Accounts", UploadForm)
def upload_accounts(request: HttpRequest, validated_form: Form):
file = validated_form.cleaned_data["file"]
return HttpResponse(file.name)


@admin.register(Account)
class AccountAdmin(FormButtonMixin, admin.ModelAdmin): # type: ignore
form_buttons = [upload_accounts]

```

## License

This project is licensed under the terms of the MIT license.

## Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

## Contact

If you want to contact me you can reach me at [email protected].
5 changes: 5 additions & 0 deletions django_form_button/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django_form_button.decorators import button
from django_form_button.decorators import form_button
from django_form_button.mixins import FormButtonMixin

__all__ = ["button", "form_button", "FormButtonMixin"]
117 changes: 117 additions & 0 deletions django_form_button/decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
from functools import wraps
from typing import Callable
from typing import ParamSpec
from typing import Protocol
from typing import Type
from typing import TypeVar
from typing import cast

from django.contrib import admin
from django.forms import Form
from django.http import HttpRequest
from django.http import HttpResponse
from django.http.response import HttpResponseBase
from django.template import RequestContext
from django.template import Template

# https://github.com/microsoft/pylance-release/issues/3777
P = ParamSpec("P")
R = TypeVar("R", covariant=True)


class FuncWithAttrs(Protocol[P, R]):
def __call__(*args: P.args, **kwargs: P.kwargs) -> R: ...

title: str
name: str


def make_func_with_attrs(fn: Callable[P, R]) -> FuncWithAttrs[P, R]:
return cast(FuncWithAttrs[P, R], fn)


template = Template("""
{% extends "admin/base_site.html" %}
{% load admin_urls static l10n %}
{% block extrastyle %}
{{ block.super }}
<link rel="stylesheet"
type="text/css"
href="{% static "admin/css/forms.css" %}">
{% endblock %}
{% block content %}
<div id="content-main">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{% for obj in queryset.all %}<input type="hidden" name="_selected_action" value="{{ obj.pk|unlocalize }}"/>{% endfor %}
<div>
{% if form.errors %}<p class="errornote">Please correct the errors below.</p>{% endif %}
<fieldset class="module aligned wide">
{% for field in form %}
<div class="form-row">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% if field.help_text %}<div class="help">{{ field.help_text|safe }}</div>{% endif %}
</div>
{% endfor %}
</div>
</fieldset>
<div class="submit-row">
<input type="hidden" name="action" value="{{ action }}"/>
<input type="submit" name="submit" value="Submit" class="default" />
</div>
</form>
</div>
{% endblock %}
""")


def render_form(request: HttpRequest, form: Form, title: str):
context = {
"site_header": admin.site.site_header,
"site_title": admin.site.site_title,
"site_title": admin.site.site_title,
"title": title,
"form": form,
}
context = RequestContext(request, context)
return HttpResponse(template.render(context))


def form_button(title: str, form_cls: Type[Form]):
def decorator(func: Callable[[HttpRequest, Form], HttpResponseBase]):
@make_func_with_attrs
@wraps(func)
def wrapper(request: HttpRequest):
if request.POST.get("submit") is not None:
form = form_cls(request.POST, request.FILES)
if form.is_valid():
# success
return func(request, form)
# show form with errors
return render_form(request, form, title)
else:
# show an empty form
return render_form(request, form_cls(), title)

wrapper.title = title
wrapper.name = func.__name__
wrapper.__name__ = func.__name__
return wrapper

return decorator


def button(title: str):
def decorator(func: Callable[[HttpRequest], HttpResponseBase]):
@make_func_with_attrs
@wraps(func)
def wrapper(request: HttpRequest):
return func(request)

wrapper.title = title
wrapper.name = func.__name__
wrapper.__name__ = func.__name__
return wrapper

return decorator
Loading

0 comments on commit d149f22

Please sign in to comment.