Search from every pages in django - python

i want to add search in my website and i want search from my pages (html)
** note : i want grab the label tag , i mean for example :
i have label tag called ' test ' and when user write in search bar 'test' i want view the label to user in new page
my label like this :
<label id="label_main_app">
<img id="img_main_app_first_screen" src="{% static " images/android_studio.jpg " %}" alt=""> test
<br>
<br>
<p id="p_size_first_page">this is an test app
<br>
<br>
<big> See More & Download </big>
</p>
</label>
always i got this message in result page : not found
my code : * this form in home html page
<form class="" action="{% url 'test_search_page'%}" method="get">
<div class="md-form mt-0 search-bar" id="search_form">
<input id="search_box" autocomplete="off" onkeyup="searchFunction()" class="form-control" type="text" placeholder="Write Here to Search ..." aria-label="Search" name="search">
</div>
</form>
and this is my view.py code :
def search(request):
input= 'search'
my_template_keyword = ['label']
if 'search' in request.GET and request.GET['search'] and input == my_template_keyword:
return render(request, 'home_page/testforsearch.html', {'search:':search})`
finally this is my code in html result page :
<div class="container">
{% if search %}
{{ search }}
{% else %}
<h2>not found</h2>
{% endif %}
</div>
any help please ?

I couldn't see the query for database search. Use generic display views like this:
from django.views.generic.list import ListView
from .models import Videos
class Search(ListView):
model = Videos
template_name = "/search.html"
paginate_by = 30
def get_queryset(self):
query = self.request.GET.get('search')
if query:
object_list = self.model.objects.filter(title__icontains=query)
else:
object_list = self.model.objects.none()
return object_list

Related

Create a preview screen in Django

I have a Django form that receives a text (that I copy from Google Classroom: a bunch of student comments). I use these comments to make student's attendance. What I want to achieve is:
Accessing /insertion/ url via GET user receive the page form as a response, to choose the class (class01, class02, etc) and to past the text
When the user clicks on submit in this form (post method), it is redirect to the same /insertion/ url, but now the form is bound to the data submited, and the page shows a preview page (based on a boolean variable I'm passing through context), showing what students are present and what are absent based on the text informed. At that page, a new submit button will be shown below a text like "if everything's ok, hit the ok button".
After click this ok button, a pdf will be generated and the user will be redirected to /files/ url, to see the generated pdf and previous generated pdf.
views.py
def insertion(request):
context = {}
if request.method == 'GET':
form = AttendanceDataForm()
context.update({"form": form})
if request.method == 'POST':
form = AttendanceDataForm(request.POST)
context.update({"form": form})
if form.is_valid():
lesson = form.cleaned_data['lesson']
raw_text = form.cleaned_data['raw_text']
# Get course students
course_students = md.Student.objects.filter(course_id=lesson.course_id)
# Get present students based on raw text informed
present_students = [s for s in course_students if s.full_name in raw_text]
# Get absent students based on raw text informed
absent_students = [s for s in course_students if s.full_name not in raw_text]
context.update({
"present_students": present_students,
"absent_students": absent_students,
"render_preview": True
})
context.update({"active_freq": True})
return render(request, 'core/insertion.html', context)
def files(request):
context = {}
if request.method == 'POST':
# How can I access all expensive calculation I did in the previous view?
context.update({"active_gen": True})
return render(request, "core/files.html", context)
insertion.html
<div class="row">
<div class="col-12 col-md-6">
<h3>Informar FrequĂȘncia</h3>
{% crispy form %}
</div>
<div class="col-12 col-md-6">
{% if render_preview %}
<div class="container">
<div class="row p-4 bg-white rounded mt-4">
<div class="col-12 col-sm-6">
<h5>Alunos presentes</h5>
<ul class="previewer-list">
{% for student in present_students %}
<li>{{ student.id }} - {{ student.full_name }}</li>
{% endfor %}
</ul>
</div>
<div class="col-12 col-sm-6">
<h5>Alunos ausentes</h5>
<ul class="previewer-list">
{% for student in absent_students %}
<li>{{ student.id }} - {{ student.full_name }}</li>
{% endfor %}
</ul>
</div>
</div>
<p class="mt-3">If everything's ok, hit the OK button</p>
<form method="post" action="{% url "core:files" %}">
{% csrf_token %}
<button type="submit" class="btn btn-primary">OK</button>
</form>
</div>
{% endif %}
</div>
</div>
I could get to implement 1 and 2, but 3 is a mistery right now. What I couldn't get is how I can access the expensive calculations I did in insertion view in the files view. How can I do that?
Here's a solution using session framework.
We'll save the calculations in the session and access those values in another view later.
For starters, we'll just save the ids (pk) of the students instead of the student instances because they are not JSON serializable [See note below].
def insertion(request):
# do expensive calucations ...
present_ids = [s.pk for s in present_students]
absent_ids = [s.pk for s in absent_students]
request.session['attendance_data'] = {
'present_ids': present_ids,
'absent_ids': absent_ids
}
def files(request):
attendance_data = request.session.get('attendance_data')
if not attendance_data:
# show error or something else ...
pass
present_students = md.Student.objects.filter(
pk__in=attendance_data['present_ids']
)
absent_students = md.Student.objects.filter(
pk__in=attendance_data['absent_ids']
)
# generate the pdf ...
Note: If you wish, you can also save the student instances in the session but you'll have to change the SESSION_SERIALIZER setting to use the PickleSerializer. See notes about session serialization.
You could submit the primary keys as form data in hidden fields. Just choose an appropriate delimiter based on your primary key (for example, don't delimit with a hyphen if you use a GUID primary key).
<form method="post" action="{% url "core:files" %}">
{% csrf_token %}
<input type="hidden"
name="present"
value="{% for s in present_students %}{{ s.pk }},{% endfor %}"
>
<input type="hidden"
name="absent"
value="{% for s in absent_students %}{{ s.pk }},{% endfor %}"
>
<button type="submit" class="btn btn-primary">OK</button>
</form>
Then in the view you can pick up the PKs in the view from the form data then request.
def files(request):
context = {}
if request.method == 'POST':
present_pks = request.POST.pop('present').split(',')[:-1]
absent_pks = request.POST.pop('absent').split(',')[:-1]
# do type conversions if needed
...
# Because we already have the pks separated, we can combine them
# for the query in order to do just 1 query
course_students = md.Student.objects.filter(pk__in=present_pks + absent_pks).all()
absent_students = []
present_students = []
for student in course_students:
if student.pk in absent_pks:
absent_students.append(student)
else:
present_students.append(student)

Django - retrieve api url from template and pass to views

I am using Cryptocompare.com api to load news from cryptocurrencies world. In the template I am looping through it show it on the home-page. I would like to add feature that if you click send button it will send an email to you with the link for the news you just clicked. What is the best way to do it? I tried that, but I dont know how to link the clicked element with the url in views.
def home(request):
# Grab Crypto News
api_request = requests.get('https://min-api.cryptocompare.com/data/v2/news/?lang=EN')
api = json.loads(api_request.content)
return render(request, 'crypto/crypto_home.html', {'api': api})
def SendLink(request):
if request.method == 'POST':
subject = 'Link to crypto news'
from_email = 'test#gmail.com'
message = 'Hello {}, here is your link:'.format(request.user)
to_email = [request.user.email]
send_mail(
subject,
message,
from_email,
to_email
)
return HttpResponseRedirect(reverse('crypto-home'))
Template:
{% for x in api.Data %}
<div class='col-sm'>
<div class="card">
<img class="card-img-top" src="{{ x.imageurl }}" alt="{{ x.source }}">
<div class="card-body">
<h5 class="card-title">{{x.title}}</h5>
<p class="card-text">{{ x.body|safe }}.</p>
<div class="btn-group btn-group-sm" role='group'>
Read More
<form method="post" action="{% url 'send_link' %}">
{% csrf_token %}
<button id="{{x.id}}" target="_blank" class="btn btn-primary">Send to e-mail</button>
</form>
</div>
</div>
</div>
</div>
{% endfor %}
I would like to add link from template 'x.url' to views to be able to add the link to the message variable. I also tried to link it via ID of the news but I am not able to pass it to the views. Any idea how I can do that? Thanks
It looks like you need to add a hidden field to your form for the URL you'd like to pass to your view:
<input type="hidden" id="URL" name="URL" value="{{x.url}}">
Once you have that variable in your view you should be able to add it to your email template.

How to get text inside <a> tag in views.py django via form action?

I have a list in my function in views.py and displayed them in the html page as tags.
When i click on any of the tag i need to get those text of tags in another function in views.py when the form is submitted.Please help.
def index(request):
vendor_data = requests.get('https://cve.circl.lu/api/browse').content
vendors = json.loads(vendor_data)
vendor_list = []
context = {}
for i in range(len(vendors['vendor'])):
vendor_list.append(vendors['vendor'][i])
paginator = Paginator(vendor_list, 50)
page_number = request.GET.get('page')
context['page_obj'] = paginator.get_page(page_number)
return render(request,'index.html',context)
index.html
<form action="{% url 'appVuldb:output' %}" method="POST" id="venform">
{% csrf_token %}
{%for vendor in page_obj%}
<ul>
<li>
<a href="javascript:void(0);" class="link" name="vendor_name"
onclick="document.forms['venform'].submit();">{{vendor}}
</a>
</li>
</ul>
{%endfor%}
</form>`
Use a hidden input:
<input type="hidden" value="{{ vendor }}" name="vendor_name"/>

add sections/cluster from users end in html via choices or any other approach

Suppose im saving a url from a texbox given by user the URL is submitted by user and its saved to my models and now what i wanna do is let the user add different sections/clusters such as technology,sports etc from his end suppose where he inputs the URL there itself he can define that cluster/section and save that particular URL to the particular section/cluster he made or selected in the option is the section/cluster was already there! could anyone help or give me a small example for the same? what would be a better approach do it with django choices or some other way?
TIA.
ill paste the current code below :
form.py
class UrlSaveForm(ModelForm):
class Meta:
model = UrlSaveModel
fields = ['the_url']
models.py (below)
class UrlSaveModel(models.Model):
the_url = EmbedVideoField()
desc = models.CharField(max_length=200)
def __str__(self):
return self.desc
HTML for saving: save.html
{% extends 'base.html' %} {% block content %}
<form method="post" action="{% url 'func' %}">
{% csrf_token %}
<div class="form-group">
<label for="exampleFormControlTextarea1"
>Enter the URL here to save video to the library:</label
>
<textarea
class="form-control"
id="exampleFormControlTextarea1"
rows="2"
name="the_url"
placeholder="Enter the URL here"
></textarea>
<br />
<button type="submit" class="btn btn-primary mb-2">Save URL</button>
</div>
</form>
{% endblock %}
"""and little snippet of views.py"""
if form.is_valid():
print('form is valid')
posted_url = request.POST['the_url']
yt = YouTube(posted_url)
description = yt.title
print('description-extracted:', description)
print('Posted_url', posted_url)
obj = UrlSaveModel(desc=description, the_url=posted_url)
obj.save()
return HttpResponse('saved sucessfully!')

Passing variable with POST in django

Hi im trying to pass a name from a form to a view in django using POST. There are no errors in the execution but its passing nothing from the template and dont know if i doing something wrong here. Im starting with django so i can have newbie errors. If u need more information tell me pls.
Views.py
def crear_pdf(request):
empresa_selec = ""
form = EmpModelForm()
if request.method == 'POST':
form = EmpModelForm(data=request.POST)
if form.is_valid():
empresa_selec = form.cleaned_data['nombre']
#"empresa_selec" that's the empty variable
Models.py
class Empresa_modelo(models.Model):
nombre = models.CharField(max_length=100,blank=True,null=True)
Forms.py
class EmpModelForm(forms.ModelForm):
class Meta:
model = Empresa_modelo
fields = ["nombre"]
template.html
<div class="container-fluid">
<form method="POST" enctype="multipart/form-data" action="{% url 'crear_pdf' %}">{% csrf_token %}
<p>Empresa</p>
<input type="text" name="empresa">
<br>
<button type="submit">Subir</button>
</form>
<br>
<a class="btn btn-primary" href="{% url 'crear_pdf' %}">Atras</a>
</div>
You haven't got a field called nombre in your template; you only have empresa.
That's presumably because you don't ouput your EmpModelForm in the template. You don't show your render call in the view, but assuming you pass it as form, you should just do {{ form.as_p }} in the template.
Try using:
<input type="text" name="nombre">
There is no field named empresa.
Had a look at your code,there are a couple of issues.First you are not using the model form defined in your forms.py file in your template. Second you have defined an input text box with the name that you are not referring in your views. Either use the model form or use the same name of your input text box in your views.
def crear_pdf(request):
empresa_selec = ""
form = EmpModelForm()
if request.method == 'POST':
form = EmpModelForm(data=request.POST)
if form.is_valid():
empresa_selec = form.cleaned_data['nombre']
else:
return render(request,"template.html",{"form":form})
And in your template you can edit as such:
<div class="container-fluid">
<form method="POST" enctype="multipart/form-data" action="{% url 'crear_pdf' %}">{% csrf_token %}
{{ form.as_p }}
<br>
<button type="submit">Subir</button>
</form>
<br>
<a class="btn btn-primary" href="{% url 'crear_pdf' %}">Atras</a>
</div>
Hope this helps.

Categories