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')
Related
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
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
What is meant is, I want to save only one object with is_featured field true, if user tried to save another object with is_featured field true it needs to give a prompt, How can i accomplish that in django any idea?
class Event(BaseModel):
title = models.CharField(max_length=200)
time = models.TimeField()
date = models.DateField()
location = models.CharField(max_length=200)
location_url = models.URLField()
description = models.TextField()
is_featured = models.BooleanField(default=False)
image = VersatileImageField('Image', upload_to="web/events")
class Meta:
db_table = 'web_event'
verbose_name = ('Event')
verbose_name_plural = ('Event')
ordering = ('auto_id',)
def __str__(self):
return str(self.title)
You can add a check that if event is already created with is_featured true then you can return error else you can create instance
if Event.objects.filter(is_featured=True).exists():
return Response({"error":"Featured Event Already Exists"})
else:
Event.objects.create(**data)
```
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__')
Hi I´m using django with haystack search. I have one model for Events. Thats the model I'm doing the search on. I have a second model to count the hits/views for the Events. I wan't to return the number of hits for every event additional to the search results.
my view:
def event_search(request):
if request.method == 'POST':
query = str(request.POST['search'])
events = SearchQuerySet().auto_query(query).models(Event).order_by('date')
return render_to_response('event_search.html', {"events": events}, context_instance=RequestContext(request))
else:
return render_to_response('event_search.html', context_instance=RequestContext(request))
my models:
class Event(models.Model):
name = models.CharField(max_length = 70)
date = models.DateTimeField()
description = models.TextField()
active = models.BooleanField(default=True, editable=False)
featured = models.BooleanField(default=False)
class EventHitcount(models.Model):
hit = models.ForeignKey(Event)
ip = models.CharField(max_length=40)
session = models.CharField(max_length=40)
created = models.DateTimeField(default=datetime.datetime.now())
By giving the ForeignKey field a related name it can call and count the related objects.
class Foo(models.Model):
fk = models.ForeignKey(Event,related_name='foofk')
some more fields...
In the template:
{{ foo.foofk.count }}