Thank You, trying to show the created_date field to the front table but i get an error, if i don't filter and use the all() method i am able to populate all the field data, but i would like to populate created_date field of member.I Get KEY ERROR "list_id"
class ListListView(ListView):
model = HBTYList
template_name = "accounts/modals/nomodal/index.html"
paginate_by = 3
def get_queryset(self):
qs = self.model.objects.all().order_by('-id')
p_f = HbtyCustomerListFilter(self.request.GET, queryset=qs)
return p_f.qs
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['dc'] = HBTYItem.objects.filter(hbty_cust_id=self.kwargs["list_id"]) #Fix this method to show created_data
context['filter'] = HbtyCustomerListFilter(self.request.GET, queryset=self.get_queryset())
return context
Related
When i add aggregate function on my get_context_data it shows the total for all members and not according to there ID. Thank You
ItemListView
class ItemListView(ListView):
model = HBTYItem
template_name = "accounts/modals/nomodal/todo_list.html"
paginate_by = 2
ordering = ['id']
def get_queryset(self):
return HBTYItem.objects.filter(hbty_cust_id=self.kwargs["list_id"])
def get_context_data(self):
context = super().get_context_data()
context['t_sum'] = HBTYItem.objects.aggregate(Sum('price'))
context["hbty_list"] = HBTYList.objects.get(id=self.kwargs["list_id"])
return context
If you have user filed in HBTVItem you can use:
HBTYItem.objects.filter(user=self.request.user).aggregate(Sum('price'))
Or you can apply filter on any field you want it
I have the following model 'ARTICULO', which I have created and templates to edit it individually
# MODEL
class Articulo(models.Model):
id = models.AutoField(primary_key=True, verbose_name='codigo')
nombre = models.CharField(max_length=100, verbose_name='nombre elemento')
cantidad = models.PositiveSmallIntegerField(verbose_name='cantidad total')
cantidad_disponible = models.PositiveSmallIntegerField(verbose_name='cantidad disponible', default=5)
UNIDAD = 'und'
KILO = 'kg'
LITRO = 'L'
UNIDADES_BASE = [
(UNIDAD, 'unidades'),
(KILO, 'Kilogramos'),
(LITRO, 'litros'),
]
unidades = models.CharField(max_length=3, choices=UNIDADES_BASE, default=UNIDAD, verbose_name='unidad base')
area = models.CharField(max_length=100, verbose_name='tipo inventario', default='primaria')
persona_asignada = models.CharField(max_length=100, default='almacen', verbose_name='persona asignada')
def __str__(self):
trama = "articulo: " + self.nombre
return trama
#form to edit individually
class ArticuloEditarForm(forms.ModelForm):
class Meta:
model = Articulo
fields = ['nombre', 'cantidad', 'unidades']
# view for generate form of individual article
def editar(request, id):
articulo = Articulo.objects.get(id=id)
formulario = ArticuloEditarForm(request.POST or None, instance=articulo)
if formulario.is_valid() and request.POST:
formulario.save()
return redirect('inventario_inicio')
return render(request, 'inventario/editar.html', {'formulario': formulario})
but additionally I would like to create a page where I can perform an update of all the records of the table as a whole (as in the following image)
When clicking on the button, all records with the checkbox activated are updated in the database according to the value indicated in their text box.
From what I have investigated so far, I think I understand that I should use the form.Form class and not form.ModelForm in combination with formsets, but in the attempts I have made, I tried trying to define a form in this way, but it does not work for me.
class AsignarReservasArticulos(forms.Form):
articulos = Articulo.objects.all()
for x in articulos:
print(x)
participa = forms.BooleanField(label='')
My deduction tells me that I must generate the form that I show in my image in an integral way from my FORM or I must make a part in the form and another in the view.
Django newbie here..
I am working on a project that I need to do search in Django Admin Panel.
I have a model named SearchModel and it has colums named "id", "word" and an object called Desert and this object has '1' as id
I have another model named Result000 ('000' refers to the first three letters of md5 of "Desert" word). It has columns named "id", "word_id", "score", "title" and has an object named "Sahara Desert" whose word_id is the same as the id of the Desert object in the first table.
No ForeignKey or any other relation types between those table's items
here's the question:
When I search for Desert in SearchModel's search field. I want to list all objects in table Result000 which have word_id same as id of Desert object in SearchModel
here's my current code:
# root/admin.py
class BookAdmin(admin.ModelAdmin):
def __init__(self, model, admin_site):
self.list_display = [field.name for field in model._meta.fields]
self.search_fields = [field.name for field in model._meta.fields]
self.temp_model = "SearchModel"
self.temp_term = ""
self.word_id = None
self.search_term = self.temp_term
super().__init__(model, admin_site)
def get_search_results(self, request, queryset, search_term):
queryset, may_have_duplicate = super().get_search_results(
request, queryset, search_term
)
if len(search_term) > 0: self.search_term = search_term
else: self.search_term = self.temp_term
hashable, ret = self.md5_er(LowerTurkish(self.search_term).lower())
if hashable: table_name = f"Result{ret}"
else: table_name = request.path_info.split("/")[-2]
try:
# modelname = apps.get_model("root", table_name)
modelname = self.model_finder(table_name)
print("try içinde modelname: ", modelname)
messages.info(
request,
f"`{table_name}` modeli içindeki arama sonuçları")
word_id = self.model_finder(self.temp_model).objects.values_list("id")
std_content = modelname.objects.filter(word_id=word_id)
queryset = std_content
except:
std_content = self.model_finder(self.temp_model).objects.all()
# "nonetype not iterable" hatasının çözümü
return queryset, may_have_duplicate
def model_finder(self, table_name):
return apps.get_model("root", table_name)
def md5_er(self, data):
"""
:#params: data: md5 hashi alınacak olan veri, type: string
"""
hash_object = hashlib.md5(data.encode())
md5_hash = hash_object.hexdigest()
if md5_hash != "d41d8cd98f00b204e9800998ecf8427e":
"d41d8cd98f00b204e9800998ecf8427e refers md5 of empty string"
ret = md5_hash[:3]
return True, ret
else:
return False, False
I can get what I want if the SearchModel and Desert table have the same column names, but it doesn't work when the column names are changed. I've read almost all of Django's documentation, looked up examples from the internet, and looked at almost all entries on stackoverflow but as I said I'm Django newbie 🥲. Thanks in advance
I'm working on an export resource but I can't figure out how to pass this field from the view as a column in my export.
issues = Student.objects.annotate(Count('issue'))
def view_student(request):
issues = Student.objects.annotate(Count('issue'))
students = Student.objects.filter(school = request.user.school).order_by('year')
return render(request, 'view_student.html', {'students': students,'issues':issues})
This is how I tried it in the resoucrces.py but it shows no result
class ExportStudentsResource(resources.ModelResource):
books = fields.Field(attribute = 'books',column_name='books',widget= ForeignKeyWidget(Student, 'issue_count'))
class Meta:
model = Student
fields = ('student_id','name','year','klass','stream','books')
This field is not from any model so I just thought Student model could be habouring it. How can I make it work
You can override the .get_queryset(…) method [Django-doc] and annotate your Student objects with:
from django.db.models import Count
class ExportStudentsResource(resources.ModelResource):
books = fields.Field(
attribute='books',
column_name='books',
widget= ForeignKeyWidget(Student,'issue_count')
)
issues_count = fields.Field(attribute='issue_count')
def get_queryset(self):
return super().get_queryset().annotate(
issue_count=Count('issue')
)
class Meta:
model = Student
fields = ('student_id','name','year','klass','stream','books')
I've a django Form with 2 choices (yes and no), on my "create page" i can render the select field to save the data and it works just fine, when i try to use on the "edit page" the value is not pre-selected with the current value, how can i make the current value selected on the select input field?
The form:
class MyForm(forms.ModelForm):
choose = forms.BooleanField(
required=False,
widget=forms.Select(
choices=[(1, 'Yes'), (0, 'No')],
attrs={'class': 'form-control'}
)
)
class Meta:
model = MyModel
When i call the view to edit:
class MyUpdateView(
LoginRequiredMixin,
SuccessMessageMixin,
UpdateView,
):
model = MyModel
form_class = MyForm
template_name = "my/template.html"
success_url = reverse_lazy('my-url')
success_message = 'Updated!'
def get_object(self, queryset=None):
data = super(MyUpdateView, self).get_object()
if not data.user == self.request.user:
raise Http404
# data.choose is False
return data
The HTML input will be always "1" (Yes) even tough the current value is "0" (No)
The HTML:
{{ form.choose }}
The Model:
class MyModel(models.Model):
choose = models.BooleanField(
default=False,
verbose_name='Cumulativo'
)
add this to your MyUpdateView:
initial = { 'choose': 1 }
You are defining the custom field 'choose' in the form, which does not refer to MyModel field 'choose'. that's why you are always getting the first value 'Y' as default or the first value 'Y' in the dropdown.
If you want to refer to your model object, you can simply use self keyword in the form
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['choose'].widget.attrs['class'] = 'form-control'
class Meta:
model = MyModel
fields = ('__all__')