Reputation: 35
I have a basic django-rest API running for a program I wrote. The program retrieves data from a database and displays it on the browser. The database is queried using two input values 'a' and 'b'.
Ex:
a = raw_input('Enter A.')
b = raw_input('Enter B.')
response = HttpResponse()
for post in db.collection.find({'field1' : a, 'field2' : b})
response.write(post)
return response
Instead of the raw_input statements, how do I write a code that will enable the user to enter the values for 'a' and 'b' from the browser?
When I enter the URL, I should have a page to input 'a' and 'b'. Once I hit Submit, it should display the posts (done by return response ). There is no 'PUT' function, only 'GET' using the user inputs.
Thanks in advance.
Upvotes: 0
Views: 1484
Reputation: 12869
Ok, so you need a page with a form on it first of all;
<form action="{% url 'searchview' %}" method="GET">
<label>A:</label>
<input name="a">
<label>B:</label>
<input name="b">
<button type="submit">
Search
</button>
</form>
Then an URL to capture that;
url(r'^search/(?P<a>\w+)/(?P<b>\w+)/$', 'views.search_view', name="searchview")
Then a view to handle that URL;
def search_view(request, a, b):
myobj = MyModel.objects.get(field1=a, field2=b)
Or a class based view would be something like;
class SearchView(View):
model = MyModel
template_name = 'template.html'
def get(self, request, *args, **kwargs):
a = request.GET['a']
b = request.GET['b']
obj = self.model.get(field1=a, field2=b)
return render(request, self.template_name, {'obj': obj})
Upvotes: 2
Reputation: 578
If you're submitting the form using GET, then the values should be in request.GET
. So something like request.GET['a']
? The request
object should be available in your Django view.
Upvotes: 0