I have a page that should show an event and the presentations of this event. In my code they are not related (I still have to fix that). On the home page, which receives the event and the lectures, the view is like this:
views.py
class EventoView(ListView):
model = Evento
template_name = 'home.html'
context_object_name = 'evento_list'
queryset = Evento.objects.all().order_by('-data')[:1]
class RegistroView(ListView):
model = Registro
template_name = 'home.html'
context_object_name = 'registro_list'
queryset = Registro.objects.all()
The problem is that I can only pass the Event object, the object of Registration, which show lectures Indexed must also be passed, however, only accepts a Django view for url.
urls.py
urlpatterns = patterns('',
url(r'^$', EventoView.as_view(), name='home'), #I can't pass two views
url(r'^cadastro/', CriarRegistroView.as_view(), name='cadastro'),
url(r'^contato/', CriarContatoView.as_view(), name='contato'),
url(r'^sobre/', SobreView.as_view(), name='sobre'),
url(r'^admin/', include(admin.site.urls)),
)
How can I solve this problem?
Thanks.
it looks like you can override ListView.get_context_data
class RegistroView(ListView):
model = Evento
def get_context_data(self, **kwargs):
context = super(RegistroListView, self).get_context_data(**kwargs)
context['registros'] = Registro.objects.all()
context['eventos'] = Evento.objects.all().order_by('-data')[:1]
return context
I don't have experience with ListViews so i don't know if i am using it as it is supposed to be used, or not
Related
I want all djaango urls use slug field without any parameter before or after, by default
just one url can use this metod
Views.py
class ArticleDetail(DetailView):
def get_object(self):
slug = self.kwargs.get('slug')
article = get_object_or_404(Article.objects.published(), slug=slug)
ip_address = self.request.user.ip_address
if ip_address not in article.hits.all():
article.hits.add(ip_address)
return article
class CategoryList(ListView):
paginate_by = 5
template_name = 'blog/category_list.html'
def get_queryset(self):
global category
slug = self.kwargs.get('slug')
category = get_object_or_404(Category.objects.active(), slug=slug)
return category.articles.published()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['category'] = category
return context
urls.py
urlpatterns = [
path('<slug:slug>', ArticleDetail.as_view(), name="detail"),
path('<slug:slug>', CategoryList.as_view(), name="category"),
]
This is my django blog codes,
I don't want write article or category & ... in urls, just slug
mysite .com/article-slug
...
mysite .com/category-slug
It will always trigger the Article view, regardless if there is an Article for that slug. You thus should make the URL patterns non-overlapping such that the other views can be triggered, for example with:
path('article/<slug:slug>/', Article.as_View(), name="articledetail"),
path('category/<slug:slug>/', Category.as_View(), name="category"),
path('product/<slug:slug>/', Product.as_View(), name="productdetail"),
If you want a path that accepts a single slug, you should define a view that looks if there is an Article with that slug, if that is not the case a Category and if that is not the case a Product you thus implement that logic in the view, not in the URL patterns.
#WillemVanOlsem is right, you will have to write a view like this:
from django.http import HttpResponseNotFound
def slug_router(request, slug):
if Category.objects.filter(slug=slug).exists():
return CategoryList.as_view()(request, slug=slug)
elif Article.objects.filter(slug=slug).exists():
return ArticleDetail.as_view()(request, slug=slug)
else:
return HttpResponseNotFound('404 Page not found')
And then
urlpatterns = [
path('<slug:slug>', slug_router, name="slug"),
]
... if I'm not mistaken. This should be the jist of it.
I didn't test this code, just typed it in here, so let me know if it doesn't work, I'll help to fix it.
Note that you'll have a preference if there are Articles with the same slug as some Categories.
I am trying to find best solution for encrypting my URL, I have found some old versions, for python 2.2.
I need to set my URLs, not to display like this:
.com/AddPost/1/ and .com/PostDetail/40.
But something like this:.com/AddPost/DMQRzZWMDdGQtbndzBHNsawN0aXRsZQR0ZXN0AzcwMQR3b2UDMjQwMjEwNQ
That you can not guess what PK is and access that page:
URLs:
urlpatterns = [
path('PostDetail/<int:pk>', PostDetail.as_view(), name ='post_detail'), ]
view.py:
class PostDetail(DetailView):
model = Post
template_name = 'post_detail.html'
def get_context_data(self, *args,**kwargs):
post = Post.objects.all()
context = super(PostDetail,self).get_context_data(*args,**kwargs)
stuff = get_object_or_404(Post,id=self.kwargs['pk'])
total_likes=stuff.total_likes()
context['total_likes'] = total_likes
return context
I am creating a Fixture webapp with Django. I have written the class below, which displays a list of first team fixtures. Can I rewrite it as TeamView, then pass the team_id?
class FirstView(generic.ListView):
template_name = 'fixtureapp/team.html'
context_object_name = 'fixtures'
def get_queryset(self):
"""return all first team matches"""
return Match.objects.filter(team_id=1).order_by('date')
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
data['page_title'] = '1st Team Fixtures'
return data
I have the following urls, how would I rewrite these to match?
urlpatterns = [
path('', views.HomeView.as_view(), name='home'),
path('first', views.FirstView.as_view(), name='first'),
path('second', views.SecondView.as_view(), name='second'),
as you can see I have currently created a second class called SecondView this is almost a carbon copy of FirstView, not very DRY
I can give you a brief of how it works, you can apply rest of the logic. Basic idea is to use slug.
In your html you can give the slug name with the url:
In urls.py, get that slug :
path('team/<slug:teamid_slug>/', views.TeamView.as_view(), name='team_by_id'),
Your Views should filter the query based on this slug, if no slug given it will give all the Match record. You can apply some other logic what fits to you.
class TeamView(generic.ListView):
queryset = Match.objects.all().order_by('date')
template_name = 'fixtureapp/team.html'
context_object_name = 'fixtures'
def get_queryset(self):
"""return all team_id team matches"""
return Match.objects.filter(team_id__slug=self.kwargs.get('teamid_slug')).order_by('date')
Also please have a look at this documentation of Dynamic Filtering
I have a app which is letting users fill in a few question, click a button to fill in a form with their contactinfo and redirecting them to a thank you page after submitting the form.
At first I had the error:
Reverse for 'contact' with arguments '('',)' not found. *
So I set a get method with reverse_lazy. Now the error is gone but when I click the buttons it directs me back to the same page. Read the docs but cannot find out what is going wrong.
urls.py
urlpatterns = [
path('<slug:bedrijfslug>/check', CheckView.as_view(), name='check'),
path('<slug:bedrijfslug>/contact/', ContactView.as_view(), name='contact'),
]
views.py
class CheckView(DetailView):
template_name = 'register/check.html'
model = Bedrijf
slug_url_kwarg = 'bedrijfslug'
context_object_name = 'bedrijf'
def get(self, request, *args, **kwars):
contact_url = reverse_lazy('ContactView')
return render(request, 'register/check.html', {'contact_url': contact_url})
class ContactView(FormView):
template_name = 'register/contact.html'
form_class = BezoekerForm
success_url = '/thankyou/'
Forgot to reference the slug field in my view. This method did the trick:
def bedrijf_detail(self, slug):
bedrijf = Bedrijf.objects.get(slug=slug)
return render(self, {'bedrijf': bedrijf})
Building a Django app where I have a view that displays a list of distinct case. When you click on a case, I'd like it to take you to a list of items related to the case (in this case it's a list of devices). The issue I am facing I don't know how to make the view display only the items related to that case (right now it displays every item in every case).
Views:
class MdeListView(LoginRequiredMixin, ListView):
model = Mde
template_name = 'mde/mde.html'
ordering = [F('date').desc()]
def get_queryset(self):
return Mde.objects.distinct('case_number')
class MdeCaseListView(LoginRequiredMixin, ListView):
model = Mde
template_name = 'mde/mde_case_list.html'
urls.py
from django.urls import path
from .views import MdeListView, MdeCreateView, MdeCaseListView
urlpatterns = [
path('<int:pk>/list', MdeCaseListView.as_view(), name='mde_case_list'),
path('new', MdeCreateView.as_view(), name='mde_new'),
path('', MdeListView.as_view(), name='mde'),
]
The url goes to the right record based on the primary key, but from there I want only the items that use the same case_number as that primary key.
I was able to figure it out!
class MdeCaseListView(LoginRequiredMixin, ListView):
model = Mde
template_name = 'mde/mde_case_list.html'
def get_queryset(self):
pkey = self.kwargs.get("pk")
case = Mde.objects.filter(id=pkey).values_list('case_number', flat=True)
return Mde.objects.filter(case_number=case[0])