Use variable with TemplateView - python

I used to have my pages in Django defined with functions like this:
def pdf(request):
return render(request, 'blog/pdf.html', {'title': 'PDF files'})
Where I was using a Title var for html page title. I started to use a TemplateView class for my pages and I'm not sure how to use the same title inside of something like this:
class About(LoginRequiredMixin, TemplateView):
template_name = 'blog/about.html'

Try this,
class About(LoginRequiredMixin, TemplateView):
template_name = 'blog/about.html'
def get_context_data(self, *args, **kwargs):
context = super(About, self).get_context_data(*args, **kwargs)
context['title'] = 'PDF files'
return context

Related

Inspect response when i use a view Class-based views - Django

I need to inspect the response for know the params of pagination. I try used Pdb but the application stops. I think to overwrite some method like def dispatch(self, request, *args, **kwargs): but i don't know if the best way, someone could guide me ?
class PostsFeedView(LoginRequiredMixin, ListView):
template_name = 'posts.html'
model = Post
ordering = ('-created',)
paginate_by = 10
context_object_name = 'posts'
# import pdb; pdb.set_trace()
You can override get:
class PostsFeedView(LoginRequiredMixin, ListView):
...
def get(self, *args, **kwargs):
response = super().get(*args, **kwargs)
import pdb; pdb.set_trace()
return response

Problem with mixing Detail View and Form Mixin django

I am trying to create a comment system for the blog portion of my app with Django. I have attempted to mix my detail view with the form mixin and I'm struggling a bit. When the form is submitted, it doesn't save and no error is present. If any of you can help I would greatly appreciate it.
Here is my View
class DetailPostView(FormMixin, DetailView):
model = Post
template_name = "blog/post_detail.html"
context_object_name = "posts"
form_class = CommentForm
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["form"] = CommentForm
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def get_success_url(self):
return reverse("post-detail", kwargs={"pk": self.object.pk})
The model
class Comment(models.Model):
comment = models.ForeignKey(Post, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
content = models.TextField()
author = models.CharField(max_length=50)
created_on = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["-created_on"]
def __str__(self):
return self.title
The reason that this happens is because you construct a new form that you pass to the context data, as a result, it will not render any errors, since you construct a form without validating the request data and render that form, you thus do not display the form that rejected the data in the first place.
But you do not need to do that. Django's FormMixin [Django-doc] already takes care of that. You thus should not override the .get_context_data(…) method [Django-doc].
Another problem is that you did not save your form, you can override a the form_valid method, or you can inherit from ModelFormMixin [Django-doc].
Finally you better first create the form, and then assign self.object, otherwise it will pass this as an instance to the form:
from django.views.generic.edit import ModelFormMixin
class DetailPostView(ModelFormMixin, DetailView):
model = Post
template_name = 'blog/post_detail.html'
context_object_name = 'posts'
form_class = CommentForm
# no get_context_data override
def post(self, request, *args, **kwargs):
# first construct the form to avoid using it as instance
form = self.get_form()
self.object = self.get_object()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def get_success_url(self):
return reverse('post-detail', kwargs={'pk': self.object.pk})

django-filter according to the logged user

I am using the django_filters to filtering the information. However, it is showing the data of all regitered user of my system. I need show only the data of logged user.
Follow the files:
filters.py
import django_filters
from apps.requisitos.models import Requisito
class RequisitoFilter(django_filters.FilterSet):
class Meta:
model = Requisito
fields = ['nomeRequisito', 'projeto']
views.py
class RequisitoList(ListView):
paginate_by = 10
model = Requisito
def get_queryset(self):
usuarioLogado = self.request.user
return Requisito.objects.filter(user=usuarioLogado)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['filter'] = RequisitoFilter(self.request.GET, queryset=self.queryset)
return context
the loop for of html page
{% for requisito in filter.qs %}
thank you very much
You need to pass the result of get_queryset to the queryset parameter:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['filter'] = RequisitoFilter(
self.request.GET,
queryset=self.get_queryset()
)
return context
Note: You might want to consider using a FilterView [GitHub],
this view implements most of the ListView [Django-doc],
and encapsulates logic to use a filter_class.

How do I pass a variable in the URL to a Django list view?

First things first, I want to state I have seen the post created here. The problem is that I am still very new to the Django framework and every attempt I had at implementing this strategy into my code failed. Anyways, I was curious about how I could pass a string value from the URL into my listview. In my case, the variable named item so I can do a filtered query. This was extremely easy to do on function-based views, but I am struggling to do the same on these class-based views. Thanks!
Class Based View:
class PostListView(ListView):
model = Post.objects.get(subject_name=item)
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 5
Routing:
path('<str:item>/', PostListView.as_view(), name='post-view')
You can add get method to your PostListView:
def get(self, request, *args, **kwargs):
item = kwargs[“item”]
// use the item variable here
return super().get(request, *args, **kwargs)
Same thing if you need to correct your context:
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
data['item'] = kwargs['item']
return data

How to populate formview with model data when fetched via GET

I have the form display info via GET request, currently I assign a new form in get_context_data, is there a better way to do it? And http decorator doesn't work too.
#require_http_methods(['GET',])
class UniversityDetail(SingleObjectMixin, FormView):
model = KBUniversity
form_class = KBUniversityForm
template_name = 'universities/form.html'
def get(self, request, *args, **kwargs):
self.object = self.get_object()
return super(UniversityDetail, self).get(self, request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super(UniversityDetail, self).get_context_data(**kwargs)
context['form'] = KBUniversityForm(instance=self.object)
context['university_id'] = self.object.pk
return context
Use UpdateView instead of FormView with SingleObjectMixin. In 99% of the cases you should not override the get method.

Categories