pass GET parameter to href link - python

I have question and don't know how to express it to find the answer
when I go to : http://127.0.0.1:8000/image/test/?title="test"
and then want to go to another page,it will go to : http://127.0.0.1:8000/image/test/?page=2"
I kow it should go to: http://127.0.0.1:8000/image/test/?title="test&page=2"
But don't know how to do it
How can I edit the url to pass the parameter(title="test) to go to the correct url ?
And I have a second question about urls too
if I'm now on path
http://127.0.0.1:8000/image/test/?title="test
How can I write the absolute href to go to http://127.0.0.1:8000/image/test/ ?
Please help me Thanks
test.html :
<form action="" method="get" class="searchtitle">
search title:<input type="text" name="title">
<button type="submit" value="submit" >search</button>
</form>
...
<div class="pagination">
<span class="step-links">
{% if contacts.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.
</span>
{% if contacts.has_next %}
next
{% endif %}
<form action="" method="get">
<td>GO to</td>
<td><input name="page" type="text" ></td>
td> page </td>
<td><input type="submit" value=" go to page "></td>
</form>
</span>
views.py:
def object_list_1(request, model):
if request.GET.get("title", None):
search_term = request.GET['title']
cls = get_model('mongo', model)
obj_list = cls.objects.filter(title__contains=search_term)
results = get_paginator(request, obj_list, 10)
template_name = 'filterimgs/%s_list.html' % model.lower()
return render_to_response(template_name, {'object_list': obj_list,'contacts': results},
context_instance=RequestContext(request))

The problem is this <a href="?page={{ contacts.previous_page_number }}">; here you are ignoring any query string (the ?title="test" part).
To fix this problem, you need to first enable the request template context processor, and then update your template so that it includes the full URL, like this:
<a href="{{ request.get_full_path }}&page={{ contact.previous_page_number }}">

Related

Get value from post method to views from a for loop

I am trying to get a value from template to views.py of a django project. I am able to get the value of name="city" correctly but unable to get the exact value of name="category" in my views, instead I am getting the first element value for all the other elements in the loop. An idea to solve this will be very much helpful.
#category.html
{% for test in mytypes %}
<form id="myform" action="{% url 'my_city_category' %}" method="POST">
{% csrf_token %}
<a href="javascript: submitform()">
<div class="col-6 col-lg-3 col-md-4 col-sm-6 col-xl-2 hover-box mt-2 text-center">
<div class="pb-1 pt-2">
<img src="{{test.icon_image.url}}" width="100"/>
<h6 class="mt-3 text-body text-capitalize text-decoration-none">{{ test.category_type }}</h6>
<input type="hidden" name="category" value="{{ test.category_type }}"># unable to repeat the value while calling it in the views, stuck at the first value
<input type="hidden" name="city" value="{{ city }}"> #rendering the exact value
</div>
</div>
</a>
</form>
{% empty %}
<h6 class="mt-3 text-body text-capitalize text-decoration-none">No Categories Listed</h6>
{% endfor %}
#views.py
def City_specific_page(request):
city = request.POST.get('city')
category = request.POST.get('category')
business= Business.objects.filter(city__City=city, type__category_type=category)
return render(request, 'community_app/type_detail_city.html',{'business':business,'category':category,'city':city})
#urls.py
path('City', views.City_specific_page, name='my_city_category'),
Each <form> in your template includes the following tag:
<a href="javascript: submitform()">
I suspect that your submitform function is submitting the first form on the page, rather than the one that was clicked.
You can quickly determine if this is the problem by adding a submit button inside your <form> tags. Make sure it's not inside the <a> tags, eg:
<form id="myform" action="{% url 'my_city_category' %}" method="POST">
{% csrf_token %}
<button type="submit">Test</button>
<a href="javascript: submitform()">
<!-- the rest of your form code -->
Click the button labelled 'Test' to see if the correct form data is submitted.

How to use Django Haystack whoosh search field in multiple application templates

I have implemented a working Django 1.6 haystack/whoosh search field following Mike Hibbert's tutorial:https://www.youtube.com/watch?v=B-n6_m66TmA. The implementation works in a twitter bootstrap search field in the navbar in the url 'search'. I'd like to use the implementation in several pages in my application but it doesn't work.
I've tried with implementing the search.html code in other pages with search bars but it changes the search url prefix from 'search/...' to the page url, e.g. to 'front/...' on the frontpage. I've also tried to include the search.html in other pages, both as the block content and with an include tag in the template but it hasn't worked.
# in app/templates/search/indexes/search.html
{% extends 'base_searches.html' %}
{% block content %}
<form method="get" action=".">
<table>
<tr><th><label for="id_q"></label></th><td><input type="text" id="id_q"
name="q" placeholder="Search..." class="form-control" /><button
class="btn btn-success" type="submit" value="Search"><spaclass="glyphicon
glyphicon-search"></span></button></td></tr>
<tr>
<td> </td>
{% if query %}
{% for result in page.object_list %}
<div class="alert alert-success" role="alert">
Hi, {{ user }}, here's the found database match for your search
<a href="{{ result.object.get_absolute_url }}">
{{result.object.title }}.</a></div>
{% empty %}
<div class="alert alert-info" role="alert">
<strong>Hi {{ user }}, there's no match found in the
database for your search !.</strong>
</div>
{% endfor %}
{% endif %}
<div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar">
<!--/.sidebar-offcanvas-->
<!--/row-->
<hr>
<td>
</td>
</tr>
</table>
</form>
</body>
</html>
{% endblock %}
# in models.py for each indexed model field
def get_absolute_url(self):
return '%s' % self.id
# in app/templates/base_searches.html
<form class="navbar-form navbar-right" id="search">{% csrf_token %}
<center><h> <td colspan="1" id="content">{% block content %}}
{% endblock %} </center></td></h>
<ul id="search-results">
</ul>
</form>
in urls.py
from haystack.query import SearchQuerySet
url(r'^search/',include('haystack.urls'),name='haystack_search'),
# in search_indexes.py
from haystack import indexes
from app.models import Article
class ArticleIndex(indexes.SearchIndex, indexes.Indexable):
text= indexes.CharField(document=True,use_template=True)
content = indexes.CharField(model_attr='description')
content_auto = indexes.EdgeNgramField(model_attr='title')
def get_model(self):
return Article
def index_queryset(self, using=None):
"""used when the entire index for model is updated """
return self.get_model().objects.all()
# in app/templates/search/indexes/appname/article_text.txt
{{ object.title }}
{{ object.content}}
How do I include the search.html in other pages, as I've included it in the navbar in base_searches.html, and maintain the prefix search/..searchresult for the get_absolut_url function for the search result object and not the url prefix for other pages that I'm trying to include it in, e.g. front/..searchresult ? when trying to implement it in the frontpage with url front/, or are there better ways to use the haystack whoosh search in search fields in multiple application pages ?
I have solved this problem by adding http://{{ request.get_host }}/search" to the search form action.
`<form method="get" action="http://{{ request.get_host }}/search"`
The action="." will reference to your current page and the request will be redirected to your current view. With adding the host URL to your action it will redirect your query to the search view no matter on which page you are.

Django form action attribute is not working propely

I am working on app in django 1.11, on search feature. I installed elasticsearch - here all things are working.
In base.html and under url 127.0.0.1:8000 - I have form to search and I would like to keep this form here. On another hand I have search app with view, url, template - under url 127.0.0.1:8000/search/ - search is working here.
To solve this problem - search on main page and redirect on site with results I was trying to use action attribute in django form.
form in base.html
<form action="{% url 'search:search' %}" method="post">
{% csrf_token %}
<div class="input-group">
<input type="text" class="form-control" id="q" {% if request.GET.q %}value="{{ request.GET.q }}"{% endif %} name="q" placeholder="Search">
<div class="input-group-append">
<button class="btn btn-outline-primary" type="button">GO</button>
</div>
</div>
</form>
view in search app
def search(request):
q = request.GET.get('q')
if q:
posts = PostDocument.search().query('match', title=q)
else:
posts = ''
return render(request, 'search/search.html', {'posts': posts})
template with results
{% extends 'base.html' %}
{% block content %}
{% for p in posts %}
{{ p.title }}
{% endfor %}
{% endblock content %}
{% block sidebar %}{% endblock sidebar %}
You here mix up GET and POST. If the method is method="post", then the data is passed in the request, and thus ends up in the request.POST query dictionary.
If on the other hand the method is method="get", then the data ends up in the querystring of the URL. In that case, you can indeed use request.GET.
Often (not always), search queries are done with querystrings, since then a person can copy the URL and send it to another person, and that person thus can see the search results.
You can thus change the form to:
<form action="{% url 'search:search' %}" method="get">
{% csrf_token %}
<div class="input-group">
<input type="text" class="form-control" id="q" {% if request.GET.q %}value="{{ request.GET.q }}"{% endif %} name="q" placeholder="Search">
<div class="input-group-append">
<button class="btn btn-outline-primary" type="button">GO</button>
</div>
</div>
</form>

Django: redirect user two pages back

I have a list of multiple objects from my database (named "plp's"), arranged in a table. Next to each "plp" element I have a button "Edit" to modify that particular entry.
Next, I redirect the user to a new url, where I pass the id of that "plp", and show the form to edit it, with a "save" button.
After pressing the "save", which is request.POST, I want to redirect the user back to the first url, with the list of all the "plp" objects in one list. That means to the site, where he first pressed "Edit".
Can I somehow save the url of where the "Edit" was clicked, and pass it to my views.py?
Thank you
listdns.html:
<td>
Uredi
</td>
urls.py:
rl(r'^(?P<plp_id>\d+)/uredi$', plp_list_uredi,name="plpuredi")
views.py:
def plp_list_uredi(request, plp_id=None):
moj_plp=PLPPostavka.objects.get(id=plp_id)
form=PLPPostavkaForm(request.POST or None,request=request,dns=moj_plp.dns, instance=moj_plp)
context ={
'plp':moj_plp,
'form':form,
}
if request.POST:
if form.is_valid():
plp = form.save()
return redirect(request.path)
return render(request, "plp_pos/uredi.html",context)
uredi.html
<form action="" method="POST">
{% csrf_token %}
<div class="box">
<div class="box-header">
<h4 class="box-title">
Urejanje PLP Postavke
</h4>
</div>
<div class="box-body">
{% for field in form %}
<div class="form-group">
<label for="{{ field.id_for_label }}" class="col-md-2 control-label detail">{{ field.label }}</label>
<div class="col-md-10">
{% if field|field_type == "datefield" %}
{% render_field field class+="form-control dateinput" %}
{% else %}
{% render_field field class+="form-control" %}
{% endif %}
</div>
</div>
{% endfor %}
</div>
<div class="box-footer">
<div class="box-tools pull-right">
<input type="submit" value="Shrani" class="btn btn-primary" />
</div>
</div>
Don't you only have 1 page to edit all the elements? Then you could perhaps hardcode the link e.g.
return HttpResponseRedirect(my_edit_url)
If this doesn't work and you need to go 2 pages back take a look at this post:
How to redirect to previous page in Django after POST request

How do I render form ChoiceField images next to choices without breaking the form?

I am trying to render the images of the choices next to their respective choice. Attempting to do so will not save the form as valid so I have become lost at what to do. I've tried both methods below and I have no idea why one works and the other doesn't, could I get some tips?
#Form:
class ServerGroupForm(forms.Form):
OPTIONS = (
("pic1", "https://i.imgur.com/tMahp6U.png"),
("pic2", "https://i.imgur.com/b76nwsj.gif"),
("pic3", "https://i.imgur.com/qzEcfyX.png Lover"),
("pic4", "https://i.imgur.com/kdc7UF7.png"),
("pic5", "https://i.imgur.com/ynWJ13W.gif"),
("pic6!", "https://i.imgur.com/goHFWsp.png"),
("pic7", "https://i.imgur.com/b76nwsj.gif"),
("pic8", "https://i.imgur.com/KPgKm79.png"),
("pic9", "https://i.imgur.com/7KtEV1i.png"),
("pic10", "https://i.imgur.com/7KtEV1i.png"),
("pic11", "https://i.imgur.com/FXfo773.png")
)
servergroups = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=OPTIONS)
#View:
def sendmessage(msg):
#Other code sends msg to user, not includes so this isn't long
def select_server_group(request):
form = ServerGroupForm(request.POST)
if form.is_valid():
servergroups = form.cleaned_data['servergroups']
sendmessage(msg=servergroups)
return redirect('/')
return render_to_response('webts3/selcectsgroup.html', {'form':form },
context_instance=RequestContext(request))
#HTML: Works but no icons
<section class="login">
<div class="titulo">Create a channel</div>
<form method="post" action="." enctype="multipart/form-data">{% csrf_token %}
<table border="0">
{{ form.as_table }}
</table>
<input type="submit" class="btn btn-block btn-danger" value="Submit" style="margin-top: 10px;">
</form>
</section>
#HTML: Icons but not working
<form method='post' action="." enctype="multipart/form-data">{% csrf_token %}>
<table>
{% for x,y in form.fields.servergroups.choices %}
<tr>
<td><input type="checkbox" name="{{ x }}" value="{{ x }}"><img src={{ y }}</img></td>
</tr>
{% endfor %}
</table>
<input type='submit' value='submit'>
</form>
The name attribute of the field should not be {{ x }}. It should be "servergroups".
Note you'd also need to have some logic that determines if the field is already selected, for when for example the form is being redisplayed after validation errors.

Categories

Resources