I have implemented two views to display data according to the choice_fields but i have two views with slightly different logic in views and templates how do i combine them into one so that i take care of DRY
views.py:
class View1(LoginRequiredMixin,TemplateView):
template_name = 'temp1.html'
def get_context_data(self, **kwargs):
context = super(View1,self).get_context_data(**kwargs)
context['progress'] = self.kwargs.get('progress', 'in_progress')
if context['progress'] == 'in_progress':
context['objects'] = Model.objects.filter(progress='in_progress')
else:
context['objects'] = Model.objects.filter(progress__iexact=context['progress'], accepted=self.request.user)
return context
class View2(LoginRequiredMixin,TemplateView):
template_name = 'temp2.html'
def get_context_data(self, **kwargs):
context = super(View2,self).get_context_data(**kwargs)
context['progress'] = self.kwargs.get('progress', 'in_progress')
if context['progress'] == 'in_progress':
context['objects'] = Model.objects.filter(progress='in_progress',created = self.request.user)
else:
context['objects'] = Model.objects.filter(progress__iexact=context['progress'], created_by=self.request.user)
return context
Implement something like get_queryset in Class-based views.
class BaseView(LoginRequiredMixin,TemplateView):
""" requires subclassing to define template_name and
update_qs( qs, progress) method """
def get_context_data(self, **kwargs):
context = super(View1,self).get_context_data(**kwargs)
progress = self.kwargs.get('progress', 'in_progress')
if progress == 'in_progress':
qs = Model.objects.filter(progress='in_progress')
else:
qs = Model.objects.filter(progress__iexact=context['progress'] )
qs = self.update_qs( qs, (progress == 'in_progress') )
context['progress'] = progress
context['objects'] = qs
return context
class View1( BaseView):
template_name = 'temp1.html'
def update_qs( self, qs, in_progress):
if in_progress:
return qs
else:
return qs.filter( accepted=self.request.user)
class View2( BaseView):
template_name = 'temp2.html'
def update_qs( self, qs, in_progress):
if in_progress:
return qs.filter( created = self.request.user)
else:
return qs.filter( created_by=self.request.user)
Related
I use a CB ListView for displaying objects. I want to add a session variable based on another models' PK during the execution of my ListView:
views.py
class ProduitListView(LoginRequiredMixin, ListView):
model = Produit
context_object_name = "produits"
paginate_by = 10
template_name = 'products/produits.html'
ordering = ['-mageid', ]
def get_context_data(self, *args, **kwargs):
context = super(ProduitListView, self).get_context_data(
*args, **kwargs)
# used for incoming products (sourcing cf URLS)
supplier_pk = self.kwargs.get('pk', None)
if supplier_pk:
set_incoming_supplier(self.request, supplier_pk)
context['avail_warehouses'] = Warehouse.objects.all()
context['js_warehouses'] = serialize(
'json', Warehouse.objects.all(), fields=('code', 'id', ))
context['title'] = 'Produits'
return context
set_incoming_supplier (in another APP)
#login_required
def set_incoming_supplier(request, pk):
supplier = Supplier.objects.filter(pk=pk).first()
supp = SupplierSerializer(instance=supplier).data
rs = request.session
if 'income' in rs:
if 'cur_supplier' in rs['income']:
prev_supplier = rs['income']['cur_supplier']
if supp != prev_supplier:
return render(request, 'sourcing/alert_supplier_change.html',
{'prev_supplier': prev_supplier, 'cur_supplier': rs['income']['cur_supplier']})
rs['income'] = {'cur_supplier': supp}
I thought the return render(request, 'sourcing/alert_supplier_change... could "break" my ListView and render my alert page but it doesn't. ListView seems to continue and finally renders my ProduitListView page.
Why doesn't this work ?
Finally found a solution that consists in using get() method within my CBV. In it, I evaluate my supplier with set_incoming_supplier() that returns a context or None. According to this evaluation, I render either the regular template or my alert template.
ProduitListView(LoginRequiredMixin, ListView):
class ProduitListView(LoginRequiredMixin, ListView):
model = Produit
context_object_name = "produits"
paginate_by = 10
template_name = 'products/produits.html'
ordering = ['-mageid', ]
def get_context_data(self, *args, **kwargs):
context = super(ProduitListView, self).get_context_data(
*args, **kwargs)
context['avail_warehouses'] = Warehouse.objects.all()
context['js_warehouses'] = serialize(
'json', Warehouse.objects.all(), fields=('code', 'id', ))
context['title'] = 'Produits'
return context
def get(self, request, *args, **kwargs):
supplier_pk = self.kwargs.get('pk', None)
if supplier_pk:
context = set_incoming_supplier(self.request, supplier_pk)
if context:
return render(request, 'sourcing/alert_supplier_change.html', context)
return super().get(request, *args, **kwargs)
set_incoming_supplier()
def set_incoming_supplier(request, pk):
supplier = Supplier.objects.filter(pk=pk).first()
supp = SupplierSerializer(instance=supplier).data
rs = request.session
if 'income' in rs:
if 'cur_supplier' in rs['income']:
prev_supplier = rs['income']['cur_supplier']
if supp != prev_supplier:
return {'prev_supplier': prev_supplier, 'cur_supplier': supp}
rs['income'] = {'cur_supplier': supp}
Maybe not the best way but it works well.
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 want pagination of following UserListView
class UserListView(LoginRequiredMixin, generic.TemplateView):
template_name = 'users/users.html'
paginate_by = 1
def get_context_data(self, **kwargs):
context = super(UserListView, self).get_context_data(**kwargs)
context['companies'] = Company.objects.exclude(company_is_deleted=True).exclude(company_name='Apollo')
context['users'] = User.objects.filter(userprofile__user_role__id=2).exclude(
Q(is_superuser=True) |
Q(userprofile__user_is_deleted = True)|
Q(userprofile__user_company__company_is_deleted=True)
)
query = self.request.GET.get('query')
if query:
list_query = context['users']
context['users'] = list_query.filter(userprofile__user_company__company_name__icontains=query)
return context
class UserListView(LoginRequiredMixin, generic.ListView):
template_name = 'users/users.html'
paginate_by = 1
context_object_name = 'users'
def get_queryset(self, *args, **kwargs):
qs = User.objects.filter(userprofile__user_role__id=2).exclude(
Q(is_superuser=True) |
Q(userprofile__user_is_deleted = True)|
Q(userprofile__user_company__company_is_deleted=True)
)
query = self.request.GET.get('query')
if query:
qs = qs.filter(userprofile__user_company__company_name__icontains=query)
return qs
def get_context_data(self, **kwargs):
context = super(UserListView, self).get_context_data(**kwargs)
context['companies'] = Company.objects.exclude(company_is_deleted=True).exclude(company_name='Apollo')
return context
If you need custom pagination you should take a look at the docs
my code is
class Leads(LoginRequiredMixin, ListView):
def get_queryset(self):
q = self.request.GET.get('q', "all")
if q == "customer":
qs = alllead.objects.filter(isCustomer="yes")
elif q == "lead":
qs = alllead.objects.filter(isCustomer="no")
else:
qs = self.queryset
return qs
def get_context_data(self, **kwargs):
context = super(Leads, self).get_context_data(**kwargs)
count = self.queryset.count()
context['count'] = count or "000"
return context
so i am filtering my queryset and also i need to set record count as context parameter "count"
but the number of record is not updating
so i have changed my code to
def get_queryset(self):
q = self.request.GET.get('q', "all")
if q == "customer":
qs = alllead.objects.filter(isCustomer="yes")
elif q == "lead":
qs = alllead.objects.filter(isCustomer="no")
else:
qs = self.queryset
return qs
def get_context_data(self, **kwargs):
context = super(Leads, self).get_context_data(**kwargs)
q = self.request.GET.get('q', "none")
if q == "customer":
count = alllead.objects.filter(isCustomer="yes").count()
elif q == "lead":
count = alllead.objects.filter(isCustomer="no").count()
else:
count = self.queryset.count()
context['count'] = count or "000"
return context
i think i am duplicating code and this is not the proper way to do it.
can anyone suggest me the optimal way to update
context['count'] = qs.count()
#inside get_queryset()
Once you've called the superclass get_queryset(), then the qs is added to the context as alllead_list; you can just access it from there.
def get_context_data(self, **kwargs):
context = super(Leads, self).get_context_data(**kwargs)
count = context['alllead_list'].count()
However, I don't think you need to do this in the view at all; you can just as easily do this in the template by accessing {{ allead_list.count|default:"000" }}.
Edit Since the queryset is paginated, you can get the count directly from the paginator: context['paginator'].count or in the template {{ paginator.count }}.