django class-based views with inline model-form or formset

Key points is: generated FormSets within forms.py using inlineformset_factory: BookImageFormSet = inlineformset_factory(BookForm, BookImage, extra=2) BookPageFormSet = inlineformset_factory(BookForm, BookPage, extra=5) returned the FormSets within a CreateView class in views.py: def get_context_data(self, **kwargs): context = super(BookCreateView, self).get_context_data(**kwargs) if self.request.POST: context[‘bookimage_form’] = BookImageFormSet(self.request.POST) context[‘bookpage_form’] = BookPageFormSet(self.request.POST) else: context[‘bookimage_form’] = BookImageFormSet() context[‘bookpage_form’] = BookPageFormSet() return context Used form_valid to … Read more

Example of Django Class-Based DeleteView

Here’s a simple one: from django.views.generic import DeleteView from django.http import Http404 class MyDeleteView(DeleteView): def get_object(self, queryset=None): “”” Hook to ensure object is owned by request.user. “”” obj = super(MyDeleteView, self).get_object() if not obj.owner == self.request.user: raise Http404 return obj Caveats: The DeleteView won’t delete on GET requests; this is your opportunity to provide a … Read more

How does the order of mixins affect the derived class?

The MRO is basically depth-first, left-to-right. See Method Resolution Order (MRO) in new style Python classes for some more info. You can look at the __mro__ attribute of the class to check, but FooMixin should be first if you want to do “check A” first. class UltimateBase(object): def dispatch(self, *args, **kwargs): print ‘base dispatch’ class … Read more

is not JSON serializable

simplejson and json don’t work with django objects well. Django’s built-in serializers can only serialize querysets filled with django objects: data = serializers.serialize(‘json’, self.get_queryset()) return HttpResponse(data, content_type=”application/json”) In your case, self.get_queryset() contains a mix of django objects and dicts inside. One option is to get rid of model instances in the self.get_queryset() and replace them … Read more

How to use permission_required decorators on django class-based views

There are a few strategies listed in the CBV docs: Decorate the view when you instantiate it in your urls.py (docs) from django.contrib.auth.decorators import login_required urlpatterns = [ path(‘view/’,login_required(ViewSpaceIndex.as_view(..)), … ] The decorator is applied on a per-instance basis, so you can add it or remove it in different urls.py routes as needed. Decorate your … Read more

tech