Custom url based off single html input without JS - python

So I have probably the simplest task you could ever wish for with an html form that I cannot solve.
I want to input a brand name into a search bar, click submit and it redirect to the url/brand/[input]
I already have a working view for the urls setup in django. How would I structure the form to actually create my desired url?
<form method="GET" action="">
<input type="text" name="brand" id="brand" placeholder="Search..." aria-label="Search">
<button type="submit">Search</button>
</form>
views.py
class GetByBrand(ListView):
def get(self, request, brand):
urls.py
urlpatterns = [
path('', GetListView.as_view(), name='home'),
path('brands/<str:brand>/', GetByBrand.as_view())
]

<form method="GET" action="brands/">
<input type="text" name="brand" id="brand" placeholder="Search..." aria-label="Search">
<button type="submit">Search</button>
in URLs(import views by from. import views)
urlpatterns = [
path('brands/', views.GetByBrand),
]
in Views
from django.http import HttpResponse
def GetByBrand(request):
s = request.GET['brand']
return HttpResponse(s)

OR use AJAX in Javascript in your HTML file
$('#brand').on('submit',function(e){
var brand = $('input[name=brands]')
$.get("brands/"+brand, function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
})

So I basically solved this by using the code I had previously tried which is identical to what Wagas Develper recommended. What I had not done though was add this last line to the urls.py in the main project folder. (and I'm still not sure why this solved it but found the solution from throwing crap at the wall)
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('shoes.urls')),
path('brands/', include('shoes.urls'))
For anyone curious about how the class based view is structured now.
class GetByBrand(ListView):
def get(self, request, brand):
get_results = request.GET.get('q')
The urls.py in the same directory as views.py (within app dir not main project dir)
urlpatterns = [
path('', GetListView.as_view(), name='home'),
path('brands/<str:brand>/', GetByBrand.as_view()),
path('brand_results/', GetByBrand.as_view(), name='b')
]
HTML Form
<form method="GET" class="form-inline my-2 my-lg-0" action="{% url 'b' %}">
<input class="form-control mr-sm-2 search-btn" type="text" name="q" value="{{request.GET.q}}" placeholder="Search..." aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>

Related

Django from Submit button doesn't do anything

I'm new to Django, and I'm trying to submit a form to process the data in a view function, but I can't find why when I press the Send button it doesn't do anything. i read many other questions but were syntax related problems, which I believe is not my case.
Here's my form. It is in the new.html template:
<from action="{% url 'notes:create' %}" method="post">
{% csrf_token %}
<input type='text' name='note_name' id='note_name' placeholder='Title...'>
<input type='date' name='note_date' id='note_date'>
<input type="submit" value="Send">
</form>
Here it is urls.py:
app_name = 'notes'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('new/', views.new_note, name='new'),
path('output/', views.create_note, name='create')
]
And here the views.py file. Currently the create_note view only redirects to the index. I'm going to process the entered data once the form works correctly.
class IndexView(generic.ListView):
template_name = 'notes/index.html'
context_object_name = 'all_notes'
def get_queryset(self):
return Note.objects.all()
def new_note(request):
return render(request, 'notes/new.html')
def create_note(request):
return HttpResponseRedirect(reverse('notes:index'))

requestsession not working in Django to pass html form variable to another function

I am trying to use request.session to pass a html form variable into another function in Django, I am currenlty having trouble because the result from the session is resulting in None. Would appreciate help fixing it or another suggestion to pass the html form variable from to another function as a string.
Here is my views.py file
def home(request):
input_email = request.POST.get('emailvalue')
request.session["input_email"] = input_email
return render(request, 'file1.html')
def pre_que_ip(request):
actual_email = request.session["input_email"]
print(actual_email)
urls.py
path('admin/', admin.site.urls),
path('', views.home, name = 'login'),
path('home/', views.home, name = 'home'),
path('add_ipaddress/', views.pre_que_ip, name = 'pre_que_ip')
file1.html
<form action="/add_ipaddress/" method="post">
{% csrf_token %}
<input type="text" name="emailvalue" required><br><br>
<input type="submit" value="Submit"><br><br>
</form>

Email from contact form error: Method Not Allowed (POST) 405

I'm creating a Contact page on my portfolio site which when the user fills out and submits will automatically send it as an email to my personal email account. But when I hit Submit I get "Method Not Allowed (POST):/contact/" in my terminal, "HTTP ERROR 405" in my browser and no email in my account.
My HTML:
<form action="" method="POST">
{% csrf_token %}
<div class="row form-group">
<div class="col">
<input name="f-name" type="text" class="form-control" placeholder="First name" required>
</div>
<div class="col">
<input name="s-name" type="text" class="form-control" placeholder="Last name" required>
</div>
</div>
<div class="form-group">
<input name="email" type="email" class="form-control" id="email-input" aria-describedby="emailHelp" placeholder="name#mail.com" required>
<small id="emailHelp" class="form-text text-muted">I Wont Share Your Email!</small>
</div>
<div class="form-group text-center">
<textarea name="e-message" class="form-control" id="exampleFormControlTextarea1" rows="3" placeholder="your message..." required></textarea>
</div>
<button type="submit" class="btn btn-primary">Send</button>
</form>
My views.py:
class ContactView(TemplateView):
template_name = 'contact.html'
def send_message(self, request):
if request.method == 'POST':
message = request.POST['f-name', 's-name', 'email', 'e-message']
send_mail('Contact Form', message,['email#gmail.com'],
fail_silently=False)
return render(request, 'thanks.html')
My project urls.py
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('projects/', views.ProjectView.as_view(), name='projects'),
path('blog/', views.BlogView.as_view(), name='blog'),
path('contact/', views.ContactView.as_view(), name='contact'),
path('thanks/', views.ThanksView.as_view(), name='thanks'),
My application urls.py
from django.conf.urls import url
from blog import views
app_name = 'blog'
urlpatterns = [
url(r'^$', views.AboutView.as_view(), name='about'),
url(r'^projects/$', views.ProjectView.as_view(), name='projects'),
url(r'^blog/$', views.BlogView.as_view(), name='blog'),
url(r'^contact/$', views.ContactView.as_view(), name='contact'),
url(r'^thanks/$', views.ThanksView.as_view(), name='thanks'),
Iv been searching for similar answers for a few hours and anything similar hasnt helped so far Maybe I should re build my form in Django forms? I dont want to risk going too far changing too much and breaking my site!
Django does not support post method on template view implicitly. You have to define post method yourself in template view like this
class ContactView(TemplateView):
template_name = 'contact.html'
def post(self, request, *args, **kwargs):
message = request.POST['e-message']
send_mail('Contact Form', message,['email#gmail.com'], fail_silently=False)
return render(request, 'thanks.html')
The rest will be handled automatically

How does Django urls are matched?

I have a page with a form in it. Its url is
url('tasks/searchBook', views.searchBook, name='searchBook'),
when I click the submit button of form, it should go to this url
url('tasks/searchBookResult/', views.searchBookResult, name='searchBookResult'),
Url is changing in address bar but next html file is not rendering.
However if I interchange the place of urls in urls.py file i.e. take the second url on top and first url at bottom then it works fine.
What is happening here?
urls.py file :
urlpatterns = [
url(r'^$', views.index, name='index'),
url('tasks/searchBook/', views.searchBook, name='searchBook'),
url('tasks/searchBookResult/', views.searchBookResult, name='searchBookResult'),
]
form code in template file :
<form action="{% url 'lms:searchBookResult' %}" method="post">
{% csrf_token %}
<div class="inner centerAlign">
<input type="text" id="bookId" name="bookId" placeholder="Book ID" class="inputField"></input>
</div>
<div class="inner centerAlign">
<label>OR</label>
</div>
<div class="inner centerAlign">
<input type="text" id="bookTitle" name="bookTitle" placeholder="Book Title" class="inputField"></input>
</div>
<div class=" inner centerAlign">
<input type="submit" value="Search" class="button button-primary" name="searchBook"></input>
</div>
</form>
views.py :
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request, 'lms/loginPage.html')
def searchBook(request):
return render(request,'lms/tasks/searchBook.html')
def searchBookResult(request):
return render(request,'lms/tasks/searchBookResult.html')
Url's are matched as regexes in the order they are shown in the urls.py.
Since searchBook matches before searchBookResult, the first page is returned.
Simply reorder these so searchBookResult url is before the other.
url('tasks/searchBookResult/', views.searchBookResult, name='searchBookResult'),
url('tasks/searchBook/', views.searchBook, name='searchBook'),
Alternatively, you can include a $ at the end of your url which indicates the end of a line
url('tasks/searchBook/$', views.searchBook, name='searchBook'),

how to use ajax to populate Google search result in container on Django

I'm looking to make something like https://www.wolframalpha.com/ except with just vanilla Google. I'd like to have the Google results populate and pop out from the container.
My index will just have something like this:
<form action="search" method="get">
<label for="query">Your Query: </label>
<input id="myapp" type="text" name="myapp" value="Enter your query here">
<input type="submit" value="search">
</form>
</div> <!-- /container -->
</body>
</html>
urls.py:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
#url(r'^admin/', admin.site.urls),
url(r'^$', include('myapp.urls')),
(r'^search/$', views.search),
]
views.py:
def search(query):
#perform Google search and return the results
return 1
I have a generic setup for non-ajax search as shown above. How would I incorporate ajax here?

Categories