I have a problem how to pass selected data from SelectDateWidget to view and to url.
Now I have the hardcoded data get_success_url in the digest, after the "submit" on the form.
For the SelectDateWidget help, I want to select the month and year for which I want to show selected events.
Here is my form:
class BookingForm(forms.ModelForm):
date_start = forms.DateField(widget=SelectDateWidget(years=range(1980, 2018)))
class Meta:
model = Booking
fields = ('date_start', )
widgets = {'date_start': SelectDateWidget()}
This is my view, where I have hardcoded value for success url:
class BookingListView(ListView, FormView):
model = models.Booking
form_class = BookingForm
queryset = models.Booking.objects.all() # order_by('-date_start')
paginate_by = 80
template_name = 'events/archive_list.html'
context_object_name = 'object_list'
date_field = 'date_start'
allow_future = True
def get_context_data(self, **kwargs):
context = super(BookingListView, self).get_context_data(**kwargs)
context['mode'] = 'archive'
context['form'] = BookingForm()
return context
def get_success_url(self):
return reverse('archive:archive_month_numeric', kwargs={'year': 2014, 'month': 10})
My url to page where I have events in selected date:
url(r'^/(?P<year>[0-9]{4})/(?P<month>[0-9]+)/$', views.ArticleMonthArchiveView.as_view(month_format='%m'), name="archive_month_numeric"),
Related
I'm trying to get a DetailView's model's pk in a variable in the get_context_data but I keep getting the error KeyError at /x/x/ 'pk'.
views.py
class MangaView(DetailView):
model = Manga
template_name = 'mangas/manga.html'
context_object_name = 'manga'
slug_field = 'manga_slug'
slug_url_kwarg = 'manga_slug'
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
manga = get_object_or_404(Manga, id=self.kwargs['pk']) # error line
favorited = False
latered = False
...
return data
urls.py
urlpatterns = [
path('mangas/', MangasHomeView.as_view(), name='mangas-home'),
path('manga/<slug:manga_slug>/', MangaView.as_view(), name='manga'),
...
]
The error you are seeing is caused by trying to access the pk value through self.kwargs, when in fact your view is using a slug field and slug URL parameter.
Try to use self.get_object() as it gives you current instance in DetailView whether it is pk or slug so:
class MangaView(DetailView):
model = Manga
template_name = 'mangas/manga.html'
context_object_name = 'manga'
slug_field = 'manga_slug'
slug_url_kwarg = 'manga_slug'
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
manga = self.get_object()
favorited = False
latered = False
...
return data
I have a class based view:
class PostListViewMojeReported(ListView):
def get_username(self, **kwargs):
login_username = request.user.username
context = {'login_username': login_username}
return context
model = Post
template_name = 'blog/filter_moje_reported.html'
context_object_name = 'posts'
queryset = Post.objects.filter(Q(status='Otvorena') & (Q(res_person_1_username=username) | Q(res_person_2_username=username)))
ordering = ['-date_posted']
paginate_by = 30
I don't know how to get username from the current logged in user to use as a filter in my queryset. I need to compare the current logged in user with 'res_person_1_username' and 'res_person_2_username'.
You can obtain the requerst object with self.request, so:
class PostListViewMojeReported(ListView):
model = Post
template_name = 'blog/filter_moje_reported.html'
context_object_name = 'posts'
paginate_by = 30
def get_username(self, **kwargs):
login_username = self.request.user.username
context = {'login_username': login_username}
return context
def get_queryset(self, *args, **kwargs):
username = self.request.user.username
return super().get_queryset(*args, **kwargs).filter(
Q(res_person_1_username=username) | Q(res_person_2_username=username),
status='Otvorena'
).order_by('-date_posted')
I would however advise to work with two ForeignKeys to the user model, and not store the username, since it is possible that later the user removes their account, and another person then creates an account with that username.
Is there a way to return a dictionary through the get_queryset function of a class based view in Django? I want to pass the array tickets and the string email to my template, but I am only able to pass tickets right now.
Content of views.py:
class UserTicketListView(ListView):
model = Ticket
template_name = 'ticket_system/user_tickets.html'
context_object_name = 'tickets'
ordering = ['-date_posted']
paginate_by = 5
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
email = User.objects.get(username=user).email
return Ticket.objects.filter(author=user).order_by('-date_posted')
class UserTicketListView(ListView):
model = Ticket
template_name = 'ticket_system/user_tickets.html'
context_object_name = 'tickets'
ordering = ['-date_posted']
paginate_by = 5
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
queryset = self.get_queryset()
user = get_object_or_404(User, username=self.kwargs.get('username'))
email = User.objects.get(username=user).email
queryset = queryset.filter(author=user).order_by('-date_posted')
context['user'] = user
context['email'] = email
return context
If the 'school year' value is changed, 404 does not appear.
I want data to be displayed only when both 'school_year' and 'pk' have the right values in url.
for example
If you have data that (School_Year = 2020, pk = 33)
when you enter url https://190.0.1/190/190/33 and https://190.0.1/190/whatthell/33
Both are the same results.
However, I would like to display the result only when both values are correct.
i really dont know if i explained correctly, thanks.
view.py
class StudentDetail(DetailView,FormView):
model = Student
template_name = 'student/member.html'
context_object_name = 'student'
form_class = AddConsultation
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['pk'] = Student.objects.filter(pk=self.kwargs.get('pk'))
return context
url.py
path('student/<school_year>/<pk>/', views.StudentDetail.as_view(), name='student_detail'),
html link
<a href='{% url 'student_detail' student.school_year student.pk %}'>
models.py
class Student(models.Model):
school_year = models.CharField(
max_length=10,
choices=SCHOOL_YEAR_CHOICES,
default='2021N',
verbose_name='school year'
)
... etc
I would remove get_context_data and override get_object using get_object_or_404:
class StudentDetail(DetailView, FormClass):
model = Student
template_name = 'student/member.html'
context_object_name = 'student'
form_class = AddConsultation
def get_object(self, queryset=None):
return get_object_or_404(Student, pk=self.kwargs['pk'], school_year=self.kwargs['school_year'])
Other solution may be:
class StudentDetail(DetailView, FormClass):
model = Student
template_name = 'student/member.html'
context_object_name = 'student'
form_class = AddConsultation
slug_field = 'school_year'
slug_url_kwarg = 'school_year'
query_pk_and_slug = True
but I find the first one less magic :)
I want to get specific queryset inside my ListView class. The queryset that I want to get is:
user = User.objects.get(username=username)
However, since ListView is class-based view, I can't define what I want.
I tried like this:
**views.py**
class PostListView(ListView):
model = Post
template_name = 'itu_forum/home.html'
context_object_name = 'posts'
ordering = ['-date_posted'] # for normal view [date_posted]
paginate_by = 6
def get_context_data(self, **kwargs):
ctx = super(PostListView, self).get_context_data(**kwargs)
ctx['title'] = 'Ana Sayfa'
return ctx
def get_queryset(self):
queryset = super(PostListView, self).get_queryset()
return queryset.filter(author.username=self.kwargs['username'])
This is the url I want to use. I want to get to specific user's profile:
**urls.py**
path('profile/<str:username>/', views.user_profile, name='user-profile')
href in My Template:
href="{%url 'user-profile' queryset.username %}
I completely messed up. Need help.
you can do
def get_queryset(self):
queryset = super(PostListView, self).get_queryset()
return queryset.filter(author.username=self.request.user.username)