Giter Site home page Giter Site logo

brack3t / django-braces Goto Github PK

View Code? Open in Web Editor NEW
1.9K 1.9K 218.0 8.6 MB

Reusable, generic mixins for Django

Home Page: http://django-braces.readthedocs.org/en/latest/index.html

License: BSD 3-Clause "New" or "Revised" License

Python 99.87% HTML 0.13%
cbv cbvs class-based django django-braces python views

django-braces's Introduction

django-braces

django-braces provides useful Mixins for Django's class-based views. Most of these mixins replicate the behavior of Django's function-based view decorators. Others solve common headaches with working with class-based views. You can read more in the documentation.

Build PyPI version codecov

Notes

django-braces is stable and time-tested. It does not receive a lot of updates and is not in active development.

django-braces also only officially supports Python version that are still receiving fixes and Django LTS versions. django-braces will work with most modern version of Python and Django, however.

Installation

Install from PyPI with pip: pip install django-braces

Contributing

See our contribution guide

Add yourself to CONTRIBUTORS.txt if you want.

All development dependencies are available in requirements.txt file.

To run the test suite, please install pytest and run pytest at the root of the repository.

Change Log

Changelog on Read The Docs

django-braces's People

Contributors

andrius-senulis avatar blueyed avatar bmispelon avatar chancez avatar chrisjones-brack3t avatar cornmander avatar dmpayton avatar drewtempelmeyer avatar esoergel avatar ezegolub avatar fladi avatar folz avatar galuszkak avatar hanneshapke avatar jayvdb avatar jefftriplett avatar jleclanche avatar joehybird avatar jp26jp avatar keimlink avatar kennethlove avatar legostormtroopr avatar luzfcb avatar michael-k avatar petrdlouhy avatar piotrkilczuk avatar pydanny avatar rafales avatar ragsagar avatar shabda avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-braces's Issues

Publish tags on github

By default git doesn't push the tags, but it would be really nice if you did. Using git push --tags it should work but recent git versions also have --follow-tags to push annotated tags that are also in the branch(es) you're pushing.

JSONResponseMixin overrides the content_type of TemplateView in Django 1.6

This happens because of django/django@23e319d it effectively means that TemplateView and JSONResponseMixin doesn't.. well.. mix.

I would suggest renaming content_type -> content_type_json, get_content_type -> get_content_type_json which would make it consistent with the names of the other methods. But that change would need a deprecation policy, so a design decision is needed. :)

For those of you that want to do this anyways, you can get away with this:

from braces.views import JSONResponseMixin as BracesJSONResponseMixin
class JSONResponseMixin(BracesJSONResponseMixin)
    content_type = None
    def get_content_type(self):
        return 'application/json'

Then just swap out your JSONResponseMixins.

ImproperlyConfigured errors should use the offending classes name

Anywhere we raise ImproperlyConfigured, we should be using the offending classes name rather than hardcoding the mixin name.

raise ImproperlyConfigured(
    "%(cls)s is missing a succes_list_url "
    "name to reverse and redirect to. Define "
    "%(cls)s.success_list_url or override "
    "%(cls)s.get_success_url()"
    "." % {"cls": self.__class__.__name__})

Add check_membership method to GroupRequiredMixin

Add a check_membership method to the GroupRequiredMixin. Standard Django group checking would be done in this method.

Users who do not use Django's standard group permissions system could override check_membership to implement their own logic to check for "group" status. Alleviates the need to override dispatch.

Required GET/POST parameters

Hy,

Could be nice have a mixing that allows to define required and not required params that could be on GET/POST request and make the asignation to the class object.

get_params = ["date_start", "date_end"]
get_required_params = ["activity"]

post_....

And then you can acces them with the instance could be somthing like that:

get_param_default_value = None
get_required_params = ["desde", "hasta", ]
get_params = ["dia", "jajaj"]

def init_get_params(self, request):
'''
Inicializte the get params
'''
if hasattr(self, "get_params"):
# get params
for param in self.get_params:
setattr(self,
param,
request.GET.get(param, self.get_param_default_value))

if hasattr(self, "get_required_params"):
    # get required params
    for param in self.get_required_params:
        if param not in request.GET:
            raise Http404
        else:
            setattr(self, param, request.GET[param])

Multiple permission support for PermissionRequiredMixin

Hi there,

Does it make sense to allow permission_required in PermissionRequiredMixin to be a list of permissions? For example:

class SomeView(PermissionRequiredMixin, ListView):
    ...
    permission_required = ["app.permission", "app.permission2"]

GroupRequiredMixin

Just a mixin to assert that the current request's user is part of a selected group. Should accept a string or a list. List would imply ANY, not ALL, unless we want to provide a switch for that.

SSLRequiredMixin

I would like to request that an SSLRequiredMixin be created. I have the basics of one right now. It is a modification of https://gist.github.com/drewtempelmeyer/4669799. However, I am not sure if this is a good idea or even secure. It does work. I figured that if it was in the Braces package it would be more likely to get attention from people who know what's up. Code below:

class SSLRequiredMixin(object):

    def dispatch(self, request, *args, **kwargs):
        # SSL, Debug, and Post don't mix!
        if not settings.DEBUG and not request.is_secure():
            host = request.get_host()
            url = 'https://{0}{1}'.format(host, request.get_full_path())
            return redirect(url)
        return super(SSLRequiredMixin, self).dispatch(request, *args, **kwargs)

Django <1.5 compatibility

In 8431b0f force_text is used, which is a Django 1.5 function. Would it be possible to use smart_text instead? And why didn't the unit tests spot this?

A few notes I took while I was writing tests

A few notes I took while I was working on this pull request: #30

  • LoginRequiredMixin should have same features as the rest of "access" mixins (StaffuserRequiredMixin, PermissionRequiredMixin) - raise_exception, custom login url etc.
  • Mixins check if permission names contain dot. This is reasonable for default authentication backend but someone may provide custom permissions named differently (or provide custom has_perm method for user in django 1.5)
  • SuccessURLRedirectListMixin should use success_url_name attribute instead of success_list_url (to be consistent with other mixins)
  • SuccessURLRedirectListMixin should raise ImproperlyConfigured exception if success_list_url is not defined

FYI: Alternative JSON serialization method

Not sure if this is related to #11, but thought you guys might be interested.

I've come up with an encoder class for use with json.dumps(), and so far it seems to be able to crunch through model objects and query sets without any major issues. It's a bit of a hack, though, so be careful. :)

Check out the gist for the actual code.

There are still a few bugs in there related to handling of related objects and such (defunct as of this posting).

For rationale behind this: I didn't quite like the way serializers.serialize includes all kinds of info in the final JSON that shouldn't be needed by the client under any circumstances (e.g., model class).

OrderableListMixin and querysets

Hi there, thanks for all the work for this time saver. I was recently toying around with using the OrderableListMixin and wanted to see if I could get my existing ListViews to work with it.

class ImageListView(LoginRequiredMixin, NeverCacheMixin, OrderableListMixin, ListView):
    template_name = 'cilia/image_browse.html'
    context_object_name = 'images'
    orderable_columns = ('created',)
    orderable_columns_default = 'created'

    # TODO: Not working properly yet for sorting, mixin occurs first
    def get_queryset(self):
        queryset = Image.objects.for_user(self.request.user)
        return queryset

I believe that the design of the mixin was such that you specify a model for the ListView for it to work. It works beautifully if I use model = Image instead of the get_queryset method that I created. Any work around for this? Thanks.

Classifiers in setup.py

Could you add those classifiers to setup.py ?

Programming Language :: Python :: 2.6
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3.2
Programming Language :: Python :: 3.3

This will tell pypi that package supports python 3. I forgot about it in my tests pull request.

AccessMixin's login_url should not be set on module import time

AccessMixin.login_url is a regular attribute which is set when the module is imported. Because settings.LOGIN_URL might change during runtime (for instance during testing with the @override_settings decorator) it should be defined dynamically.

I'm trying to submit a pull request later unless someone else is willing to do this.

AllVerbsMixin

Mixin to cause a view to respond to all verbs with one method, likely like:

class MyView(AllVerbsMixin, View):
    def all(self, request, *args, **kwargs):
        return HttpResponse('hi there')

The reason for having such a mixin is to make CBVs replicate the functionality of FBVs, in that they response equally to all HTTP verbs out of the box.

Delete Multiple View (feature)

There are many requests on the web for DeleteMultiple mixin which would let users delete objects from ListView View by selecting checkboxes. Couldn't find one on the net and as I see some users use forms with MultipleSelect.. and others use request.POST.getlist().

Think this would be a great feature.

Rename raise_exception attribute to more informative one

Seeing this attribute on a view now is quite confusing. Looking at the code it is not clear what exception this attribute toggles, especially in case there are few base classes or mixins involved. I may imagine such generic name may clash with other methods or attributes from other base classes/mixins.
I propose rename raise_exception to access_exception as it only applies to the AccessMixin bahavoir.

Needs tests

The lack of tests makes this package harder to advocate.

JSONResponseMixin

We keep telling people we have a JSONResponseMixin and we don't so we probably should have.

SuccessMessageMixin and FailureMessageMixin

Two mixins to allow success_message and failure_message class attributes on any view that is derived from FormView. Should also have get_success_message and get_failure_message methods.

No "official" license

setup.py says the package is BSD, but there isn't a formal license file I can find in the package.

Potential mixin contributions - sortable-listview & spreadsheet-response

Hi lovely django-braces people, hope this is the right place for this, I wasn't sure how best to reach you otherwise. Am a huge fan of braces, use it a lot.

I have two mixins which I'm wondering whether you might be interested in. If so, I'd be delighted to do the work to get them fit for braces, they already have some tests, but not python 3 etc..

django-spreadsheetresponsemixin - https://github.com/birdsarah/django-spreadsheetresponsemixin
Renders views that have a queryset e.g. a ListView, into an excel spreadsheet or a CSV. Takes headers from model or you can customize them. Can specify fields and order columns by doing so. Maybe you don't want to rely on additional libraries, so maybe just the CSV portion would be interesting.

django-sortable-listview - https://github.com/aptivate/django-sortable-listview
Like OrderableListMixin but takes things a bit further, for example, if you're already sorted in one direction it'll provide context data so that the next sort can be in the opposite direction. Obviously, would be happy to pull out specific features and add them to the existing OrderableListMixin.

Thanks in advance for your thoughts.

CONTRIBUTING.txt

We need one. Detail how to run the tests and what we expect submitted code to look like.

How do you actually use post_ajax()?

There's no documentation on this and there are no tests that I saw. There's also no hits on Google or SO and no one knows on IRC.

How would you convert this to using braces?
https://docs.djangoproject.com/en/1.6/topics/class-based-views/generic-editing/#ajax-example

If I do something like this:

class FooCreate(AjaxResponseMixin, CreateView):
    model = Foo
    success_url = reverse_lazy('foos:list')

    def post_ajax(self, request, *args, **kwargs):
        data = {
            'foo': {
                'pk': self.object.pk,
                'first_name': self.object.first_name,
                'last_name': self.object.last_name,
            },
        }

        return self.render(request, "foos/_as_single_tr.html", data)

Then it crashes saying self.object does not exist.

Deprecation policy

django-braces 1.4 will be the last version of django-braces to officially support Django 1.4.

In the future, django-braces will only officially support one version back of Django. We'll do our best to support as far back as feasibly possible and to support the upcoming version.

SuperUserOrLoggedInUserRequiredMixin

For use cases such as editing a user profile which can only be editted by the user themselves or a "superuser".

from braces.views._access import AccessMixin

class SuperUserOrLoggedInUserRequiredMixin(AccessMixin):
    """
    View mixin that verifies that the user is a superuser
    or a logged in user that is the owner of the object.
    Extends django-braces AccessMixin
    """
    def dispatch(self, request, *args, **kwargs):
        obj = self.get_object()
        if not request.user.is_superuser and request.user.id != obj.id:
            if self.raise_exception:
                return PermissionDenied
            else:
                return redirect_to_login(request.get_full_path(),
                    self.get_login_url(),
                    self.get_redirect_field_name())

        return super(SuperUserOrLoggedInUserRequiredMixin, self).dispatch(request, *args, **kwargs)

String/Unicode type check raises an error when using ugettext_lazy

Checking form_valid_message and form_invalid_message type is incompatible with i18n framework when using ugettext_lazy.

The example below will raise an error because the type of form_valid_message is not either string or unicode. However the code is correct. Moreover, it is the most appropriate (and fastest) way to handle translation in that place.

from django.utils.translation import ugettext_lazy as _

class my_view(FormValidMessageMixin, TemplateView):
    form_valid_message = _("The form is valid")

class ProtectedView(LoginRequiredMixin, PermissionRequiredMixin, View)

when i want to protect a view using the above mentioned access mixins, setting the attribute raise_exception = True, if the user is not logged in, ie. AnonymousUser, the LoginRequiredMixin raises a PermissionDenied exception. I've checked the codes and shouldn't "if self.raise_exception: raise PermissionDenied" come after the if user.is_authenticated condition statement?

Login required without exception, permission required with

I require the functionality to create a view that redirects to the login page if the user is not logged in, but raises an exception if they are but do not have the correct permissions. In vanilla Django, I'd do the following:

@login_required
@permission_required('my_permission', raise_exception=True)
def my_view(request):
    pass

Doing this using the LoginRequiredMixin and the PermissionRequiredMixin is impossible, as they both use the same raise_exception class-level variable.

This would apply to the MultiplePermissionsRequiredMixin also.

reverse_lazy in LoginRequiredMixin

Hello!
It seems to me that it is not possible to assign reverse_lazy proxy object to class attribute login_url:

class MainMenuView(LoginRequiredMixin, TemplateView):
    template_name = 'administration/main_menu.html'
    login_url = reverse_lazy('administration:login')

Since I don't want to hardcode the login URL I have to use:

    def get_login_url(self):
        return reverse('administration:login')

Would it be possible to change it?
M.

How do I respond to a cross domain AJAX request, using django-braces?

I am able to write a custom AJAX response without braces, that works cross domain (in response to an AJAX request). I added allow domain, allow credentials headers to the response from my nginx server.

However, the class based view from braces don't seem to work.

Can you show an example implementation of how this can be accomplished? Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.