I cannot retrieve data from form to Django class. Cannot get data from object with using form field value - django-forms

This is the HTML file
<form action="{% url 'invDrugs:invDrugs-search' %}" method="GET" id="form1"></form>
<div class="col-md-6">
<input type="text" placeholder="Search" name="search" class="form-control ">
</div>
<div class="col-md-2">
<button type="submit" form="form1" value="Submit"><i class="fas fa-search"></i></button>
</div>
</form>
this is the url path
path('search/', InvDrugsSearchView.as_view(), name='invDrugs-search')
this is the class
class InvDrugsSearchView(ListView):
model = InvDrugs
template_name = "invDrugs/search.html"
def get_queryset(self): # new
query = self.request.GET.get('search')
object_list = InvDrugs.objects.filter(Q(code=query))
return object_list
As you can see, I am submitting the form then it should be go to this class InvDrugsSearchView(ListView) but nothing happend.
I just want to get this value and search it from the DB.

You are closing the form tag right there in the first line. This means that the text field and submit button are not part of the form.

Related

i cant add image to my new blog post in django

kindly help me, i am using class based views now am about to create new post using Createview i added all the fields including an image which stands for the thumbnail so if i go to http://127.0.0.1:8000/pages/blog/new/ i get a form and if i fill in the fields and submit i get return back to the form saying the image fields is required meanwhile i already inserted an image , this is the error in picture
and this is my code below
views.py
class BlogCreateView(LoginRequiredMixin, CreateView):
model = Blog
fields = ['title', 'categories', 'overview', 'thumbnail', 'summary']
blog_form.html
<div class="content-section text-center">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group ">
<legend class="border-bottom mb-4 h2">Blog Post</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Post</button>
</div>
</form>
</div>
You need to add "enctype="multipart/form-data" to your form, so:
<form method="post" enctype="multipart/form-data">
See detailed explanation is this elaborate answer:
What does enctype='multipart/form-data' mean?

Input value doesn't hold the value after clicking button

I'm trying to type invoice number as input type i.e. 123456789
After I click Print Record button, the value of invoice number disappears like this:
Aslo I have wrote
<div class="form-group row">
<label for="invoice_no" class="col-sm-2 col-form-label">Inovice Number</label>
<div class="col-sm-10">
<input type="text" class="form-control col-sm-4" name="InvNumber" id="InvNumber" value="{{request()->input('InvNumber')}}">
</div>
</div>
And the Print button looks like:
<div class="form-group row">
<div class="col-sm-12 dol-12" >
<button class="btn btn-secondary float-right" onclick="printDiv()">Print Record</button>
</div>
And printDiv() function is:
<script type="text/javascript" language="javascript">
function printDiv(divName) {
var printContents = document.getElementById('printableArea').innerHTML;
document.body.innerHTML = printContents;
window.print();
}
Clicking a submit button will submit the form it is in.
Presumably, your form's action is the current URL, so it reloads the page.
The new page doesn't have the data in the form fields that you had typed into the previous page.
If you don't want to submit the form, use the type attribute to change the <button> from its default of submit.
As per the documenation, if you don't specify type of button it assumes it as submit button that is why your form is being submitted by default.
Add type="button" in your button
<button type="button" class="btn btn-secondary float-right" onclick="printDiv()">Print Record</button>
submit: The button submits the form data to the server. This is the
default if the attribute is not specified for buttons associated with
a form, or if the attribute is an empty or invalid value.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button

How to validate template versioned form fields in django without using django forms?

I wrote a small authentication application where i used manual template rendering. I can fetch and update data from from forms but i just want to validate the fields. But i can't move forward as i didn't use any Django form models.Client side validation is going on but what about the Server side validation.
Using python v3 and Django v2
I didn't used forms model doesn't inherited from the forms.py . So how can i validate??
my tempalate file for signup.
`
<form action="{% url 'register' %}" method="post">
{% csrf_token %}
{% for message in messages %}
<div class="alert {% if message.tags %} alert-{{ message.tags }}{% endif %}">{{ message|safe }}</div>
{% endfor %}
<h3>Registration Form</h3>
<div class="form-group">
<input type="text" name="first_name" placeholder="First Name" class="form-control" required>
<input type="text" name="last_name" placeholder="Last Name" class="form-control" required>
</div>
<div class="form-wrapper">
<input type="text" name="email" placeholder="Email Address" class="form-control" required>
<i class="zmdi zmdi-email"></i>
</div>
<div class="form-wrapper">
<input type="text" name="phone" placeholder="Phone" class="form-control" required>
<i class="zmdi zmdi-phone"></i>
</div>
<div class="form-wrapper">
<input type="password" name="password1" placeholder="Password" class="form-control" required>
<i class="zmdi zmdi-lock"></i>
</div>
<div class="form-wrapper">
<input type="password" name="password2" placeholder="Confirm Password" class="form-control"
required>
<i class="zmdi zmdi-lock"></i>
</div>
<button>Register
<i class="zmdi zmdi-arrow-right"></i>
</button>
</form>
</div>
</div>
`
views.py
def register(request):
if request.method == "POST":
first_name = request.POST['first_name']
last_name = request.POST['last_name']
phone = request.POST['phone']
email = request.POST['email']
password1 = request.POST['password1']
password2 = request.POST['password2']
if password1 == password2:
if User.objects.filter(phone=phone).exists():
messages.info(request, 'Requested phone exists')
elif User.objects.filter(email=email).exists():
messages.info(request, 'Requested email exists')
return redirect('register')
else:
user = User.objects.create_complete_user(first_name=first_name, last_name=last_name, phone=phone,
email=email, password=password1)
user.save()
messages.info(request, 'successfully user object is created')
return redirect('login')
else:
messages.info(request, 'Passwords not matching')
return redirect('register')
else:
return render(request, 'signup.html')
The only situation I can think of for adding your forms separately from Django is when your front-end and back-end are split apart and they communicate though an API. If this is the case, you should use serializers for validation. More details here: https://www.django-rest-framework.org/api-guide/serializers/
If you have a special situation in Django and you still want to use your coded HTML form, you will also need to create a Django form that mirrors the form you made in HTML.
Lets say you have the following HTML input types:
<form>
<input type="email" name="my_email">
<input type="text" name="my_text">
<input type="file" name="my_file">
</form>
Your form in django must be identical
#forms
class Myform(forms.Form):
my_email = forms.EmailField()
my_text = forms.CharField()
my_file = forms.FileField()
# view
def myview(request):
myform = Myform(request.POST, request.FILES)
if myform.is_valid():
# Cleaned and validated data
my_email = myform.cleaned_data["my_email"]
my_text = myform.cleaned_data["my_text"]
my_file = myform.cleaned_data["my_file"]
# Do here whatever you need to do with
Never save data that has not been validated and cleaned.
# Never do this.
def myview(request):
my_email = request.POST["my_email"]
request.user.email = my_email
request.user.save()
Note: This is untested code and might not work as is. But it serves as an example of what you should do.
Short answer: use django forms.
Longest answer: use django forms.
Proper validation / sanitization of user inputs is not trivial (if you want to do it right at least) and doing it manually you will only end up rewriting most of the existing form validation code, without the man/years of design, implementation, debugging, fixed security issues (and there are quite a few) etc you'll get from using django forms.

CS- cart custom form and ajax response

Actually I am new in cs-cart and I am trying to show my result set into html/smarty block which contains the form code which I added from backend
Design->Layout but it only shows response in console ,I am pasting of some code here
Block code (added from backend Design->Layouts) :
<div class="quick-quote">
<h3>Quick Quote!</h3>
<form class="cm-ajax" action="index.php" method="post" id="quick_quote_form">
<div id="quick-quote">
<div class="clearfix">
<label style="width:73px;" >Width:</label>
</div>
<div class="input">
<input type="text" placeholder="enter width" name="d_width" id="d_width" class="required form-control" >
</div>
<div class="clearfix">
<label style="width:73px;" >Height:</label>
</div>
<input type="submit" class="get-quote-btn" value="Get Quote" name="dispatch[get_qoute.get_rates]" />
</div>
<div class="result"></div>
<!-- tag -->
<input type="hidden" name="result_ids" value="result" />
</form>
</div>
Controller code:
<?php
use Tygh\Registry;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($mode == 'get_rates') {
$height= $_POST["d_height"];
$width=$_POST["d_width"];
$val = $height+$width;
Registry::get('view');
Registry::get('ajax')->assign('get_rates', $val);
}
exit;
}
?>
Result set is coming correctly , Now I don't know how to show response in block div.
<div class="result"></div>
<!-- tag -->
<input type="hidden" name="result_ids" value="result" />
Thanks in advance.
Dont goto design ->layout because its common for all forms and pages.
Goto the website menu-> content then choose the form you want to change, there you can see layout tab, edit block done.
In form you set what block must refresh by ajax method
<input type="hidden" name="result_ids" value="result" />
Your problem in this line:
<div class="result"></div>
All refresh results must be in ID tag:
<div id="result"></div>

How to collect form data and convert them json format and send back to server in spring mvc

I have form and I want to grab the data inserted by users and then convert them json format.
So first here is my form—
<form id="patient_form" action="#" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="firstName"> First Name<em>*</em></label>
<div class="controls">
<input type="text" id="firstName" class="required" maxlength="100"
placeholder="First Name" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="middleNameInitial">
Middle Name Initial</label>
<div class="controls">
<input type="text" id="middleNameInitial"
placeholder="Middle Name Initial" class="input-small"
maxlength="1" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="lastName"> Last Name <em>*</em></label>
<div class="controls">
<input type="text" id="lastName" placeholder="Last Name"
class="required" maxlength="100" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="dateOfBirth"> Date Of
Birth</label>
<div class="controls">
<input type="text" id="dateOfBirth" class="required" />
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="button" class="btn btn-primary"
onclick="savePatientInfo()">Save Changes</button>
<button type="button" class="btn"
onclick="cancelPatientInfoForm()">Cancel</button>
</div>
</div>
</form>
And then I want to send back them to server. And for server side code, I’m using spring mvc and client side I’m using JQuery.
Now how can I do it? I need two things basically,
Ajax call (JavaScript function to which will basically do 3 things, one- grab the form data and convert them into json and then ajax call)
Sever side method to consume ajax call (Controller method as I’m
suing spring mvc.)
Any help is much appreciated.
First of all you need to perform ajax call from the JSP as below:
$.post("${pageContext.servletContext.contextPath}/ajaxTestData",
{
firstName:$("#firstName").val(),
middleNameInitial:$("#middleNameInitial").val(),
<other form data>
},
function(j)
{
<j is the string you will return from the controller function.>
});
Now in the controller you need to map the ajax request as below:
#RequestMapping(value="/ajaxTestData", method=RequestMethod.POST)
#ResponseBody
public String calculateTestData(#RequestParam("firstName") String firstName, #RequestParam("middleNameInitial") String middleNameInitial, HttpServletRequest request, HttpServletResponse response){
<perform the task here and return the String result.>
return "xyz";
}
I have not used the JSON input and result in this way but I think if you return the Pojo then it might converts the same in the json format automatically. Just check that.
Hope this helps you. Cheers.

Resources