Django Validate Form As Per Database Entry ID - python

Hello Wonderful people,
I have made a form in Django which has some serial numbers stored in Django-admin database.
I am now creating another app and similar form, However I want is that the new Form should accept the serial number which is valid and checked as per the serial number got entered in the first form which is in app 1.
I am pasting a bit of my code for you to understand it more clearly with some screenshots.
<form method="POST" action="/reservation/home/">
{% csrf_token %}
<div class="form-group">
<label for="exampleFormControlInput1">Radio Serial Number</label>
<input type="text" class="form-control" id="exampleFormControlInput1" name= "sno"
placeholder="S/N123ABC123" required >
</div>
<button type="submit" class="btn btn-primary"> Submit </button>
</form>
views.py of new app.
def reserve(request):
if request.method == "POST":
sno = request.POST.get('sno')
date_req = request.POST.get('date_req')
reserve = Reserve( sno=sno, date_req=date_req )
reserve.save()
return render(request, 'home.html')
models.py of new app.
from django.db import models
# Create your models here.
class Reserve(models.Model):
sno = models.CharField(max_length=100)
date_req = models.DateField()
def __str__(self):
return self.sno
I want it to accept the serial number which got input by another form and validate it.
If the new serial number is not same as the database entry in previous form , It should display some error message that it is not found or not valid.
If it is valid it should accept that serial number and the entry should be done in new form.
I have provided the name and id as "sno"
I am not sure how to get any documentation or any video regarding this.
Any help would be highly appreciated.
In case you need more of information, please drop a comment or check my github repository : https://github.com/samatharkar/altiostar/tree/reserve-tool/inventory/reservation_app

Related

Multiple Error in view,edit a list of a model

i am trying to view and edit the my customer model-
i am doing is when you open the server for first time the list of customer opens as a link .
as sson as i press suppose customer 1 .
the form appears well pre filled as soon as i make changes and press save button it gives me error-
Page not found (404)
Request Method: POST
Request URL: http://127.0.0.1:8000/marketing/editcustomer/2250a9b1-5d25-4bce-b426-e3a4abb45abb/POST
I also have back button - I get the same error after pressing back button too!
Then if I go back to the customerlist(seecustomer) and I again click on the same or any other customer it gives me the following error-
Manager isn't accessible via customer instances
sometimes it also gives -
First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'customer'.
my models.py
class customer(models.Model):
customerid=models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
customername=models.CharField(max_length=1000)
my views.py
def editcustomer(request,customer_pk):
global customer
customer=get_object_or_404(customer,pk=customer_pk,user=request.user)
if request.method=='GET':
form=createcustomerform(instance=customer)
return render(request,'marketing/editcustomer.html',{'customer':customer,'form':form})
else:
try:
form=createcustomerform(request.POST,instance=customer)
form.save()
return redirect('seecustomer')
except ValueError:
return render(request,'marketing/editcustomer.html',{'customer':customer,'form':form,'error':'Incorrect entry'})
my html form code-
<form action="POST" method="POST">
{% csrf_token %}
<div id="customername"> <span><label for="customername">Company Name</label></span>
<input type="text" id="customername" name="customername" placeholder="Enter Company's Full name" value="{{ customer.customername}}"> </div>
<button class="btn btn-primary btn-md" type="submit">Save</button>
<br>
<input type="button" class="btn btn-primary btn-md" value="Go Back" onclick="history.back(-1)" />
</form>
The reason this happens is due to the fact that after the first time get_object_or_404 is called, customer is a customer object, and no longer the class.
You can import the model for example with an uppercase:
from app.models import customer as Customer
def editcustomer(request,customer_pk):
customer=get_object_or_404(Customer,pk=customer_pk,user=request.user)
if request.method=='GET':
form=createcustomerform(instance=customer)
return render(request,'marketing/editcustomer.html',{'customer':customer,'form':form})
else:
try:
form=createcustomerform(request.POST,instance=customer)
form.save()
return redirect('seecustomer')
except ValueError:
return render(request,'marketing/editcustomer.html',{'customer':customer,'form':form,'error':'Incorrect entry'})
So here we remove the global part, and use the alias Customer. That being said, I strongly advise to use the PEP-8 style guidelines and thus write the names of classes in PerlCase, not snake_case. In that case you can simply import it with:
from app.models import Customer
def editcustomer(request,customer_pk):
customer=get_object_or_404(Customer,pk=customer_pk,user=request.user)
if request.method=='GET':
form=createcustomerform(instance=customer)
return render(request,'marketing/editcustomer.html',{'customer':customer,'form':form})
else:
try:
form=createcustomerform(request.POST,instance=customer)
form.save()
return redirect('seecustomer')
except ValueError:
return render(request,'marketing/editcustomer.html',{'customer':customer,'form':form,'error':'Incorrect entry'})

i am unable to save content of a form in database via Django

hello everyone i am trying to save a form in my database
my models.py
class customer(models.Model):
customerid = models.CharField(default=str(uuid.uuid1()), max_length=500, primary_key=True)
customername=models.CharField(max_length=1000,)
my forms.py
from .models import customer
class createcustomerform(ModelForm):
class Meta:
model=customer
fields=['customername']
my views.py
def createcustomer(request):
if request.method=='GET':
return render (request,'marketing/createcustomer.html',{'form':createcustomerform()})
else:
try:
form=createcustomerform(request.POST)
newcreatecustomer=form.save(commit=False)
newcreatecustomer.user=request.user
newcreatecustomer.save()
return redirect('createcustomer')
except ValueError:
return render(request,'marketing/createcustomer.html',{'form':createcustomerform(),'error':'Check for Invalid Data. Try Again.'})
my html is
<form method="POST">
{% csrf_token %}
<div id="customernamename"> <span>Company Name</span>
<input type="text" id="customername" placeholder="Enter Company's Full name"> </div>
</form>
When i am clicking save button its redirecting me again to createcustomer but not saving data in my database. kindly help what is wrong or what am i missing ?
Its saving the customer by admin area not by html page.
Your mistake is here: newcreatecustomer.user=request.user
The variable newcreatecustomer does not have user field; that is why it is not working.

Displaying multiple flask variables from different forms at once in HTML template

I have 2 separate forms on a html template called queries.html, one for inputting a company name and one for inputting keywords as seen below.
<form method="POST">
<p>Enter Company Name:</p>
<p><input type="text" name="company_name"></p>
<p><input type="submit" value="submit"></p>
</form>
<p> Name: {{ name }} </p>
<form method="POST">
<p>Enter Keywords:</p>
<p><input type="text" name="keywords"></p>
<p><input type="submit" value="submit"></p>
</form>
<p> Keywords: {{ keywords }}</p>
I want to be able to display the form input in the paragraph tags seen below each form.
Below is the relevant flask code:
#app.route('/queries/', methods=['GET', 'POST'])
def queries():
if request.method == 'POST':
if request.form['company_name']:
name = request.form['company_name']
return render_template('queries.html', name=name)
elif request.form['keywords']:
keywords = request.form['keywords']
return render_template('queries.html', keywords=keywords)
return render_template('queries.html')
My problems are, firstly, the company name when entered does display fine where the {{ name }} element is as it should but when inputting a keyword I get a 'bad request' error. Secondly, I did previously have both inputs working but when I would use one form, it would wipe the displayed data from the other, e.g. when inputting a keyword after having already input and displayed a company name, the keyword would appear at the {{ keyword }} element as it should but the company name would disappear. After some research I may need to use AJAX to keep the all elements displayed but not sure if i'm looking in the right direction. It seems this should be a relatively simple issue to solve, please help! Thanks in advance to any responses.
In Place of :
request.form['company_name']
request.form['keywords']
Use this :
request.form.get("company_name")
request.form.get("keywords")
Flask throws error if there is no value in the form input. Using form.get the flask will try to get the value and will handle if there is no value.

Django Form request not saving data to db

I am using a django form in atemplate to save data entered to database.
In my view after the request is made, the response is redirected correctly but the data is not saved to db.
I might be missing something. but am unable to find it even after a lot of debugging.
here is what has been done so far:
views.py:
from .models import testmodel
def testview(request):
if request.method== 'POST':
form=MapForm(request.POST)
if form.is_valid():
test1=request.POST.get('t1')
print meaningid1
test2=request.POST.get('t2')
print meaningid2
pobj=testmodel(test1=test1,test2=test2)
pobj.save()
return HttpResponse('Successful')
after this the response message "Successful" is seen
from template:
<form action="/testview/" method="post"> {% csrf_token %}
{{form.as_p}}
<input type="text" name="t1" value='' id='t1'/> <br><br><br>
<input type="text" name="t2" value='' id='t2'/><br>
<input type="submit" value="Submit" />
</form>
from forms.py:
from .models import testmodel
class MapForm(forms.ModelForm):
class Meta:
model = testmodel
fields = ['test1','test2']
after the data is entered in form it is going to page /testview and showing message on page. but from backend data is not been saved to db.
Can some one suggest what could be done
Thanks
In python, indentation matters.
def testview(request):
if request.method== 'POST':
form=MapForm(request.POST)
if form.is_valid():
test1=request.POST.get('t1')
print meaningid1
test2=request.POST.get('t2')
print meaningid2
pobj=testmodel(test1=test1,test2=test2)
pobj.save()
return HttpResponse('Successful')
In the above code 'Successful' will be displayed regardless of whether the form is actually successful or not. You need to push your return statement four spaces to the right, and you also need to add an else clause which handles the situation where the form is not valid. Typically that is just to display the form again (with form errors which wil be displayed for you automatically is you use form.as_p or form.as_table)

django form multiple fields dynamically

So I want to create a member form with Education part that will contain 3 elements:
Foreign Key to Academic_Background (which has High School, BC degree, master degree, etc..),
Charfield - Name of school
Charfield - Field of studies
No problem doing one, or two... but how can I make several "Education" fields (by adding a button of "Add another" and using JS&Jquery to display the new Education to the user.
What should I put in my Model, and in my Form? and how will it be saved in the DB?
It seems like something that probably happened to someone before, yet I couldn't find a solution for that...
Please help !
Thanks
i did this without using django forms .. just using html forms to upload multiple as many as user wishes..
this is my template.html file which has normal form without any input file field initially
the js method adds a new input file field to the form when clicked on "add new item" href
<form action="{{request.path}}" method="post" enctype="multipart/form-data" id="upload_form">
{%csrf_token%}
<input type="text" name="name" id="name" value="{{request.POST.name}}" placeholder="Person Name"/>
<input type="text" name="categorie" id="categorie" value="{{request.POST.categorie}}" placeholder="Categorie"/>
<div class="file_inputs" id="file_inputs">
<!-- <-- field where im adding multiple files initially empty -->
</div>
<input type="submit" value="Upload">
</form>
<!-- link to add new file input box when clicked on it -->
<a href="#" onClick="addformelement()" >add new item</a>
<script type="text/javascript">
// method to add an file input box when clicked on add new item link
function addformelement(){
a = document.getElementById('file_inputs')
divx=document.createElement('div')
divx.class='file_inputs'
x=document.createElement('input');
x.type='file';
x.name='docfile';
divx.appendChild(x);
a.appendChild(divx) ;
}
</script>
and in views i did this
if request.method == 'POST':
name_instance = get_name_instance(request)
if(name_instance == -1):
return HttpResponse("Error - Check Server logs")
for f in request.FILES.getlist('docfile'):
# do your logic for each file f
# as f.name to get filename ...
all my fileinputs have the same id as docfile ...
so in my views i called getlist('docfile')
you can do the same with normal data like
request.POST.getlist('idname')

Categories

Resources