How do I preserve search result in Django pagination - python

I am new to Django and I have develop form with Country and State field from the Profile Model. If I search for country and a particular state, I want a list of persons belonging to that country and state to display and paginated. And if the records are in multiple pages then I should be able to click on individual pages that follow to view the searched results on those pages without losing the search results.
Here is my views code with pagination.
def search_applicants(request):
form = ApplicantsSearchForm(request.GET or None)
if form.is_valid():
list_submited = Profile.objects.filter(
nation__icontains=form.cleaned_data['nation'],
state__icontains=form.cleaned_data['state']
)
else:
list_submited = submited_apps.objects.all()
paginator = Paginator(list_submited, 5)
page = request.GET.get('page')
paged_listApps = paginator.get_page(page)
context = {
'list_applicants':paged_listApps,
'form':form,
}
return render(request, 'user/list_applicants.html',context)
I have got the pagination of all records from the Profile Model but any time I perform a search and try to click on the pagination tabs the search result is get scattered and returns to all the list items in the database.

On the front-end you need to submit your search data when clicking on your pagination tabs as well.

Related

Add page loading while scraping process

I created a view using django that displays a search engine to type in the name of the product to be scraped and starts the scraping process.
Also, I created a view as a loading page that I want to be displayed when I start the scraping and disappear when the scraping finishes and display the datatable as mentioned in my code.
Here is my view.py :
def home_view(request):
context = {}
context ['form'] = Scraping()
# if user inserted into form and validated the form
if request.method =='POST':
form= Scraping(request.POST)
if form.is_valid():
# get variable (nom product)
subject = form.cleaned_data['subject']
# remove space and replace it with a + sign
sbjt = subject.replace(" ","+")
# call scrapy command line with this variable
os.chdir('C:/Users/aicha/Desktop/new_version/django_project/aliScrap/scraper/codes/aliscraper/')
os.system("scrapy crawl aliproduct -a product=" + sbjt)
# get results from database
client = MongoClient("mongodb://localhost:27017/")
db = client["aliexpress"]
col = db["listproducts"]
products = col.find()
context = {'products' : products}
return render(request,'datatable.html', context)
# default page
return render(request,'index.html', context)
Page loading view :
def loading_view(request):
return render(request,'loading.html')
Knowing that I have already prepared the html of my loading page.
The issue is that I don't know how to integrate my loading page after starting the scraping.
I think that it should appear after the execution of this line of code :
os.system("scrapy crawl aliproduct -a product=" + sbjt)
and disappear before this line of code :
return render(request,'datatable.html', context)
I will be so grateful if you help me fixing that problem because I am pretty new using django.
Thank you in advance !

Pagination with function based view with dictionary

I'm trying to paginate the pages with the help of Paginator. Have written this so far but I don't understand what would I pass in the context. Simply doing this doesn't work, I think my knowledge with Paginator is limited.
customerproducts = customerproductsjsondata.json()
customerproducts_list = customerproducts['data']
paginated_products = Paginator(customerproducts_list, 20)
You may want to return multiple things, like queryset for the current page, current page number, whether there is prev or next page, number of total records, number of total pages based on the offset.
You need to get the page from Paginator depending on the page number:
page_number = request.data.get('page_num')
page = paginated_products.page(page_number)
total_records = paginated_products.count
total_pages = paginated_products.num_pages
queryset = page.object_list
has_prev = page.has_previous()
has_next = page.has_next()
but you can User DRF's included pagination support by following the link https://www.django-rest-framework.org/api-guide/pagination/

Django: User Reporting Some URL on Website

So i'm trying to build something, so that users would be able to report something on site. Here's the model,
class Report(models.Model):
reporting_url = models.URLField()
message = models.TextField()
I created Form for this Model including 'message' field only because 'reporting_url' is something it needs to populate by itself depending upon the specific page from where user has clicked "Report" button.
def report(request):
url_report = ???
if request.method == 'POST':
form = ReportForm(request.POST or None)
if form.is_valid():
new_form = form.save(commit=False)
new_form.reporting_url = url_report
new_form.save()
I was wondering How can I pass the specific url to 'reporting_url' field in form depending on the Page from where user has clicked "Report" button? (Much like s we see on social Networks).
Am I doing this correctly, Or is there a better way for doing this?
Please help me with this code. Thanks in Advance!
If there is a report button on that specific page then I believe you could write custom context processor.
More info: Django: get URL of current page, including parameters, in a template
https://docs.djangoproject.com/en/1.11/ref/templates/api/
Or maybe just write it directly in the views.py in your function and set
url_report = request.get_full_path()
I think you can use the form on the same page of the URL and use:
url_report = request.get_full_path()
in the view, to get the current URL.
Else if you want to create a separate view for the reporting form. You can use
url_report = request.META.get('HTTP_REFERER')
to get the previous or refering URL which led the user to that page.
request.META.get('HTTP_REFERER') will return None if it come from a different website.

Queryset not displayed in django admin interface

I am creating a Django application and trying to include more search boxes in Django web admin interface for a specific model, so that users can simultaniously search more fields. For example, users can enter in one search box the name of the city, and in another search box the name of the street, and all model instances which have corresponding city and street are shown in browser after 'Search' button is hit. Default admin web interface has only one search box. I've added three search boxes in change_list.html file, and when I enter some data in those search boxes in browser and hit 'Search', a proper URL is formed (with query string containing those three input parameters by which the search shoould be done). Then I capture those input parameters in queryset method which I have overriden in my class that extends models.AdminModel calss, perform query set filtering and finally return the filtered queryset. Now, the problem is that the filtered query set is simply not shown on the web page (web interface of my model) after the search process is done, it says that no matches were found. But I am definately sure that my filtered query set contains data beacues I print it in command line just before the return command of queryset method is executed, and it prints correct data.
Here is my queryset method:
def queryset(self, request):
qs = super(UkopcanjeAdmin, self).queryset(request)
if "mjesto" in request.GET:
lokacija = request.GET.get('mjesto',None)
if lokacija:
qs = qs.filter(mjesto__icontains=lokacija)
if "ulica" in request.GET:
ulica = request.GET.get('ulica',None)
if ulica:
qs = qs.filter(ulica__icontains=ulica)
if "naziv" in request.GET:
naziv = request.GET.get('naziv',None)
if naziv:
qs = qs.filter(naziv__icontains=naziv)
print qs #this prints correct filtered data
return qs
Why isn't filtered query set shown in web interface?
EDIT : Thanks to my friend, I've finally managed to solve the problem. And solution is quite simple, all I had to do is move the whole code of queryset method to get_search_results method, and along filtered queryset return false boolean parameter (because get_search_results method returns two parameters). So if anybody wants to customize the search process in Django, the get_search_results method should be used. There you can access query string argumnets and retreive some data the way you want.
I think it should be get_queryset but not queryset method.
def get_queryset(request):
#your code here
queryset = super(UkopcanjeAdmin, self).get_queryset(request)
if 'miesto' in request.GET:
print 'Yes'
return queryset
else:
print 'No'
Here is some short explanation from Django docs.

Django Links by Month

I'm having trouble figuring out how to create links on a blog I'm making. I want my index page to have links to blog posts grouped by year/month.
Here is my view that will display the all the blog posts by month/year (the url will look like 2014/10 if I want to see the blog entries from October 2014):
def month(request, year, month):
month_entry_list = Entry.objects.filter(pub_date__year=year, pub_date__month=month)
return render(request, 'blog/list_post_by_month.html', {
'month_entry_list': month_entry_list
})
Here is my index view:
def index(request):
# latest_entry_list = Entry.objects.order_by('-pub_date')[:5]
entries = Entry.objects.all().order_by('-pub_date')
latest_entry_list = entries[:5]
template = loader.get_template('blog/index.html')
context = RequestContext(request, {
'latest_entry_list': latest_entry_list
})
return HttpResponse(template.render(context))
I have an idea of how to go about this but I'm not sure it's optimal. Should I just query the database to get a list of all the year/month combinations, and use that to create links in the index template?
Maybe you could keep the relevant month-years in server-side cache (https://docs.djangoproject.com/en/dev/topics/cache/) and just update it occasionally by appending to it (i.e. just checking for more posts since the last month that had one.)

Categories