brack3t / django-braces Goto Github PK
View Code? Open in Web Editor NEWReusable, generic mixins for Django
Home Page: http://django-braces.readthedocs.org/en/latest/index.html
License: BSD 3-Clause "New" or "Revised" License
Reusable, generic mixins for Django
Home Page: http://django-braces.readthedocs.org/en/latest/index.html
License: BSD 3-Clause "New" or "Revised" License
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.
A few notes I took while I was working on this pull request: #30
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.
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.
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"]
The docs for this mixin were never updated from the client code this came out of so it doesn't make as much sense in a public context.
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.
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.
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__})
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])
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.
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.
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.
Should provide doc pages for different categories of mixins.
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.
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
.
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?
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 JSONResponseMixin
s.
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).
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.
setup.py says the package is BSD, but there isn't a formal license file I can find in the package.
Because sometimes you have to hit another domain.
Right now I'm using CORS but would like to support JSONP.
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.
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")
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?
Considering https://docs.djangoproject.com/en/1.6/topics/db/transactions/, it would be nice to have something like:
from bracers.views import TransactionMixin
class FunUpdateView(TransactionMixin, UpdateView):
model = Article
Need to create a new object that contains the existing functionality with appropriate object-finding, a la https://github.com/django/django/blob/stable/1.4.x/django/views/generic/detail.py#L19.
Then, possibly, provide one new view, SaveAndContinueEditingView, that encapsulates the functionality with existing view classes like UpdateView and CreateView.
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.
We need one. Detail how to run the tests and what we expect submitted code to look like.
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)
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.
Use Django's serializer to better be able to handle models, etc.
https://docs.djangoproject.com/en/dev/topics/serialization/
Might also look into doing and XMLResponseMixin, too.
When GroupRequiredMixin is used on a view, the superuser is blocked.
We need to update the Change Log for the 1.2 release.
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.
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.
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)
For JSONResponseMixin
and the like.
Right rtfd says you're on 0.2.3
๐ฑ
Hello!
get_group_required method raises NameError: name 'unicode' is not defined when running isinstance(self.group_required,(str, unicode, list, tuple))
Michal
We keep telling people we have a JSONResponseMixin and we don't so we probably should have.
The CreateAndRedirectToEditView
has been deprecated since v1.0. A 1.3 release should finally remove this.
The lack of tests makes this package harder to advocate.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.