I'm rewriting my django function view to class based views. I have this current function
#login_required
def settings(request, template_name="settings.html"):
context = {}
context['kcs'] = KlarnaProfile.objects.filter(user_profile__user=request.user)
context['extends'] = ExtendProfile.objects.filter(user_profile__user=request.user)
context['fortnoxs'] = FortnoxProfile.objects.filter(user_profile__user=request.user)
return render(request, template_name, context)
that confirms first if a user is logged in and then get's information linked to that user account
here's what I've got as my class based view
class SettingsView(TemplateView):
template_name = "settings.html"
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
how can I add the three filters that use the logged in user as a filter?
Use get_context_data method like this:
class SettingsView(TemplateView):
...
def get_context_data(self, **kwargs):
context_data = super().get_context_data(**kwargs)
context_data['kcs'] = KlarnaProfile.objects.filter(user_profile__user=self.request.user)
...
return context_data
Neat pick. Instead of doing:
class SettingsView(TemplateView):
...
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
You can do:
#method_decorator(login_required, name='dispatch')
class SettingsView(TemplateView):
...
You might want to read Decorating the class from Django's official documentation.
Related
I am trying to build CBV with class View parent. This view takes slug of object and find that object between two django models. The functions from services.py was doing a lot of DB queries, so, I tried to reduce them by giving to FeedbackSection necessary attributes(slug, model_instance and context) and lately override them in get method.
class FeedbackSection(View):
"""
Feedback section for different objects.
This is something like 'generic' view, so I implement it that it will find
the model and feedbacks for this model by having only slug.
"""
template_name = 'feedbacks/feedback-section.html'
form_class = CreateFeedbackForm
slug = None
model_instance = None
context = None
def get(self, request, *args, **kwargs):
self.slug = kwargs.get('slug')
self.model_instance = get_model_instance(self.slug)
self.context = get_feedback_section_context(self.slug, self.form_class, self.model_instance)
return render(request, self.template_name, self.context)
#method_decorator(login_required)
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
# will create feedback object and update model[Advert, Company] rating.
end_feedback_post_logic(self.request.user, form, self.model_instance)
return render(request, self.template_name, self.context)
The attributes(slug, model_instance and context), when post method is in runtime are equivalent to None.
The problem is that this implementation was working fine yesterday, but today it's not.
I know I can use my functions again, but in post method. I don't want to do this. Because it will multiple DB Queries by two.
We need to override the setup method of the View class and define those attributes there.
def setup(self, request, *args, **kwargs):
self.slug = kwargs.get('slug')
self.model_instance = get_model_instance(self.slug)
self.context = get_feedback_section_context(
self.slug,
self.form_class,
self.model_instance
)
return super().setup(request, *args, **kwargs)
I want to switch between two models depending on which route I am in.
I am overwriting get_queryset() function to return the correct model:
class DynamicModelView(TemplateView, PageDescriptionListingMixin):
model = None
template_name = 'dynamic_model.html'
context_object_name = "accounts"
def get_context_data(self, **kwargs):
context = super(DynamicModelView, self).get_context_data(**kwargs)
self.add_page_text_to_context(context)
return context
def get_queryset(self):
if '/dynamic_user/' in self.request.path:
model = UserAccount
else:
model = AdminAccount
return model.objects.first()
As you can see in get_context_data I am injecting an object in context for AdminAccount but inside template I can't see it! in fact if I changed model from None to AdminAccount then it appears which I want that to happen dynamically.
Is there any way to switch models dynamically in Django?
override dispatch method.
def dispatch(self, request, *args, **kwargs):
if not self.model:
self.model = <MODEL>
return super(DynamicModelView, self).dispatch(request, *args, **kwargs)
I'm rewriting my function to class based views, this is the function I currently have.
#login_required
def invoice(request, invoice_no, template_name="invoice.html"):
context = {}
invoice_exists = Invoice.objects.filter(invoice_no=invoice_no)
if invoice_exists:
context['invoice'] = invoice_exists.first()
else:
return HttpResponseRedirect(reverse('invoices'))
return render(request, template_name, context)
you have to be logged in, it filters using a filter named invoice_no
path('invoice/<int:invoice_no>', views.InvoiceView.as_view(), name="invoice"),
and if a match is found returns it, if not redirects you back to the invoices page.
this is what I have as a class
class InvoiceView(DetailView):
queryset = Invoice.objects.all()
context_object_name = 'invoice'
pk_url_kwarg = 'invoice_no'
template_name = "invoice.html"
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def get_object(self):
obj = super().get_object()
return obj
also the get object or 404 will do also since all it needs is a 404 page and it'll work.
Try this:
class ArticleDetailView(LoginRequiredMixin, DetailView):
template_name = "invoice.html"
context_object_name = 'invoice'
model = Invoice
def dispatch(self, request, *args, **kwargs):
try:
return super().dispatch(request, *args, **kwargs)
except Invoice.DoesNotExist:
return HttpResponseRedirect(reverse('invoices'))
def get_object(self):
return Invoice.objects.get(invoice_no=self.kwargs['invoice_no'])
Adjust according to your code.
from django.contrib.auth.mixins import LoginRequiredMixin
class InvoiceView(LoginRequiredMixin, DetailView):
template_name = "invoice.html"
context_object_name = 'invoice'
def get_queryset(self, *args, **kwargs):
invoice = get_object_or_404(Invoice, invoice_no=kwargs['invoice_no'])
return invoice
This will however return a 404 page if no data is found, if you like it to redirect it to invoices page, use a filter. Then use an IF statement to compare length > 0, if 0 then just redirect to page. Might as well put a message error then too.
I noticed that I am setting site-wide context variables and request variables for many views on my site. Naturally, this situation calls for inheritance. If all of my view class-based views are inheriting from SiteView instead of the generic View, I can factor out all the commonalities into the SiteView child class. I can then inherit from SiteView on all my views. But, I cannot get this to work. Here is my code:
from django.contrib.auth.decorators import login_required
from django.views.generic import View
from django.utils.decorators import method_decorator
class SiteView(View):
''' Extends the generic django-supplied View class '''
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(SiteView, self).dispatch(*args, **kwargs)
def get(self, *args, **kwargs):
''' Adds the variables required in the get request '''
context = super(SiteView, self).get(*args, **kwargs)
context['common_var'] = 'some common value'
context['user'] = request.user
return self.render_to_response(context)
This throws the following TypeError:
dispatch() missing 1 required positional argument: 'request'
Any help would be appreciated
Edit: Even though the correct answer is marked, there were other issues with the code. In particular, the get method of the SiteView should not have the following line:
context = super(SiteView, self).get(*args, **kwargs)
This is because the View class does NOT have any get method.
You forgot to pass the request to the super().dispatch(..) call:
class SiteView(View):
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(SiteView, self).dispatch(request, *args, **kwargs)
or you can just omit the request in the dispatch parameters, and thus pass it through *args and **kwargs:
class SiteView(View):
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(SiteView, self).dispatch(*args, **kwargs)
It is however probably more elegant, to pass the name of the function, like:
#method_decorator(login_required, name='dispatch')
class SiteView(View):
# ...
EDIT: Note that a View has no get(..), post(..), etc. method. The dispatch(..) method will look if such method exists, and if so redirect to it. If such method does not exists, it will return a "405 Method Not Allowed" response.
Your get(..) function thus be implemented like:
#method_decorator(login_required, name='dispatch')
class SiteView(View):
''' Extends the generic django-supplied View class '''
def render_to_response(self, context):
# ...
def get(self, request, *args, **kwargs):
context = {
'common_var': 'some common value',
'user': request.user
}
return self.render_to_response(context)
It perhaps makes more sense to implement a "mixin" (perhaps with a subclass of the LoginRequiredMixin mixin [Django-doc].
For example like:
class SiteViewMixin(LoginRequiredMixin):
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context.update(common_var='some common value', user=self.request.user)
return context
and then use the mixin in another view, like:
class SomeView(SiteViewMixin, TemplateView):
# ...
I am trying to add the decorator #xframe_options_exempt into a django template view but it complais with a
Exception Value: 'dict' object has no attribute
'xframe_options_exempt'
I noticed in Django 1.9 docs the decorator is used for views with a request parameter and I am using a TemplateView.
Is it possible to use it like this?
class MyView(TemplateView):
"""
"""
template_name = 'app/template.html'
from django.views.decorators.clickjacking import xframe_options_exempt
#xframe_options_exempt
def get_context_data(self, **kwargs):
context = {}
context['test'] = 'hello'
return context
Basically I need to embed a django template view into an iframe
When you are decorating class based views, you should use method_decorator. You should override a method that takes the request as an argument, e.g. dispatch (will apply to all request types) or get (will apply to get requests but not post requests). As you found, decorating get_context_data will not work.
class MyView(TemplateView):
#method_decorator(xframe_options_exempt):
def dispatch(self, *args, **kwargs):
return super(MyView, self).dispatch(*args, **kwargs)
Note that by using super() you don't have to duplicate the code from TemplateView.
You can decorate the class if you prefer (Django 1.9+)
#method_decorator(xframe_options_exempt, name='dispatch')
class ProtectedView(TemplateView):
template_name = 'secret.html'
Based on the available #xframe_options_exempt decorator, you can also implement a mixin class to be mixed into your view classes:
class XFrameOptionsExemptMixin:
#xframe_options_exempt
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
class SomeView(XFrameOptionsExemptMixin, TemplateView):
…
Well, if anyone else has this problem, this decorator cannot be applied to get_context_data method, but you can override the get method from the TemplateView, something like this:
class MyView(TemplateView):
"""
"""
template_name = 'app/template.html'
from django.views.decorators.clickjacking import xframe_options_exempt
#xframe_options_exempt
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
context = {}
context['test'] = 'hello'
return context
And this will do the trick