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
Related
i want that a form is prepoluate with data
my model:
TYPE = (("S",'Swing'),
("R","Rapide"))
class valuation(models.Model):
stock = models.ForeignKey("stock",on_delete=models.CASCADE,related_name='valuation',)
date = models.DateField(auto_created=True)
val_type = models.CharField(choices=TYPE, max_length=1,default='R')
user = models.ForeignKey("users.User", on_delete=models.CASCADE)
def __str__(self):
return f"{self.stock} - {self.date} - {self.val_type}"
my view:
class valuationCreateviewSwing(CreateView):
template_name = "evaluation/evaluation_create.html"
form_class = valuationModeform
def get_form_kwargs(self): # prepopulate form
kwargs = super(valuationCreateviewSwing, self).get_form_kwargs()
stck = get_object_or_404(stock, pk=self.kwargs['pk'])
kwargs['user'] = self.request.user
kwargs['val_type'] = "S"
kwargs['stock'] = stck
return kwargs
def get_context_data(self, **kwargs):
# we need to overwrite get_context_data
# to make sure that our formset is rendered
data = super().get_context_data(**kwargs)
if self.request.POST:
data["val_detail"] = ChildFormset1(self.request.POST)
else:
data["val_detail"] = ChildFormset1()
data.update({
"typeVal": "Swing",})
return data
def form_valid(self, form):
context = self.get_context_data()
val_detail_Swing = context["val_detail_Swing"]
self.object = form.save(commit=False)
# add data info neede about valuation model
self.object = form.save()
if val_detail_Swing.is_valid():
val_detail_Swing.instance = self.object
val_detail_Swing.save()
return super().form_valid(form)
def get_success_url(self):
return reverse("stock:stock-list")
I've a child form in my view (this part works ok):
ChildFormset1 = inlineformset_factory(
valuation, val_detail_Swing, form=valuationSwingModelform, can_delete=False)
I tried to use ge_for_kwargs but it seems not working as I've an error message :
init() got an unexpected keyword argument 'user'
You can use get_initial() method:
class valuationCreateviewSwing(CreateView):
template_name = "evaluation/evaluation_create.html"
form_class = valuationModeform
def get_initial(self):
query = self.request.GET
return {
'user': self.request.user.pk
'val_type': "S",
'stock': self.kwargs.get('pk')
}
...
Or you should override __init__() method and stay to use get_form_kwargs()
class valuationModeform(ModelForm):
class Meta:
model = Valuation
fields = '__all__'
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
val_type = kwargs('val_type', None)
stock = kwargs.pop('stock', None)
super().__init__(*args, **kwargs)
# assign initial values
self.fields['user'].initial = user
self.fields['val_type'].initial = val_type
self.fields['stock'].initial = stock
I work on a small Django App and get an error tells me: super(type, obj): obj must be an instance or subtype of type.I am trying to save the details of the sale in the database but I get this error.
Views
class VentaCreateView(LoginRequiredMixin, ValidatePermissionRequiredMixin, CreateView):
model = Venta
form_class = nueva_venta_form
template_name = 'venta/venta_form.html'
success_url = reverse_lazy('Index')
permission_required = 'store_project_app.change_categoria'
url_redirect = success_url
#method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
data = {}
try:
action = request.POST['action']
if action == 'autocomplete':
elif action == 'add':
#ventas = request.POST['action']
#ventas = request.POST['ventas']
ventas = json.loads(request.POST['ventas'])
#print(ventas)
venta = Venta()
venta.id_cliente = Cliente.objects.get(id_cliente = ventas['id_cliente'])
venta.id_empleado = Empleado.objects.get(id_empleado = ventas['id_empleado'])
venta.fecha_venta = ventas['fecha_venta']
venta.forma_pago = Metodo_Pago.objects.get(id_metodo_pago = ventas['forma_pago'])
venta.precio_total = float(ventas['precio_total'])
venta.save()
for i in ventas['productos']:
detalle_venta = Detalle_Venta()
detalle_venta.id_venta = venta.id_venta
detalle_venta.id_producto = i['id_producto']
detalle_venta.cantidad = int(i['cantidad'])
detalle_venta.subtotal = float(i['subtotal'])
detalle_venta.save()
else:
data['error'] = 'No ha ingresado a ninguna opciĆ³n'
except Exception as e:
data['error'] = str(e)
return JsonResponse(data, safe=False)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = 'Crear una Venta'
context['entity'] = 'Venta'
context['list_url'] = self.success_url
context['action'] = 'add'
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/')
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.
i am using class based generic view in my Subject_En roll application
my view.py is
cc = 0
#login_required
def add_subject_enroll(request):
user = request.user
obj = StudentRegistration.objects.get(user=user)
print "obj.first_name",obj.first_name
first_name = obj.first_name
print "first_name",first_name
if obj.user:
print "object exist"
#form = Subject_EnrollForm(request.POST or None, initial={'student_name' : first_name})
#form = Subject_EnrollForm( initial={'student_name' : obj.first_name})
form = Subject_EnrollForm(request.POST or None, request.FILES or None)
form.fields["student_name"].initial = first_name
form.fields["birth_place"].initial = obj.birth_place
form.fields["gender"].initial = obj.gender
form.fields["phone"].initial = obj.phone
form.fields["email"].initial = obj.email
form.fields["phone"].initial = obj.phone
form.fields["nationality"].initial = obj.nationality
form.fields["religion"].initial = obj.religion
form.fields["blood_group"].initial = obj.blood_group
form.fields["nationality"].initial = obj.nationality
form.fields["nationality"].initial = obj.nationality
form.fields["nationality"].initial = obj.nationality
form.fields["nationality"].initial = obj.nationality
else:
print "object not found"
Subject_EnrollForm(request.POST or None, request.FILES or None)
if request.POST:
if form.is_valid():
a = form.save()
a.user = request.user
a.save()
#user.save()
messages.add_message(request,messages.SUCCESS, "your Profile was added")
#return HttpResponseRedirect('/app/all')
return HttpResponseRedirect('/')
args = {}
args.update(csrf(request))
args['form'] = form
context = RequestContext(request,
{'request': request,
'user': request.user,
'form': form})
return render_to_response('subject_enroll/add_subject_enroll.html', args, context)
class Subject_EnrollListView(ListView):
"""View to display all published and visible news entries."""
template_name = "subject_enroll/subject_enroll_list.html"
def get_queryset(self):
return Subject_Enroll.objects.all()
class DetailViewMixin(object):
"""Mixin to handle different DetailView variations."""
model = Subject_Enroll
#slug_field = 'translations__slug'
def get_queryset(self):
#return Subject_Enroll.objects.all()
return Subject_Enroll.objects.lang(self.request, False)
class Subject_EnrollDetailView(DetailViewMixin, DetailView):
def get_context_data(self, **kwargs):
context = super(Subject_EnrollDetailView, self).get_context_data(**kwargs)
context['subject_enrolls'] = Subject_Enroll.objects.all()
return context
class Subject_EnrollUpdateView(UpdateView):
form_class = Subject_EnrollForm
model = Subject_Enroll
template_name = 'subject_enroll/subject_enroll_detail.html'
def get(self, request, **kwargs):
self.object = Subject_Enroll.objects.get(id=self.request.id)
form_class = self.get_form_class()
form = self.get_form(form_class)
context = self.get_context_data(object=self.object, form=form)
return self.render_to_response(context)
def get_object(self, queryset=None):
obj = Subject_Enroll.objects.get(id=self.kwargs['id'])
return obj
i try with pass form in context of Detilviewmixin
class DetailViewMixin(object):
"""Mixin to handle different DetailView variations."""
model = Subject_Enroll
#slug_field = 'translations__slug'
def get_context_data(self, **kwargs):
context = super(DetailViewMixin, self).get_context_data(**kwargs)
#context['form'] = Subject_EnrollForm
#context['form'] = Subject_EnrollForm()
return context
def get_queryset(self):
#return Subject_Enroll.objects.all()
return Subject_Enroll.objects.lang(self.request, False)
in that form are render on template but when i press save button so it can't save record
from this code i get all field access in "subject_enroll/subject_enroll_detail.html" like {{ object.student_name }}
{{ object.enroll_status }}
so it gives value of that field but now i want to edit record in subject_enroll_detail.html template like s
subject_enroll values "draft" to "submit" with click on some buttons in subject_enroll_detail.html template
i tried with form view and updateview but can't find solution
pls help!!!
Thanks in advance!!
from django.views.generic import UpdateView
class StudentRegistrationUpdateView(UpdateView):
model = StudentRegistration
form_class = Subject_EnrollForm #don't need if you are editing all the fields
template_name = 'subject_enroll/add_subject_enroll.html'
https://docs.djangoproject.com/en/1.7/ref/class-based-views/generic-editing/#updateview
in your urls.py
import StudentRegistrationUpdateView
in urls.py don't forget to include 'pk' like below, this determines which object to be updated
url(r'student/(?P<pk>\d+)/update/$', StudentRegistrationUpdateView.as_view(), name='student_registration_update'),