I have this html search form and I want to link it to my search view to make it work.
<form class="navbar-form navbar-left" role="search" >
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" action = "/search/">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Here is the views.
def searchResults(request, drname):
# drname = request.GET.get('drname')
doctors = Doctor.objects.filter(name__contains=drname)
clinic = Doctor.objects.filter(clinic__name__contains=drname)
d = getVariables(request)
d['doctors'] = doctors
d['doctors_by_clinic'] = doctors
return render_to_response('meddy1/doclistings.html',d)
urls.py
url(r'^search/(?P<drname>\w+)/$', views.searchResults, name='searchResults'),
Html. <form> must have action attribute, not <input>. Also, send search string as get parameter, don't include it in url (add name attribute to <input>):
<form class="navbar-form navbar-left" role="search" action="/search/">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" name="drname">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
urls.py. Drop this part (?P<drname>\w+)/:
url(r'^search/$', views.searchResults, name='searchResults'),
views.py. Get search string from GET parameter:
def searchResults(request):
drname = request.GET.get('drname')
doctors = Doctor.objects.filter(name__contains=drname)
clinic = Doctor.objects.filter(clinic__name__contains=drname)
d = getVariables(request)
d['doctors'] = doctors
d['doctors_by_clinic'] = doctors
return render_to_response('meddy1/doclistings.html',d)
action goes in the form element, not the input.
Related
I want to save a value in the database when the button is clicked without using a form.
I want to save the value in h2 to another model when the button is clicked.
What can i do?
TEMPLATE
<div class="widget-main">
<center><h2 name="urun" value="{{ urun.urun_adi }} ">{{ urun.urun_adi }}</h2></center>
</a>
<input type="submit" onclick="location.href='{% url 'sepete_ekle' %}'" value = "sepete ekle" class="btn btn-sm btn-default pull-right">
Sepete Ekle
</input>
{{urun.fiyat}} TL
</div>
VIEWS
def sepete_ekle(request):
if request.method == 'POST':
urun = request.POST["urun"]
status = 0
urunler = Siparis.objects.create(urun,status)
urunler.save()
messages.success(request, " Sepete Eklendi")
return redirect('/bayi/profil_duzenle')
else:
return HttpResponseRedirect("/")
MODEL
class Siparis(models.Model):
bayi = models.ForeignKey('auth.User', verbose_name='bayi', on_delete=models.CASCADE, related_name='bayi',limit_choices_to={'groups__name': "BayiGrubu"})
urun = models.ForeignKey(Urun, on_delete=models.CASCADE)
adet = models.IntegerField()
tarih = models.DateTimeField()
status = models.BooleanField()
class Meta:
verbose_name = 'Bayi Sipariş'
verbose_name_plural = 'Bayi Siparişleri'
Replace the html posted by you in problem statement with the below one.
<div class="widget-main">
<center>
<h2>{{ urun.urun_adi }}</h2>
</center>
<form method="POST" action="{% url 'sepete_ekle' %}">
<input type="hidden" value="{{ urun.urun_adi }}" name="urun" />
<input
type="submit"
value="sepete ekle"
class="btn btn-sm btn-default pull-right"
/>
</form>
{{urun.fiyat}} TL
</div>
to know more about form hidden fields, here is a simple explaination for reference check this out
Once try this, I hope it works.
Change view.py to this. Add an arguement to your function sepete_ekle.
def sepete_ekle(request,urun):
if request.method == 'POST':
status = 0
urunler = Siparis.objects.create(urun,status)
urunler.save()
messages.success(request, " Sepete Eklendi")
return redirect('/bayi/profil_duzenle')
else:
return HttpResponseRedirect("/")
And urls.py to this:
path('/path/to/function/<urun>',views.sepete_ekle,name='sepete')
And in your html file:
<div class="widget-main">
<center><h2 name="urun" value="{{ urun.urun_adi }} ">{{ urun.urun_adi }}</h2></center>
</a>
<input type="submit" onclick="location.href='{% url 'sepete_ekle' %}'" value = "sepete ekle" class="btn btn-sm btn-default pull-right">
Sepete Ekle
</input>
{{urun.fiyat}} TL
</div>
So, when you click the button the h2 value will be sent in the url and in the view it will be taken from the arguement.
This is my view.So I want to keep 2 different HTML forms in same view ,But I am unable to do so beacuse whenever I add 1 form , I get the error of other on being none.
def home(request):
name = None
if request.method == 'POST':
name = request.POST.get('name')
choices = request.POST.get('choices')
subtest = request.POST.get('subtest')
reference = request.POST.get('reference')
unit = request.POST.get('unit')
test = Test()
test.name = name
test.save()
subtest = Subtest()
subtest.test = Test.objects.get(name=choices)
subtest.name = subtest
subtest.unit = unit
subtest.reference_value = reference
subtest.save()
# print(name)
return redirect('home')
return render(request,'main.html',{})
I have got 2 different forms . I didn't use django forms because I wanted to try something new.
MY FIRST FORM
<form method="POST">
{% csrf_token %}
<div class="icon-holder">
<i data-modal-target="test-popup" class="icon-cross"></i>
</div>
<div class="input-group">
<input type="text" name="name" placeholder="Test name" />
</div>
<div class="button-group">
<button type="submit">Submit</button>
</div>
</form>
MY SECOND FORM
<form method="POST">
{% csrf_token %}
<div class="icon-holder">
<i data-modal-target="menu-test-popup" class="icon-cross"></i>
</div>
<div class="input-group">
<label for="test-select">Test Name:</label>
<select name="choices" id="test-select">
{% for test in test %}
<option value="{{test.name}}" name='choices'>{{test.name|title}}</option>
{% endfor %}
</select>
</div>
<div class="input-group">
<input type="text" name="subtest" placeholder="SubTest name" />
</div>
<div class="input-group">
<input type="text" name="reference" placeholder="Reference rate" />
</div>
<div class="input-group">
<input type="text" name="unit" placeholder="Unit" />
</div>
<div class="button-group">
<button type="submit">Submit</button>
</div>
</form>
first form
<form method="POST">
...
<input name="form_type" value="first-form" type="hidden">
</form>
second form
<form method="POST">
...
<input name="form_type" value="second-form" type="hidden">
</form>
view function
def view(request):
if method == "POST":
form_type = request.POST.get('form_type')
if form_type == "first-form":
# first form's process
elif form_type == "second-form":
#second form's process
You have two forms here, when you submit the second form, only the fields from the second form gets submitted.
so from this line
name = request.POST.get('name')
name will become None. But I believe your Test model does not take any None value for name field( the reason for you " IntegrityError at / NOT NULL constraint failed: lab_test.name ").
To overcome this, first check if there is any value for 'name' then proceed with creating the test instance
if name:
test = Test()
test.name = name
test.save()
Similarly check if the other fields are present for the second form before creating and saving the instance.
I'm new in django and i'm stuck now.
I'm trying to pass the url in form [action] attribute that would go to my edit function defined in [views.py] file and do it's job but whenever I try to pass the url [NoReverseMatch] is shown.
This is what i tried to do:
<div class="modal fade" id="editform" role="dialog">
<div class="modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<button type = "button" class = "close" data-dismiss="modal">×</button>
<h3 class="modal-title">
<b>Edit Information</b>
</h3>
</div>
<div class = "modal-body">
<form action="{% url 'studentapp:editrow' rowid=id %}" id="editform" method="POST">
{% csrf_token %}
<div class = "form-group">
<label for = "your_name">
Your name:
</label>
<input class = "form-control" id="new_name" type = "text" name="name" value="{{ student_detail.name }}" placeholder="Enter your name">
</div>
<div class="form-group">
<label for = "course_name">
Course:
</label>
<input id="new_course" class = 'form-control' type = "text" name="course" value="{{ student_detail.course }}" placeholder="Enter your course">
</div>
<div class = "form-group">
<label for = "rollno">
Roll No.:
</label>
<input id="new_rollno" type = "text" class = 'form-control' name="roll" value="{{ student_detail.roll }}" placeholder="Enter your roll number">
</div>
<div class = "form-group">
<label for ="addr">
Address:
</label>
<input id="new_address" type = "text" name="address" class = 'form-control' value="{{ student_detail.address }}" placeholder="Enter your address"/>
</div>
<input type = "submit" value="Update" id="update" class = "btn btn-success" style="font-size:18px;" />
</form>
</div>
</div>
</div>
</div>
In my urls.py I've used the following url:
url(r'^editrow/(?P<rowid>[0-9]+)/$', views.editrow, name='editrow'),
My [editrow] view looks something like this:
def editrow(request, rowid):
item = get_object_or_404(Studentapp, rowid=id)
print item
if request.method=="POST":
form = EntryForm(request.POST, instance=item)
if form.is_valid():
post=form.save(commit=False)
post.save()
return HttpResponseRedirect(reverse('studentapp:index'),rowid.id)
else:
form=EntryForm(instance=item)
return render(request, 'index.html',{'form':form})
else:
form=EntryForm(instance=item)
return render(request, 'index.html',{'form':form})
View that render's the template:
def index(request):
context = {}
latest_student = Studentapp.objects.order_by('pub_date')
context.update({
'latest_student': latest_student
})
response = {"status": False, "errors": []}
if request.is_ajax():
id = request.POST['id']
response = {}
response['status'] = False
student_detail = Studentapp.objects.filter(id=id).first()
context = {
"student_detail": student_detail
}
template = render_to_string("studentapp/_edit_student.html", context)
response['template'] = template
response['status'] = True
return HttpResponse(json.dumps(response), content_type="applicaton/json")
return render(request, "studentapp/index.html", context)
What i'm doing in crud is:
1) make an [edit] button in table through for loop.
2) when i click [edit] button a pre-populated form shows up(which i'm getting).
3) After i click the pre-populated form i want to edit that form and save it and updated data is reflected in my django db.
Thanks to #Alasdair, I looked in my code what he was trying to tell me and i got the answer.
The url that i was trying to pass through my action attribute was wrong. Here's what i did.
<form action="{% url 'studentapp:editrow' rowid=student_detail.id %}" id="editform" method="POST">
Through "student_detail" i'm able to get pre-populated form as i mentioned above. i used the same to get the id and pass it to my "editrow" view.
It's working for me now.
It seems like you never add id to your context in your view index. So the template does not have that variable available.
You need to add that id to your context.
Just like #Alasdair pointed out in the comments.
I'm using Python Pyramid with Jinja2 template. I want to save my form data into session and retrieve it in another HTML page. How should I change in order to pass the data? I only know how to store the data I key in Views.py into session like this request.session['postal'] = 01934 but this is not the data I key in Delivery.jinja2. And if I used print (session['postal']), this will only show in my command prompt but not HTML page. Can anyone help me out? I'm a beginner to this.
What to add in/ change in my Views.py?
my HTML: Delivery.jinja2
<form class="form-horizontal" method="POST">
<div class="form-group">
<label class="control-label col-md-2" for="postal">Postal Code:</label>
<input type="text" class="form-control" id="postal" placeholder="Enter Postal Code" name="postal" />
</div>
<div class="form-group">
<label class="control-label col-md-2" for="address">Detailed Address:</label>
<textarea class="form-control" rows="3" id="address" placeholder="Enter Address" name="address"></textarea>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="unit">Unit No #:</label>
<input type="text" class="form-control" id="unit" placeholder="Enter Unit No" name="unit" />
</div>
<button type="submit" class="btn btn-default" name="submit">Submit</button>
</form>
Views.py
#view_config(route_name='deliveryLink', renderer='templates/deliveryLink.jinja2')
def deliveryLink(request):
print("YAY for gift delivery via Link")
if 'submit_deliverylink' in request.POST:
print("request.POST: ", request.POST)
myform = request.POST
for m in myform:
print("key: ", m, " value: ", myform[m])
session = request.session
session['postal'] = ?
session['address'] = ?
session['unit'] = ?
data = "??"
data_array = data.split(",")
session['data'] = data_array
session['delivery'] = str(data_array)
print (session['delivery'])
return HTTPFound(location='http://localhost:5555/confirmation')
return {}
#view_config(route_name='confirmation', renderer='templates/confirmation.jinja2')
def confirmation(request):
print("YAY for confirmation")
for a in request.POST:
request.session[a] = request.POST[a]
return {}
and I want the data entered previously to show on this confirmation page: Confirmation.jinja2
<form class="form-horizontal" method="POST">
<div class="form-group">
<label class="control-label col-md-2" for="postal">Postal Code:</label>
<input type="text" class="form-control" id="postal" name="postal" />
</div>
<div class="form-group">
<label class="control-label col-md-2" for="address">Detailed Address:</label>
<textarea class="form-control" rows="3" id="address" name="address"></textarea>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="unit">Unit No #:</label>
<input type="text" class="form-control" id="unit" name="unit" />
</div>
</form>
I think, you can just pass POST from initial form to template of confirmation page, without session.
If anyway you need session, you can call it from your template
<input type="text" class="form-control" id="postal" name="postal" value="{{session['postal']}}" />
# after form submitted, it sends post request, just check if it exist
if request.POST:
print("request.POST: ", request.POST)
myform = request.POST
# you need iterate over keys for this case
for m in myform.keys():
print("key: ", m, " value: ", myform[m])
session = request.session
# you can access request.POST directly or use your variable myfrom
# use myform.get('postal','') to get value by key
session['postal'] = myform.get('postal','')
session['address'] = myform.get('postal','')
session['unit'] = myform.get('unit','')
data = "??"
data_array = data.split(",")
session['data'] = data_array
session['delivery'] = str(data_array)
print (session['delivery'])
return HTTPFound(location='http://localhost:5555/confirmation')
I'm currently stuck in trying to find a solution to my problem. So I have a URL which is like so:
https://www.domain.com/forum/topic/
In my template view, I have a form and an input which is responsible for searching for posts:
<form method="GET" action="">
<div class="input-group">
<input type="text" name="q" placeholder="Search..." value="{{ request.GET.q }}" class="form-control">
<span class="input-group-btn">
<input class="btn btn-secondary" type="submit" value="Search">
</span>
</div>
</form>
In my Views.py the search acts as follows:
def discussion(request, discussion):
topics_list = Topic.objects.all().filter(discussion__url=discussion)
discussion = Discussion.objects.get(url=discussion)
search_query = request.GET.get('q')
if search_query:
topics_list = topics_list.filter(
Q(title__icontains=search_query) |
Q(user__username__icontains=search_query)
)
paginator = Paginator(topics_list, 10)
page = request.GET.get('page')
try:
topics = paginator.page(page)
except PageNotAnInteger:
topics = paginator.page(1)
except EmptyPage:
topics = paginator.page(paginator.num_pages)
context = {'topics': topics, 'discussion': discussion,}
return render(request, 'forum/forum_show_posts.html', context)
Now when I run the search It works fine, It actually filters the objects based on my query, thus making the url appear as:
https://www.domain.com/forum/topic/?q=test
Now I want to work on a order by for my objects so I proceeded to modify the discussion view to be:
def discussion(request, discussion):
topics_list = Topic.objects.all().filter(discussion__url=discussion)
discussion = Discussion.objects.get(url=discussion)
search_query = request.GET.get('q')
sort_query = request.GET.get('sort')
if search_query:
topics_list = topics_list.filter(
Q(title__icontains=search_query) |
Q(user__username__icontains=search_query)
)
elif sort_query:
if sort_query == "newest":
topics_list = topics_list.order_by('-timestamp')
if sort_query == "oldest":
topics_list = topics_list.order_by('timestamp')
if sort_query == "name":
topics_list = topics_list.order_by('title')
# sort_query = sort_query.title()
paginator = Paginator(topics_list, 10)
page = request.GET.get('page')
try:
topics = paginator.page(page)
except PageNotAnInteger:
topics = paginator.page(1)
except EmptyPage:
topics = paginator.page(paginator.num_pages)
context = {'topics': topics, 'discussion': discussion, 'sort_value':sort_query,}
return render(request, 'forum/forum_show_posts.html', context)
and my template to have the corresponding links for each method of ordering:
<div class="dropdown-menu">
<a class="dropdown-item disabled" href="#">Sort...</a>
<form method="GET" action="">
<div class="input-group">
<button class="dropdown-item" type="submit" name="sort" value="newest">Newest</button>
<button class="dropdown-item" type="submit" name="sort" value="oldest">Oldest</button>
<button class="dropdown-item" type="submit" name="sort" value="views">Views</button>
<button class="dropdown-item" type="submit" name="sort" value="comments">Comments</button>
<button class="dropdown-item" type="submit" name="sort" value="replies">Replies</button>
<button class="dropdown-item" type="submit" name="sort" value="name">Name</button>
</div>
</form>
</div>
Now when I actually go ahead and choose to order by Newest or Oldest, it sorts them, making the url appear as:
https://www.domain.com/forum/topic/?sort=newest
My problem is that let's say I wanted to search for 'test' making the URL
https://www.domain.com/forum/topic/?q=test
but when I want to sort with the search already, that gets overwritten and instead it just shows all posts, with what I chose to sort it with. How do I get it to sort even with the search already there, and if there is no search still sort it.
From https://www.domain.com/forum/topic/?q=test to https://www.domain.com/forum/topic/?q=test&sort=newest so It shows the newest of the list of posts with the query 'test'.
You need to keep track of your GET params, update your view to be:
def discussion(request, discussion): # <<- view name and var name both are same which might cause issues
search_query = request.GET.get('q', '')
sort = request.GET.get('sort', '')
direction = request.GET.get('dir', 'asc')
if direction not in ['asc', 'desc']:
direction = 'asc'
topics_list = Topic.objects.all().filter(discussion__url=discussion)
discussion = Discussion.objects.get(url=discussion)
if search_query:
topics_list = topics_list.filter(
Q(title__icontains=search_query) |
Q(user__username__icontains=search_query)
)
if sort:
order_by = '{0}{1}'.format('-' if direction == 'desc' else '', sort)
topics_list = topics_list.order_by(order_by)
# rest of code
# pass search_query, sort and direction in context
context = {
'topics': topics,
'discussion': discussion,
'sort': sort,
'direction': direction,
'search_query': search_query,
}
return render(request, 'forum/forum_show_posts.html', context)
Now in template keep track of those params in both forms:
Search Form:
<form method="GET" action="">
<div class="input-group">
<input type="text" name="q" placeholder="Search..." value="{{ search_query }}" class="form-control">
<span class="input-group-btn">
<input class="btn btn-secondary" type="submit" value="Search">
</span>
</div>
<input type="hidden" name="sort" value="{{ sort }}" />
<input type="hidden" name="direction" value="{{ direction }}" />
</form>
Sort Form:
<div class="dropdown-menu">
<a class="dropdown-item disabled" href="#">Sort...</a>
<form method="GET" action="">
<div class="input-group">
<button class="dropdown-item" type="submit" name="sort" value="newest">Newest</button>
<button class="dropdown-item" type="submit" name="sort" value="oldest">Oldest</button>
<button class="dropdown-item" type="submit" name="sort" value="views">Views</button>
<button class="dropdown-item" type="submit" name="sort" value="comments">Comments</button>
<button class="dropdown-item" type="submit" name="sort" value="replies">Replies</button>
<button class="dropdown-item" type="submit" name="sort" value="name">Name</button>
</div>
<input type="hidden" name="search_query" value="{{ search_query }}" />
<input type="hidden" name="direction" value="{{ direction }}" />
</form>
</div>