I have a view which should redirect the user to the new tribe that he created. but I don't know how to get the tribe_id for it to work.
views.py
def tribeview(request, tribe_id):
tribe = get_object_or_404(Tribe,pk=tribe_id)
playlist = tribe.playlist_set.all()
context = { 'tribe': tribe, 'playlists':playlist }
return render(request, 'app/tribe.html', context)
class create_tribe(CreateView):
model = Tribe
form_class = TribeForm
template_name = 'app/create_tribe.html'
def form_valid(self, form):
tribe = form.save(commit=False)
tribe.chieftain = self.request.user
tribe.save()
return super().form_valid(form)
def get_success_url(self):
return reverse('app:tribe-view', args={'tribe': self.object.tribe_id})
urls.py
app_name = 'app'
urlpatterns = [
path('', views.index, name='index'),
path('tribe/<int:tribe_id>',views.tribeview,name='tribe-view'),
path('tribe/<int:tribe_id>/playlist/<int:playlist_id>',views.playlistview,name='playlist-view'),
path('new_tribe', login_required(create_tribe.as_view()), name="new-tribe"),
]
models.py
class Tribe(TimeStamped):
name = models.CharField(max_length=200,unique=True)
chieftain = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
tribe_members = models.ManyToManyField(Member)
def __str__(self):
return self.name[:80]
Related
So I'm building an e-commerce store with Django(First project after learning). I need to click on Sort in the template, and have the CBV return an object that's ordered by either, price, or whatever field I specify in the request. This is what I have so far
Template
Sort by Lowest Price
View
class ClotheListView(ListView):
model = Clothe
paginate_by = 8
def get_filter_param(self):
# Grab the absolute url and then retrieve the filter param
filter_param = self.request.path.split("/")[-1]
return filter_param
def get_queryset(self):
filter_param = self.get_filter_param()
if(filter_param != ""):
queryset = self.model.objects.filter(cloth_gender=filter_param)
else:
queryset = self.model.objects.all()
return queryset
return clothes_filtered_list.qs
def get_ordering(self):
ordering = self.request.GET.get('ordering', '-cloth_price')
return ordering
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
Url.py
urlpatterns = [
path('', views.ClotheListView.as_view(), name="clothe_list"),
path('<slug:slug>', views.ClotheListView.as_view(),
name="clothe_list_category"),
path('<int:pk>/', views.ClotheDetailView.as_view(), name="clothe_detail")
]
ok, so this is how I did it:
Template
<span class="float-end d-none d-lg-block mt-3">
Sort by: Price -
High To Low |
Price:
Low to High
</span>
View
class ClotheListView(ListView):
model = Clothe
paginate_by = 8
def get_filter_param(self):
# Grab the absolute url and then retrieve the filter param
filter_param = self.request.path.split("/")[-1]
return filter_param
def get_queryset(self):
# code for price sorting
default_order = "cloth_name"
order_param = ""
user_filter = ""
try:
order_param = self.request.GET.get('ordering').strip()
except:
pass
try:
user_filter = self.request.GET.get('filter').strip()
except:
pass
order_by = order_param or default_order
# End of sorting code
filter_param = self.get_filter_param()
if(filter_param != "" or not filter_param):
if(user_filter != ""):
queryset = self.model.objects.filter(
cloth_gender=filter_param, cloth_category=user_filter)
else:
queryset = self.model.objects.filter(
cloth_gender=filter_param)
else:
queryset = self.model.objects.all()
return queryset.order_by(order_by)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
url.py
urlpatterns = [
path('', views.ClotheListView.as_view(), name="clothe_list"),
path('<slug:slug>', views.ClotheListView.as_view(),
name="clothe_list_category"),
path('<int:pk>/', views.ClotheDetailView.as_view(), name="clothe_detail")
]
I have a list of movie genre. Each genre has its own movie. For instance, there is a list of movies for every movie genre but the object_list is empty.
the github link: https://github.com/AdebayoAnuoluwapo/imdb-original.git
My View:
class MovieCategory(ListView):
model = Movie
paginate_by = 2
def get_queryset(self):
self.category = self.kwargs['category']
return Movie.objects.filter(category=self.category)
def get_context_data(self , **kwargs):
context = super(MovieCategory , self).get_context_data(**kwargs)
context['movie_category'] = self.category
print(context)
return context
My Models:
ACTION = 'action'
DRAMA = 'drama'
COMEDY = 'comedy'
ROMANCE = 'romance'
CATEGORY_CHOICES = (
(ACTION, 'Action'),
(DRAMA, 'Drama'),
(COMEDY, 'Comedy'),
(ROMANCE, 'Romance'),
)
class Movie(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(max_length=2000)
image = models.ImageField(upload_to='movies')
category = models.CharField(choices=CATEGORY_CHOICES, max_length=10)
language = models.CharField(choices=LANGUAGE_CHOICES, max_length=7)
status = models.CharField(choices=STATUS_CHOICES, max_length=2)
cast = models.CharField(max_length=100)
year_of_production = models.DateField()
views_count = models.IntegerField(default=0)
def __str__(self):
return self.title
my Urls:
from django.urls import path
from . import views
app_name = 'movie'
urlpatterns = [
path('', views.HomeView.as_view(), name='home'),
path('list/', views.MovieListView.as_view(), name='movie_list'),
path('category/<str:category>', views.MovieCategory.as_view() , name='movie_category'),
path('language/<str:lang>', views.MovieLanguage.as_view(), name='movie_language'),
path('search/', views.MovieSearch.as_view() , name='movie_search'),
path('<int:pk>/', views.MovieDetailView.as_view(), name='movie_detail'),
]
when i print(context) I get
'object_list': <QuerySet []>,
'movie_list': <QuerySet []>
Thanks In Advance...
I have solved it already.
I forgot to add the context_object_name
class MovieCategory(ListView):
model = Movie
paginate_by = 2
context_object_name = 'movies'
def get_queryset(self,**kwargs):
self.category = self.kwargs['category']
return Movie.objects.filter(category=self.category)
def get_context_data(self , **kwargs):
context = super(MovieCategory,self).get_context_data(**kwargs)
context['movie_category'] = self.category
return context
I am writing an application on Django.
How can I save data (provider.category) from form using form.instance.
models
class RequestProvider(models.Model):
category = models.ManyToManyField(Category, related_name="provider_request")
forms
class ProviderForm(forms.ModelForm):
class Meta:
model = RequestProvider
fields = ('category',)
widgets = {
'category': forms.SelectMultiple(
attrs={
'class': 'select2',
'style': 'width: 246px;'
}
),
}
views
#method_decorator(currency_account_dec, name='dispatch')
class ProviderCreateView(CreateView):
form_class = ProviderForm
template_name = 'provider_create.html'
def form_valid(self, form):
provider_id = self.kwargs.get('provider_id',None)
session_user = self.request.user
if provider_id:
form.instance.provider = Provider.objects.get(pk=provider_id)
form.instance.user = self.request.user
#form.instance.category = form.cleaned_data.get('category')
return super(ProviderCreateView,self).form_valid(form)
def get_context_data(self, **kwargs):
provider_id = self.kwargs.get('provider_id',None)
ss = RequestProvider.objects.filter(user=self.request.user)
for s in ss:
print(s.category)
ctx = super(ProviderCreateView, self).get_context_data(**kwargs)
ctx['organizations'] = Organization.objects.filter(user=self.request.user)
ctx['payments'] = Payment.objects.all()
if provider_id:
this_provider = Provider.objects.get(pk=provider_id)
ctx['this_provider'] = this_provider
ctx['categories'] = Category.objects.all()
ctx['roles'] = this_provider.role.all()
ctx['payments'] = Payment.objects.all()
ctx['deliveries'] = Delivery.objects.all()
return ctx
I believe you can do form.save()
No need to rewrite the form_valid.
#method_decorator(currency_account_dec, name='dispatch')
class ProviderCreateView(CreateView):
form_class = ProviderForm
template_name = 'provider_create.html'
def post(self, request):
provider_id = self.kwargs.get('provider_id',None)
session_user = request.user
form = ProviderForm(request.POST)
if form.is_valid():
rq = form.save(commit=False)
if provider_id:
rq.provider = Provider.objects.get(pk=provider_id)
rq.user = self.request.user
rq.save()
rq.category = form.cleaned_data.get('category')
return HttpResponseRedirect('/providers/')
else:
return HttpResponseRedirect('/providers/create/')
I have a response error that is driving me crazy, I tried everything but no way to find why am I getting that error :
django.urls.exceptions.NoReverseMatch: Reverse for 'team_select' with keyword arguments '{'pk1': ''}' not found.
1 pattern(s) tried: ['website/project/(?P<pk1>[0-9]+)/linkteam2/$']
that is my views:
class HomePage(TemplateView):
template_name= 'index.html'
class LinkTeam(generic.ListView):
template_name = 'link_project.html'
def get_queryset(self):
#import pdb; pdb.set_trace()
#team2 = Team.objects.all().filter(team_hr_admin = self.request.user)
queryset = Team.objects.filter(team_hr_admin=self.request.user)
return queryset
def TeamSelect(request):
import pdb; pdb.set_trace()
if request.method == "POST":
select_form = EditSelectTeam(request.user, request.POST)
if select_form.is_valid():
data = select_form.cleaned_data['team_choice']
obj2 = Project.objects.filter(project_hr_admin=request.user)
obj3 = obj2.latest('id')
if obj3.team_id == None:
obj3.team_id = data
obj3.save()
obj4 = obj3.team_id
obj5 = obj4.members.all()
for i in obj5:
current_site = get_current_site(request)
message = render_to_string('acc_join_email.html', {
'user': i.first_name,
'domain':current_site.domain,
})
mail_subject = 'You have been invited to SoftScores.com please LogIn to get access to the app'
to_email = i.email
email = EmailMessage(mail_subject, message, to=[to_email])
email.send()
messages.success(request, 'test')
return HttpResponseRedirect(reverse('website:ProjectDetails', kwargs={'pk':obj3.id}))
else:
print('this project has already a team')
else:
print('Non Valid form')
else:
select_form = EditSelectTeam(request.user)
return render(request,'link_project.html',
{'select_form':select_form })
class HRIndex(generic.ListView):
#import pdb; pdb.set_trace()
template_name = "HR_index.html"
model = Project
class CandidateIndex(TemplateView):
#import pdb; pdb.set_trace()
template_name = "candidate_index.html"
class EmployeeIndex(TemplateView):
#import pdb; pdb.set_trace()
template_name = "employee_index.html"
def get_context_data(self, **kwargs):
context = super(EmployeeIndex, self).get_context_data(**kwargs)
surveys = Survey.objects.filter(is_published=True)
if not self.request.user.is_authenticated():
surveys = surveys.filter(need_logged_user=False)
context['surveys'] = surveys
return context
class ProjectCreate(LoginRequiredMixin,CreateView):
model = Project
fields = ['name']
template_name = 'project_form.html'
def form_valid(self, form):
form.instance.project_hr_admin = self.request.user
return super(ProjectCreate, self).form_valid(form)
class ProjectDetailView(LoginRequiredMixin,generic.DetailView):
#import pdb; pdb.set_trace()
model = Project
template_name = 'project_details.html'
def get_object(self, queryset=None):
return get_object_or_404(Project,id=self.kwargs['pk1'])
def get_context_data(self, **kwargs):
context = super(ProjectDetailView, self).get_context_data(**kwargs)
try:
team_name = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all()
context['team_name'] = team_name
except AttributeError:
pass
return context
class EmployeeDetailView(LoginRequiredMixin, generic.DetailView):
#import pdb; pdb.set_trace()
model = MyUser
template_name = 'Employee_Details.html'
def get_object(self, queryset=None):
return get_object_or_404(MyUser, pk=self.kwargs['pk2'], members__project=self.kwargs['pk1'])
def get_context_data(self, **kwargs):
context = super(EmployeeDetailView, self).get_context_data(**kwargs)
employee_name = MyUser.objects.get(id=self.kwargs['pk2'])
team_list = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all()
team_list_pop = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all().exclude(id=self.kwargs['pk2'])
context={
'employee_name' : employee_name,
'team_list' : team_list,
'team_list_pop' : team_list_pop
}
return context
class TeamCreate(CreateView):
model = Team
fields = ['team_name']
template_name = 'team_form.html'
def form_valid(self, form):
#import pdb; pdb.set_trace()
valid = super(TeamCreate, self).form_valid(form)
form.instance.team_hr_admin = self.request.user
obj = form.save()
#SELECT * FROM project WHERE user = 'current_user' AND team_id = NULL
obj2 = Project.objects.get(project_hr_admin=self.request.user, team_id=None)
obj2.team_id = obj
obj2.save()
return valid
return super(TeamCreate, self).form_valid(form)
def get_success_url(self):
#import pdb; pdb.set_trace()
project = Project.objects.get(team_id=None, project_hr_admin=self.request.user)
return project.get_absolute_url()
URL:
from django.conf.urls import url, include
from website import views
app_name = 'website'
urlpatterns = [
url(r'^hr_index/$', views.HRIndex.as_view(), name='hr_index'),
url(r'^candidate_index/$', views.CandidateIndex.as_view(),name='candidate_index'),
url(r'^employee_index/$', views.EmployeeIndex.as_view(),name='employee_index'),
url(r'^addproject/$', views.ProjectCreate.as_view(), name='add_project'),
url(r'^project/(?P<pk1>[0-9]+)/addteam/$', views.TeamCreate.as_view(), name='add_team'),
url(r'^project/(?P<pk1>[0-9]+)/linkteam/$', views.LinkTeam.as_view(), name='link_team'),
url(r'^project/(?P<pk1>[0-9]+)/linkteam2/$', views.TeamSelect, name='team_select'),
url(r'^project/(?P<pk1>[0-9]+)/$',views.ProjectDetailView.as_view(), name='ProjectDetails'),
url(r'^project/(?P<pk1>[0-9]+)/api/chart/data2/$',views.TeamChartData.as_view(), name='TeamChartData'),
url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/$',views.EmployeeDetailView.as_view(), name='EmployeDetails'),
url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/api/chart/data/$',views.EmployeeChartData.as_view(), name='EmployeeChartData'),
#url(r'^project/(?P<pk>[0-9]+)/api/chart/data/$', views.ChartData.as_view(), name='chartdata'),
]
the keyword argument say that pk1 is empty when it should not since I am in the page http://127.0.0.1:8000/website/project/2/
My template look like...................................
{% load static %}
<div class="invite-team">
<div class="jumbotron greenback">
<div class="jumbo-text">
<h7>Your project has been created, It is time to link a team or create a new for your project</h3>
</div>
<div class="jumbo-button">
<span class="fa fa-link"></span> Link an existing team
<span class="fa fa-plus-circle"></span> Create a new team
</div>
</div>
</div>
edit:
the error appeared after I added :
renderer_classes = [TemplateHTMLRenderer]
template_name = 'project_details.html'
class TeamChartData(APIView):
queryset = MyUser.objects.all()
serializer_class = MyUserSerializer, #ProjectSerializer
permission_classes = []
http_method_names = ['get',]
renderer_classes = [TemplateHTMLRenderer]
template_name = 'project_details.html'
def get_serializer_class(self):
return self.serializer_class
def get(self, request, format=None, *args, **kwargs):
chunk_team = get_team_info_score(self)
motiv_team = get_team_motivation_score(self)
action_team = get_team_action_score(self)
behav_team = get_behaviour_action_score(self)
team_complete = get_team_complete_data(self)
cohesiveness_score = get_team_cohesivenss_score(self)
info_dist = get_question_similarities(self)[0]
motiv_dist = get_question_similarities(self)[1]
action_dist = get_question_similarities(self)[2]
behav_dist = get_question_similarities(self)[3]
data = {
"team_info_score":chunk_team,
"team_motiv_score":motiv_team,
"team_action_score":action_team,
"team_behaviour_score":behav_team,
"team_complete":team_complete,
"cohesiveness_score":cohesiveness_score[0],
"users":cohesiveness_score[1],
"user_dist":cohesiveness_score[2],
"info_dist":info_dist,
"motiv_dist": motiv_dist,
"action_dist":action_dist,
"behav_dist":behav_dist,
"complete_label":complete_label,
"info_label":processing_information_label,
"motivation_label": motivation_label,
"action_label":action_label,
"behav_label":other_data_label,
}
return Response(data)
Your url reverse looks fine. The problem is that you don't set project to your context in ProjectDetailView:
def get_context_data(self, **kwargs):
context = super(ProjectDetailView, self).get_context_data(**kwargs)
try:
project = Project.objects.get(id=self.kwargs['pk1'])
team_name = project.team_id.members.all()
context['team_name'] = team_name
context['project'] = project
except AttributeError:
pass
return context
Hi guys I have an issue with my private keys.
I do not know what is the problem if someone could give me a hand it would be greatly appreciated.
the errror that I get is : Generic detail view ProjectDetailView must be called with either an object pk or a slug
my models are the following:
class Team(models.Model):
team_name = models.CharField(max_length=100, default = '')
team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
members = models.ManyToManyField(MyUser, related_name="members")
def __str__(self):
return self.team_name
class Project(models.Model):
name = models.CharField(max_length=250)
team_id = models.ForeignKey(Team, blank=True, null=True)
project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True)
candidat_answers = models.ManyToManyField('survey.response')
def get_absolute_url(self):
return reverse('website:ProjectDetails', kwargs = {'pk1' : self.pk})
def __str__(self):
return self.name
my views :
class HomePage(TemplateView):
template_name= 'index.html'
class LinkTeam(generic.ListView):
template_name = 'link_project.html'
def get_queryset(self):
#import pdb; pdb.set_trace()
#team2 = Team.objects.all().filter(team_hr_admin = self.request.user)
queryset = Team.objects.filter(team_hr_admin=self.request.user)
return queryset
def TeamSelect(request):
import pdb; pdb.set_trace()
if request.method == "POST":
select_form = EditSelectTeam(request.user, request.POST)
if select_form.is_valid():
data = select_form.cleaned_data['team_choice']
obj2 = Project.objects.filter(project_hr_admin=request.user)
obj3 = obj2.latest('id')
if obj3.team_id == None:
obj3.team_id = data
obj3.save()
obj4 = obj3.team_id
obj5 = obj4.members.all()
for i in obj5:
current_site = get_current_site(request)
message = render_to_string('acc_join_email.html', {
'user': i.first_name,
'domain':current_site.domain,
})
mail_subject = 'You have been invited to SoftScores.com please LogIn to get access to the app'
to_email = i.email
email = EmailMessage(mail_subject, message, to=[to_email])
email.send()
messages.success(request, 'test')
return HttpResponseRedirect(reverse('website:ProjectDetails', kwargs={'pk1':obj3.id}))
else:
print('this project has already a team')
else:
print('Non Valid form')
else:
select_form = EditSelectTeam(request.user)
return render(request,'link_project.html',
{'select_form':select_form })
class HRIndex(generic.ListView):
#import pdb; pdb.set_trace()
template_name = "HR_index.html"
model = Project
class CandidateIndex(TemplateView):
#import pdb; pdb.set_trace()
template_name = "candidate_index.html"
class EmployeeIndex(TemplateView):
#import pdb; pdb.set_trace()
template_name = "employee_index.html"
def get_context_data(self, **kwargs):
context = super(EmployeeIndex, self).get_context_data(**kwargs)
surveys = Survey.objects.filter(is_published=True)
if not self.request.user.is_authenticated():
surveys = surveys.filter(need_logged_user=False)
context['surveys'] = surveys
return context
class ProjectCreate(CreateView, LoginRequiredMixin):
model = Project
fields = ['name']
template_name = 'project_form.html'
def form_valid(self, form):
form.instance.project_hr_admin = self.request.user
return super(ProjectCreate, self).form_valid(form)
class ProjectDetailView(generic.DetailView, LoginRequiredMixin):
#import pdb; pdb.set_trace()
model = Project
template_name = 'project_details.html'
def get_context_data(self, **kwargs):
context = super(ProjectDetailView, self).get_context_data(**kwargs)
try:
team_name = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all()
context['team_name'] = team_name
except AttributeError:
pass
return context
class EmployeeDetailView(generic.DetailView, LoginRequiredMixin):
#import pdb; pdb.set_trace()
model = MyUser
template_name = 'Employee_Details.html'
def get_object(self, queryset=None):
return get_object_or_404(MyUser, pk=self.kwargs['pk2'], members__project=self.kwargs['pk1'])
def get_context_data(self, **kwargs):
context = super(EmployeeDetailView, self).get_context_data(**kwargs)
employee_name = MyUser.objects.get(id=self.kwargs['pk2'])
team_list = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all()
team_list_pop = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all().exclude(id=self.kwargs['pk2'])
context={
'employee_name' : employee_name,
'team_list' : team_list,
'team_list_pop' : team_list_pop
}
return context
class TeamCreate(CreateView):
model = Team
fields = ['team_name']
template_name = 'team_form.html'
def form_valid(self, form):
#import pdb; pdb.set_trace()
valid = super(TeamCreate, self).form_valid(form)
form.instance.team_hr_admin = self.request.user
obj = form.save()
#SELECT * FROM project WHERE user = 'current_user' AND team_id = NULL
obj2 = Project.objects.get(project_hr_admin=self.request.user, team_id=None)
obj2.team_id = obj
obj2.save()
return valid
return super(TeamCreate, self).form_valid(form)
def get_success_url(self):
#import pdb; pdb.set_trace()
project = Project.objects.get(team_id=None, project_hr_admin=self.request.user)
return project.get_absolute_url()
my urls:
urlpatterns = [
url(r'^hr_index/$', views.HRIndex.as_view(), name='hr_index'),
url(r'^candidate_index/$', views.CandidateIndex.as_view(),name='candidate_index'),
url(r'^employee_index/$', views.EmployeeIndex.as_view(),name='employee_index'),
url(r'^addproject/$', views.ProjectCreate.as_view(), name='add_project'),
url(r'^project/(?P<pk1>[0-9]+)/addteam/$', views.TeamCreate.as_view(), name='add_team'),
url(r'^project/(?P<pk1>[0-9]+)/linkteam/$', views.LinkTeam.as_view(), name='link_team'),
url(r'^project/(?P<pk1>[0-9]+)/linkteam2/$', views.TeamSelect, name='team_select'),
url(r'^project/(?P<pk1>[0-9]+)/$',views.ProjectDetailView.as_view(), name='ProjectDetails'),
url(r'^project/(?P<pk1>[0-9]+)/api/chart/data2/$',views.TeamChartData.as_view(), name='TeamChartData'),
url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/$',views.EmployeeDetailView.as_view(), name='EmployeDetails'),
url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/api/chart/data/$',views.EmployeeChartData.as_view(), name='EmployeeChartData'),
What am I messing up here ?
DetailView's get_object method is looking for pk url argument. Because you have only pk1 url argument it raise error. You need to rename argument in url to pk:
url(r'^project/(?P<pk>[0-9]+)/$',views.ProjectDetailView.as_view(), name='ProjectDetails')
or override get_object method like you did in EmployeeDetailView.
You can also try to define pk_url_kwarg inside ProjectDetailView like this:
class ProjectDetailView(generic.DetailView, LoginRequiredMixin):
#import pdb; pdb.set_trace()
model = Project
template_name = 'project_details.html'
pk_url_kwarg = 'pk1'
In this case you need not to change url pattern or override get_object.