django pagination by giving textbox inputs - django

I'm a new pratikant and when i joined in the company they gave me the task of configuring number of items per page by giving textbox input for example i created a textbox in html and submmit button and now i want to insert some value say 2 then it should show me first 2 records of the items in the same way 3, 4, 5 ,.......now for me the problem is i was unable to make or attch or call my html code into views.py i mean i was able to make he static pagination
eg :
table.paginate(page=request.GET.get("page", 1), per_page = 10)
like this but now what i want is when i give input to the textbox,, PER_PAGE must be changed according to the given input like 2 records or 4 or n records
i donno whether it is easy or tough but im a starter of python programming and learning still i was unable to make it please help me
Fella student
Thanks in advance

Use
table.paginate(page=request.GET.get("page", 1), per_page = request.GET.get("per_page", 10))
That way 10 will be the default value if "per_page" wasn't passed.

Related

Better way to query and join multiple querysets other than using a forloop in django?

I have a model Item:
Item:
batch_no
batch_no can be anything from 1 to 20. And there are 1000s of items in the database.
Now. I need to get first 4 elements of each batch_no.
I know to do it by querying and appending using forloop.
batches = Item.objects.values('batch_no').exclude(batch_no__isnull=True).distinct()
blist=[]
for batch in batches:
bitems= Item.objects.filter(batch_no=batch['batch_no'])[:4]
blist.append(bitems)
return blist
Is there a better way than this? To do in a single Query?
I'm new to Django.
Here is a similar question. The short answer is:
Item.objects.annotate(rank=Window(
expression=Rank(),
order_by=F('batch_no').desc(),
partition_by=[F('batch_no')])
).filter(rank__lte=4)
Check out Rank window function in Django 2.0. It will allow you to grab Top N elements within a group as in an example here

Searching via multiple form fields?

I'm displaying a page with a 4 textboxes, each storing the user entered value into a separate variable.
My Database has 4 columns, each corresponding to one text box's variable.
I want to do this:
The user can enter values in 1,2,3 or all 4 of the textboxes, and I want to trim the search results according to each value that they've entered. Each textbox is optional.
How do I do this? I'm new at Django, and I only know how to search using one search term.
I think you need Q objects. See: https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects
From the docs:
Poll.objects.get(
Q(question__startswith='Who'),
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)
Translates to:
SELECT * from polls WHERE question LIKE 'Who%'
AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
You can populate the Q query from your cleaned form - you might even want to override clean() and return the queryset that way, so that you could just access the query set from the validated form.

How to create linked (associated) automatically updated form fields in GAE Django

I am new to Django and GAE. I would like to create two input fields, where the first one is a drop-down menu (let name it select), which decides the values in the second one (let name it val).
For example, once 'A' is chosen from 'select', field 'val' will show '1'. similarly, 'B' is associated to '10'. I have written several lines below, but it does not work. Two issues:
The second field ('val') always equals 0.
It seems like my second field ('val') does not 'listen' to the choice made by the first one ('select'), which means those two fields are not linked.
Can anyone give me some suggestions (or recommend books on using Django on GAE)? Thank you!
select_CHOICES=(('A','A'),('B','B'),('Other','Other'))
select = forms.ChoiceField(choices=select_CHOICES, initial='A')
def get_choices(select):
if select=='A':
r= 1
elif select=='B':
r= 10
else:
r= 0
return r
val=forms.FloatField(initial=get_choices(select))
I think you have understood how django works a bit wrong. The code that you input is run before the page is rendered, so no selection is made yet. If you want the input field to dynamically change as user makes the choise on page, you should use Javascript.
Also you are comparing a Field (select) to a string ('A'), which naturally always is unequal.
Read more documentation and tutorials and you'll soon get how it works.

I need some help understand Django form validators

I've read the Django documentation here:
http://docs.djangoproject.com/en/dev/ref/forms/validation/
I've also browsed a number of search results on Google and Stack Overflow, but I haven't been able to answer my questions below.
As an example, say I have a model named "Widgets" with a CharField named "product_name". Now say that I want to restrict the allowable characters in "product_name" to [a-zA-Z0-9] plus apostrophes, dashes and underlines (i.e. ' - _) and show a form error to the user if they enter a restricted character.
From the above research, I gather that I need to create a validation function somewhere to check for these characters.
My specific questions:
1. What is best practice as to where a validation function like this should live in my Django project?
2. From where do I call this validation function?
3. How do I show an error to the user if a "bad" character is entered?
4. Would someone be so kind as to post a sample validation function?
Thank you, I appreciate any help you can provide.
Go with Chefsmart's answer if you can. Here is an example of a sample validation function in case it helps:
class MyCustomInvoiceForm(forms.Form):
serial_number = forms.IntegerField(min_value = 1, initial = 1)
# Other fields. I am interested in serial_number.
def clean_serial_number(self):
serial_number = self.cleaned_data.get('serial_number')
if not serial_number:
return
return _my_custom_validation(serial_number)
def _my_custom_validation(self, serial_number):
serial_number = int(serial_number)
if not ((serial_number - 1) % 10 == 0):
message = "Serial number should be 1 or one greater than a multiple of 10 (Example: 1, 11, 21 etc.)"
raise forms.ValidationError(message)
return serial_number
This is a snippet of code from a project I did. The customer required some interesting verification logic for serial number.
If you are using a Django form, you have the option of using a RegexField for your product_name field. See http://docs.djangoproject.com/en/1.2/ref/forms/fields/#regexfield
That would be the cleanest approach for your situation.

Using breadcrumbs with django-filter, QueryDict trouble

I'm using django-filter to drill down and would like to create breadcrumbs for each item that was filtered. For example:
Price ranges:
10,000+
5,000-9,999
1,000-4,999
0-999
Bedrooms:
4
3
2
1
Each of the items under Price ranges and Bedrooms would be a link to drill down in a queryset.
I'd like to create a breadcrumb such as Price range 0-999 or Bedrooms 3 if the user were to click those links, and then show Price range 0-999 > Bedrooms 3 or Bedrooms 3 > Price range 0-999 when they click a second link.
The breadcrumbs should maintain order (the part I'm having trouble with) and work for any number of attributes. Clicking a link in the breadcrumb trail should apply the filter clicked on and all filters before it in the trail.
I'd like to create an empty QueryDict and then iterate through request.GET to build the QueryDict up as I output the breadcrumbs, but for some reason QueryDict iterates through its elements backwards (see the documentation).
What's the cleanest way to accomplish this? Does anyone know why QueryDict works this way? (I imagine there's a use-case I'm missing.) Any advice is appreciated.
keep track of the order in sessions. so when the first filter is clicked (eg 3 beds) store it. then if another one is clicked, build your bread crumbs from sessions. say the second one was 0-999 you'd pull any existing breadcrumbs (in this example you'd find the 3 beds) and then tack on the latest (0-999).