SO I'm tryng to create a Django site using HTML forms.The form takes in vendor choice and amount, which is then needed to be passed into views. The employee table's balance needs to be updated, with the amount paid deducted from the balance of the current logged in user, and an entry needs to be added to the transaction table stating the details, with credit = 0, rest info taken from form. How can this be done?
Given below are my files:
html:
<form method="POST" action="/profiles/updatingBalance">
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" value="1" id="defaultUnchecked" name="defaultRadios">
<label class="custom-control-label" for="defaultUnchecked">Vendor 1</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" value="2" id="defaultUnchecked" name="defaultRadios">
<label class="custom-control-label" for="defaultUnchecked">Vendor 2</label>
</div>
<input type="" class="form-control" id="amount1" name="amt" aria-describedby="emailHelp" placeholder="Enter amount">
<br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Models.py:
from django.db import models
from django.contrib.auth.models import User
import django
import datetime
# Create your models here.
class vendor(models.Model):
id = models.CharField(max_length=20, on_delete=models.CASCADE, primary_key=True)
name = models.CharField(maxlength=30, on_delete=models.CASCADE)
class employee(models.Model):
name = models.OneToOneField(User, on_delete=models.CASCADE)
id = models.CharField(max_length=20, on_delete=models.CASCADE, primary_key=True)
balance = models.IntegerField(default=0)
class transaction(models.Model):
vendor_id = models.ForeignKey(vendor, on_delete=models.CASCADE)
emp_id = models.ForeignKey(employee, on_delete=models.CASCADE)
debit = models.IntegerField()
credit = models.IntegerField()
timestamp = models.DateField(_("Date"), default=datetime.date.today)
Here's the views.py I tried. I got till updating emplyee table's balance(not sure if it's correct):
def updatingBalance(request):
if request.method=="POST":
ven_id = request.POST["defaultRadios"]
amount = request.POST["amt"]
x = employee.objects.filter(id = request.User.id)
x.balance = x.balance - amount
p = transaction(vendor_id =ven_id.value, emp_id = request.User.id, debit=amount, credit=0)
p.save()
return render(request, 'profiles/userLogin.html', employee)
return HttpResponseRedirect(request.META.get('profiles/userLogin.html'))
I am confused as to how data can be taken from pure html forms( I'm a beginner), and how that info can be used to get my desired results. Any help would be greatly appreciated.
to get the data from form you should pass the view that will process the information in the action attribute of the form, then with request.POST dictionary you can extract the data that you want.
html:
<form method="POST" action="/Yourapp/theview/">
your html
</form>
views:
def theview(request):
amount=request.POST["amt"]
Related
Inside a form, I want to input time. For this I am using the HTML input type="time" . I tried to set a value, but it does not appear
Time value just appears empty
<input type="time" name="due_time" id="id_due_time" class="form-control form-control-lg" value="{{ todo.due_time }}">
This is how I tried to get it done.
When the time default value did not appear, I tried formatting it like this-
<input type="time" name="due_time" id="id_due_time" class="form-control form-control-lg" value="{{ todo.due_time|time:'h i A' }}">
But it still doesn't work...
I'm a newbie, and I'm not familiar with Javascript, so I would appreciate it if the answers were kept simple.
Views.py
#login_required
def view_todo(request, todo_pk):
todo = get_object_or_404(Todo, pk=todo_pk, user=request.user)
if request.method == 'GET':
form = TodoForm(instance=todo)
return render(request, 'todo/view_todo.html', {'todo': todo, 'form': form})
else:
try:
form = TodoForm(request.POST, instance=todo)
form.save()
return redirect('current_todos')
except ValueError:
return render(request, 'todo/create_todo.html',
{'form': TodoForm(), 'error': 'Error:Bad data passed in. Please try again'})
Models.py
class Todo(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(blank=True)
due_date = models.DateField(null=True, blank=True)
due_time = models.TimeField(null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
last_updated = models.DateTimeField(auto_now=True)
date_completed = models.DateTimeField(null=True, blank=True)
important = models.BooleanField(default=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
tags = models.CharField(max_length=40, blank=True)
def __str__(self):
return self.title
Forms.py
from django.forms import ModelForm
from todo.models import Todo
class TodoForm(ModelForm):
class Meta:
model = Todo
fields = ['title', 'description', 'important', 'due_time', 'due_date', 'tags']
Thank You
The default value of <input type='time'> element should be in h:i:s format.
So change
<input type="time" name="due_time" id="id_due_time" class="form-control form-control-lg" value="{{ todo.due_time|time:'h i A' }}">
to
<input type="time" name="due_time" id="id_due_time" class="form-control form-control-lg" value="{{ todo.due_time|time:'h:i:s' }}">
I am working on a Django project .In front-end I want to add user data through input tags but I do not know how to save data through input tags
My models.py file is::
class User(AbstractBaseUser):
full_name = models.CharField(max_length=255, blank=True, null=True)
sur_name = models.CharField(max_length=255, blank=True, null=True)
email = models.EmailField(max_length=255 ,unique=True)
choose_subject = models.CharField(choices=SUBJECT_CHOICES , max_length=100)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
time_stamp = models.DateTimeField(auto_now_add=True)
father_name = models.CharField(max_length=255)
father_sur_name = models.CharField(max_length=255)
mobile_phone_number = models.IntegerField(blank=True,null=True)
father_email = models.EmailField(max_length=255, unique=True)
fiscal_code = models.CharField(max_length=20)
address = models.CharField(max_length=200 )
A part of my register.html file is:
<div class="card-body">
<h2 class="title">Registration Form</h2>
<form method="POST">{% csrf_token %}
<div class="row row-space">
<div class="col-2">
<div class="input-group">
<label class="label">Full name</label>
<input class="input--style-4" type="text" name="first_name"{{form.full_name}}>
</div>
</div>
<div class="col-2">
<div class="input-group">
<label class="label">Sur name</label>
<input class="input--style-4" type="text" name="last_name"{{form.sur_name}}>
</div>
</div>
</div>
I just want the Django model field to be working in input tags
You must create in the views.py file a method in which the templates and the logic of it, an example can be the following
views.py
#csrf_exempt
def register(request):
if request.method == 'POST':
var1 = request.POST.get('var1')
var2 = request.POST.get('var2')
var3 = request.POST.get('var3')
#Save to the database here
return render_to_response(
'home.html',
{'message': 'Update Success', }
)
else:
#elif request.method == "GET":
obj = table.objects.all()
if obj:
ctx['data'] = obj
return render(request, template_name, ctx)
and in your template add a form tag
<form method="POST">
{ % csrf_token % }
<div class="row row-space">
<div class="col-2">
<div class="input-group">
<label class="label">Full name</label>
<input class="input--style-4" type="text" value={{data.full_name}}>
</div>
</div>
<div class="col-2">
<div class="input-group">
<label class="label">Sur name</label>
<input class="input--style-4" type="text" value={{data.sur_name}}>
</div>
</div>
</div>
<input type="submit" value="OK">
</form>
refer this tutorial
I made a django website where doctor and patient both can signup. Patient mark their problem and it will send to those doctor whom he/she want, like question asking on Quora. And I also want to save data in db
But my webpage when patient insert data it does not save in database.
Models.py
class patients(models.Model):
fever=models.BooleanField()
others=models.TextField()
Views.py
from django.shortcuts import render, redirect
from .models import patients
def patient(request):
if request.method == 'POST':
fever=request.POST['fever']
others=request.POST['others']
patient_details=patients(fever= fever,others = others)
patient_details.save()
return render(request, "patient")
else:
return render(request, "patient.html")
Patient.html
<form action="patient">
<label for="exampleFormControlTextarea1"><u>Mark Your Problems</u></label><br>
<!-- FEVER -->
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="inlineCheckbox1" value="option1">
<label class="form-check-label" name="fever" for="inlineCheckbox1">Fever </label>
</div>
<!--Others-->
<h6 style="text-align:left;"><u>Others</u></h5>
<div class="form-group">
<textarea class="form-control" name="others" id="exampleFormControlTextarea1" rows="1"></textarea>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit"> SUBMIT </button>
</h6>
</form>
How I store these data on database ?
try this line
patient_details=patients.objects.create(Fever= fever, others = others)
instead of :
patient_details=patients(Fever= fever, others = others)
I'm new in django. I'm trying to connect already made an html file to django backend without rebuilding whole file.
Already created forms and views in python but have no idea what to put into html file.
view class:
class signup(View):
template = loader.get_template('signup.html')
form_class = UserRegistrationForm
def get(self, request):
form = self.form_class(None)
return render(request, 'signup.html', {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
current_user = form.save(commit=False)
email = form.cleaned_data['email']
password = form.cleaned_data['password']
current_user.set_password(password)
current_user.save()
userToAuthenticate = authenticate(email=email, password=password)
if userToAuthenticate is not None:
if userToAuthenticate.is_active:
login(request, userToAuthenticate)
return redirect('siteViews:index')
return render(request, 'signup.html', {'form': form})
form code:
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['email', 'password']
and html code:
<div id="registersquare">
<div id="panel">
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<label for="email">Email adress:</label>
<input type="email" id="username" name="email}">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<label for="password">Repeat password:</label>
<input type="password" id="password" name="repeatedpassword">
<label class="control-label col-sm-2" for="password">{{ field.label_tag }}</label>
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox"><a style="color: #999999;" href="#">I Accept Website Terms And Conditions.</a></label>
<input type="submit" value="Sign up">
</div>
</form>
</div>
</div>
anyone can explain how to do it?
cheers
You hav already created a Form, which is not Django's form, so you dont actually have to write anything in forms.py, as the purpose of it is to create an form based on the model structure and perform validations according to the fields defined.
Now you have to fetch data from form and perform the validation and checks by yourself in views. So the post would be
def post(self, request):
email = request.POST.get('email') # get value in name="email" field
password = request.POST.get('password')
repeatedpassword = request.POST.get('repeatedpassword')
if password == repeatedpassword: # manual validation to check if both string are same
# Other Validations code here and
# Register or Login etc functions here
return render(request, 'signup.html', {'form': form})
You need to delete the labels and inputs from your html file and add this tag after the {% csrf_token %}, {{form.as_p}}, that's a start. You are also using an older version of Django, the way I can tell is because when you defined your ModelForm you wrote forms.ModelForm when it has been changed to just ModelForm, to upgrade write
pip install -U Django
You essentially created two forms, one with just html and one with Django only you did not apply your ModelForm to your html file instead you just made a html form instead of a html rendered Django ModelForm.
I am using Bootstrap/Tagsinput for adding tags in a Django input form.
Problem
The first field is where I want the tags added and the second field is a simple text field. I am able to add the tags in the first field and a normal text in the second field. But, when I submit the form the input values get removed and am returned to the original form. The django form.errors indicates that the second field is empty with a This field is required message even though I had entered a text! What am I missing?
form.errors
Is returning
<ul class="errorlist"><li>experiments<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
Here are the related files
tags_add.html
I am using a custom html rather than the django's forms.as_table. All required css and min.js have been added in the html file.
<form id="defaultForm" method="post" action="" class="form-horizontal">{% csrf_token %}
<div class="form-group">
<label class="col-lg-3 control-label">Tags:</label>
<div class="col-lg-5">
<input type="text" name="tags" id="aa" class="form-control" value="" data-role="tagsinput" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Experiments:</label>
<div class="col-lg-5">
<input type="text" name="tags" id="exp_id" class="form-control" value="" />
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-3">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
forms.py
class TagsForm(ModelForm):
tags = forms.CharField( widget=forms.TextInput(attrs={'size':'20', 'placeholder':'add tags'}), required=True )
experiments = forms.CharField( widget=forms.TextInput(attrs={'size':'20', 'placeholder':'expid'}), required=True )
def __init__(self, *args, **kwargs):
super(TagsForm, self).__init__(*args, **kwargs)
class Meta:
model = Tags
fields = '__all__'
views.py
def view_tags(request,formtype):
form_type = formtype
if request.method == "POST":
form = form_type(request.POST or None)#, extra=extra_additives)
if form.is_valid():
instances = form.save(commit=False)
temp_str= str(instances)
print temp_str
experiment_tags = temp_str
return HttpResponse(experiment_tags)
else:
print "from view_tags {0}".format(form.errors)
return HttpResponse(form.errors)
else:
form = TagsForm()
return render(request, 'tags_add.html', {'form': form})
models.py
class Tags(models.Model):
tags = models.CharField(max_length=1000)
experiments = models.CharField(max_length=1000)
def __str__(self):
return ':'.join([self.tags, self.experiments])
I got it working by adding the following to a scripts tag in the html file:
$("input[name='tags']").tagsinput({
confirmKeys:[13] //-- Only enter
});