IntegrityError at /accounts/regist_save/ happens - javascript

IntegrityError at /accounts/regist_save/
NOT NULL constraint failed: accounts_newuser.user_id
error happens .I wrote in
views.py
def regist(request):
regist_form = RegisterForm(request.POST or None)
profile_form = ProfileForm(request.POST or None)
context = {
'regist_form': regist_form,
'profile_form': profile_form,
}
return render(request, 'registration/regist.html', context)
#require_POST
def regist_save(request):
regist_form = RegisterForm(request.POST or None)
profile_form = ProfileForm(request.POST or None)
if request.method == "POST" and regist_form.is_valid() and profile_form.is_valid():
regist = regist_form.save(commit=False)
regist.is_staff = True
regist.save()
profile = profile_form.save(commit=False)
sex = request.POST.get("sex", "")
print(1111)
print(sex)
profile.save()
else:
print(regist_form.errors)
print(profile_form.errors)
return redirect('detail')
regist.html
<div class="form-group-lg">
<label for="id_username">Username</label>
{{ regist_form.username }}
</div>
<div class="form-group-lg">
<label for="id_email">Email</label>
{{ regist_form.email }}
</div>
<div class="form-group-lg">
<label for="id_password">Password</label>
{{ regist_form.password1 }}
</div>
<div class="form-group-lg">
<label for="id_password">Password2</label>
{{ regist_form.password2 }}
<p class="help-block">{{ regist_form.password2.help_text }}</p>
</div>
{% load static %}
<div class="form-group-lg">
<label for="birthday">Date</label>
<select id="year" class="form-control year" name="year">
<option value="">--</option>
</select>
Year
<select id="month" class="form-control month" name="month">
<option value="">--</option>
</select>
Month
<select id="day" class="form-control day" name="day">
<option value="">--</option>
</select>
Day
<br>
<br>
</div>
<div class="form-group-lg">
<label for="sex">SEX</label>
<select id="sex" class="form-control sex" name="sex">
<option value="">--</option>
<option value="male">male</option>
<option value="female">female</option>
</select>
</div>
<script src="{% static 'accounts/register.js' %}"></script>
<button type="submit" class="btn-lg regist">REGIST</button>
<input name="next" type="hidden" />
{% csrf_token %}
</form>
regist.js
$(() => {
for (let i = 1900; i < 2020; i++) {
$("#year").append(`<option value="${i}">${i}</option>`);
}
for (let i = 1; i < 12; i++) {
$("#month").append(`<option value="${i}">${i}</option>`);
}
for (let i = 1; i < 31; i++) {
$("#day").append(`<option value="${i}">${i}</option>`);
}
})
models.py
from django.db import models
from django.contrib.auth.models import User
class NewUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birthday = models.CharField(max_length=100,null=True, blank=True, default=None)
sex = models.CharField(max_length=100,null=True, blank=True, default=None)
in forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm
from .models import User
from .models import NewUser
class RegisterForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email','password1','password1',)
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['email'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.attrs['class'] = 'form-control'
class ProfileForm(forms.ModelForm):
class Meta:
model = NewUser
fields = (
"birthday", "sex"
)
I really cannot understand why this error happens because I did not write user_id in NewUser models.I think Integrity Error means columns cannot be found in Model.OneToOneField can be connected withUser and NewUser's model .I think this error means I should prepare user_id in New User model but if my thinking is right, I cannot understand why.How should I fix this?What should I write it?

This happens because in the NewUser model, the user field is a required field. In the ProfileForm the user field is not included. So when the ProfileForm tries to save the NewUser without user attached to it, it results in the above mentioned error.
What we have to do is to attach the user to the instance before actual save happens:
profile = profile_form.save(commit=False)
profile.user = registered_user # you can get the user from the registerform above
profile.save()

Related

Data not displaying from the flask sqlalchemy database

I want to display the data of a person that is inputted via a pop-up form. But for whatever reason, the data isn't showing up on the HTML page.
Here is the HTML code for the home page
{% block title %}Home{% endblock %}
{% block content %}
<!-- <script type="text/javascript" src="js/jquery.js"></script> -->
<!-- onclick="window.location.href='add-users'" -->
<head>
<link rel="stylesheet" href="{{ url_for('static',filename='add-users.css') }}" type="text/css"/>
<!-- <h4>Log out</h4> -->
<h1>
<div class="dropdown" style="position:absolute; top:80px; right:170px;">
<button class="btn btn-info dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{{ user.name }}
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenu2">
<a style="text-decoration: none;"href="/logout"><button class="dropdown-item" type="button">Log Out</button></a>
<!-- <button class="dropdown-item" type="button">Switch Users</button>
<button class="dropdown-item" type="button">Something else here</button> -->
</div>
</div></h1>
<h1><button style="position:absolute; top:80px; right:100px; text-decoration: none"title="Add people" class="button" data-modal="modalOne"><span style="font-size:36px;">⊕</span></button></h1>
<div id="modalOne" class="modal">
<div class="modal-content">
<div class="contact-form">
<a class="close">⊗</a>
<form method="POST" action="/">
<h2>Add person</h2>
<br>
<!-- 2 column grid layout with text inputs for the first and last names -->
<div class="row mb-4">
<div class="col">
<div class="form-outline">
<input type="text" name="first_name" id="first_name" class="form-control" placeholder="First name"/>
</div>
</div>
<div class="col">
<div class="form-outline">
<input type="text" name="last_name" id="last_name" class="form-control" placeholder="Last name"/>
</div>
</div>
</div>
<!-- Email input -->
<div class="form-outline">
<input type="email" name="person_email" id="person_email" placeholder="Email" class="form-control" />
</div>
<!-- Address input -->
<div class="form-outline">
<input type="address" name="address" placeholder="Address" class="form-control" />
</div>
<div class="form-outline">
<input type="company" name="company" placeholder="Company" class="form-control" />
</div>
<div class="form-outline">
<input type="city" name="city" placeholder="City" class="form-control" />
</div>
<div class="form-outline">
<input type="county" name="county" placeholder="County" class="form-control" />
</div>
<!-- Submit button -->
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</head>
<body>
<div id=container>
<ul class="list-group list-group-flush">
{% for item in user.person %}
{{ item.first_name }}
{% endfor %}
</ul>
</div>
</body>
<script type="text/javascript">
let modalBtns = [...document.querySelectorAll(".button")];
modalBtns.forEach(function (btn) {
btn.onclick = function () {
let modal = btn.getAttribute("data-modal");
document.getElementById(modal).style.display = "block";
};
});
let closeBtns = [...document.querySelectorAll(".close")];
closeBtns.forEach(function (btn) {
btn.onclick = function () {
let modal = btn.closest(".modal");
modal.style.display = "none";
};
});
window.onclick = function (event) {
if (event.target.className === "modal") {
event.target.style.display = "none";
}
};
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
{% endblock %}
Here is the code for models.py
from sqlalchemy import null
from . import __innit__ # importing from the package (website) the db
from flask_login import UserMixin
db = __innit__.db
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(20), unique=False, nullable=False)
last_name = db.Column(db.String(), unique=False, nullable=False)
# person_email = db.Column(db.String(), unique=False, nullable=False)
company = db.Column(db.String(), unique=False)
address = db.Column(db.String(), unique=False)
county = db.Column(db.String(), unique=False)
city = db.Column(db.String(), unique=False)
#image = db.Column(db.String(), unique=True, default="default.jpg")
user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), unique=True)
email = db.Column(db.String(), unique=True)
password = db.Column(db.String(150), nullable=False)
person = db.relationship("Person")
Here is the code for views.py
#views.route('/', methods=["GET", "POST"])
#login_required
def home(new_person):
if request.method == "POST":
first_name = request.form.get("first_name")
last_name = request.form.get("last_name")
person_email = request.form.get("person_email")
company = request.form.get("company")
address = request.form.get("address")
city = request.form.get("city")
county = request.form.get("county")
print(f"The first name is {first_name}")
if first_name == "":
flash("First name field empty", category="error")
elif last_name == "":
flash("Last name field empty", category="error")
elif person_email == "":
flash("Email field empty", category="error")
elif company == "":
flash("Company field empty", category="error")
elif address == "":
flash("Address field empty", category="error")
elif city == "":
flash("City field empty", category="error")
elif county == "":
flash("County field empty", category="error")
else:
new_person = Person(first_name=first_name, last_name=last_name, person_email=person_email, company=company, address=address, city=city, county=county, user_id=current_user.id)
db.session.add(new_person)
db.session.commit()
print("USER ADDED")
flash("New person added", category="success")
redirect(url_for("views.home"))
return render_template("second-home.html", user=current_user, new_person=new_person)
By the way the statement print(f"THe first name is {first_name}") isn't working, meaning the form isn't being accessed however when I hit the submit button, the terminal outputs a POST request
Here is the HTML page in which the data should be shown
It might be that you need to explicitly set the id value for each of the inputs in your modal. You have name specified, but I think id is a more stable option when collecting form data.
If you're running this locally in dev mode (via terminal/cmd line) I would absolutely suggest throwing a breakpoint() in before print(f"The first name is {first_name}") and look at what values request.form actually returns.

I want to add custom countdown timer in my project where admin/teacher set time for exam,that time becomes input for timer

i tried creating timer in python but its not being as i wanted so i guess javascript is only going
to help and im not very good in javascript do please help me to create a timer and page should close when timer runs out of time
'THIS IS : models.py'
from django.db import models
from student.models import Student
class Course(models.Model):
course_name = models.CharField(max_length=50)
question_number = models.PositiveIntegerField()
total_marks = models.PositiveIntegerField()
time_to_solve = models.IntegerField()
required_marks_to_pass = models.IntegerField()
def __str__(self):
return self.course_name
class Question(models.Model):
course=models.ForeignKey(Course,on_delete=models.CASCADE)
marks=models.PositiveIntegerField()
question=models.CharField(max_length=600)
option1=models.CharField(max_length=200)
option2=models.CharField(max_length=200)
option3=models.CharField(max_length=200)
option4=models.CharField(max_length=200)
cat=(('Option1','Option1'),('Option2','Option2'),('Option3','Option3'),('Option4','Option4'))
answer=models.CharField(max_length=200,choices=cat)
class Result(models.Model):
student = models.ForeignKey(Student,on_delete=models.CASCADE)
exam = models.ForeignKey(Course,on_delete=models.CASCADE)
marks = models.PositiveIntegerField()
date = models.DateTimeField(auto_now=True)
'THIS IS HTML TEMPLATE WHERE COUNTDOWN TIMER SHOULD APPEAR '
{% extends 'student/studentbase.html' %}
{% block content %}
{%load static%}
{% block scripts %}
<script src="{% static 'quiz.js' %}" defer></script>
{% endblock scripts %}
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
{% comment %} <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> {% endcomment %}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<div class="jumbotron my-4">
<form class="form" autocomplete="off" onsubmit="return saveAns()" action="/student/calculate-marks" method="POST">
{% csrf_token %}
<h2 style="text-align: left;">Course: {{course.course_name}}</h2>
<h2 style="text-align: right;">Countdown: </h2>
{% comment %} <h2 id="timer-box" style="text-align: right;">Time: {{5:00}} min</h2> {% endcomment %}
<h1 style="text-align: right;"><span id = "time">00:00</span></h1>
{% for q in questions%}
<h3 class="text-danger">{{ forloop.counter }}. {{q.question}}</h3><h4 style="text-align: right;">[{{q.marks}} Marks]</h4>
<input type="hidden" name="csrfmiddlewaretoken" value="C24rUotmdHawVQJL3KrqiWxvti8UffOFYUc8TRbZtLt36AVLdP3jbkzUVe3beRAa">
<div class="form-check mx-4">
<input class="form-check-input" type="radio" name="{{ forloop.counter }}" id="{{q.option1}}" value="Option1">
<label class="form-check-label" for="option1">
{{q.option1}}
</label>
</div>
<div class="form-check mx-4">
<input class="form-check-input" type="radio" name="{{ forloop.counter }}" id="{{q.option2}}" value="Option2">
<label class="form-check-label" for="option2">
{{q.option2}}
</label>
</div>
<div class="form-check mx-4">
<input class="form-check-input" type="radio" name="{{ forloop.counter }}" id="{{q.option3}}" value="Option3">
<label class="form-check-label" for="option3">
{{q.option3}}
</label>
</div>
<div class="form-check mx-4">
<input class="form-check-input" type="radio" name="{{ forloop.counter }}" id="{{q.option4}}" value="Option4">
<label class="form-check-label" for="option4">
{{q.option4}}
</label>
</div>
{% endfor %}
<input class="btn btn-success btn-lg" style="border-radius: 0%;" type="submit" value="Submit Answers">
</form>
</div>
<script>
function saveAns(){
var ele = document.getElementsByTagName('input');
for(i = 0; i < ele.length; i++) {
if(ele[i].type="radio") {
if(ele[i].checked){
setCookie(ele[i].name,ele[i].value,3)
}
}
}
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
</script>
<br><br><br><br><br><br>
{% endblock content %}
'THIS IS VIEWS.PY'
from django.shortcuts import render,redirect,reverse
from . import forms,models
from django.db.models import Sum
from django.contrib.auth.models import Group
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required,user_passes_test
from django.conf import settings
from datetime import date, timedelta
from django.db.models import Q
from django.core.mail import send_mail
from teacher import models as TMODEL
from student import models as SMODEL
from teacher import forms as TFORM
from student import forms as SFORM
from django.contrib.auth.models import User
def home_view(request):
if request.user.is_authenticated:
return HttpResponseRedirect('afterlogin')
return render(request,'exam/index.html')
def is_teacher(user):
return user.groups.filter(name='TEACHER').exists()
def is_student(user):
return user.groups.filter(name='STUDENT').exists()
def afterlogin_view(request):
if is_student(request.user):
return redirect('student/student-dashboard')
elif is_teacher(request.user):
accountapproval=TMODEL.Teacher.objects.all().filter(user_id=request.user.id,status=True)
if accountapproval:
return redirect('teacher/teacher-dashboard')
else:
return render(request,'teacher/teacher_wait_for_approval.html')
else:
return redirect('admin-dashboard')
def adminclick_view(request):
if request.user.is_authenticated:
return HttpResponseRedirect('afterlogin')
return HttpResponseRedirect('adminlogin')
#login_required(login_url='adminlogin')
def admin_dashboard_view(request):
dict={
'total_student':SMODEL.Student.objects.all().count(),
'total_teacher':TMODEL.Teacher.objects.all().filter(status=True).count(),
'total_course':models.Course.objects.all().count(),
'total_question':models.Question.objects.all().count(),
}
return render(request,'exam/admin_dashboard.html',context=dict)
#login_required(login_url='adminlogin')
def admin_teacher_view(request):
dict={
'total_teacher':TMODEL.Teacher.objects.all().filter(status=True).count(),
'pending_teacher':TMODEL.Teacher.objects.all().filter(status=False).count(),
'salary':TMODEL.Teacher.objects.all().filter(status=True).aggregate(Sum('salary'))['salary__sum'],
}
return render(request,'exam/admin_teacher.html',context=dict)
#login_required(login_url='adminlogin')
def admin_view_teacher_view(request):
teachers= TMODEL.Teacher.objects.all().filter(status=True)
return render(request,'exam/admin_view_teacher.html',{'teachers':teachers})
#login_required(login_url='adminlogin')
def update_teacher_view(request,pk):
teacher=TMODEL.Teacher.objects.get(id=pk)
user=TMODEL.User.objects.get(id=teacher.user_id)
userForm=TFORM.TeacherUserForm(instance=user)
teacherForm=TFORM.TeacherForm(request.FILES,instance=teacher)
mydict={'userForm':userForm,'teacherForm':teacherForm}
if request.method=='POST':
userForm=TFORM.TeacherUserForm(request.POST,instance=user)
teacherForm=TFORM.TeacherForm(request.POST,request.FILES,instance=teacher)
if userForm.is_valid() and teacherForm.is_valid():
user=userForm.save()
user.set_password(user.password)
user.save()
teacherForm.save()
return redirect('admin-view-teacher')
return render(request,'exam/update_teacher.html',context=mydict)
#login_required(login_url='adminlogin')
def delete_teacher_view(request,pk):
teacher=TMODEL.Teacher.objects.get(id=pk)
user=User.objects.get(id=teacher.user_id)
user.delete()
teacher.delete()
return HttpResponseRedirect('/admin-view-teacher')
#login_required(login_url='adminlogin')
def admin_view_pending_teacher_view(request):
teachers= TMODEL.Teacher.objects.all().filter(status=False)
return render(request,'exam/admin_view_pending_teacher.html',{'teachers':teachers})
#login_required(login_url='adminlogin')
def approve_teacher_view(request,pk):
teacherSalary=forms.TeacherSalaryForm()
if request.method=='POST':
teacherSalary=forms.TeacherSalaryForm(request.POST)
if teacherSalary.is_valid():
teacher=TMODEL.Teacher.objects.get(id=pk)
teacher.salary=teacherSalary.cleaned_data['salary']
teacher.status=True
teacher.save()
else:
print("form is invalid")
return HttpResponseRedirect('/admin-view-pending-teacher')
return render(request,'exam/salary_form.html',{'teacherSalary':teacherSalary})
#login_required(login_url='adminlogin')
def reject_teacher_view(request,pk):
teacher=TMODEL.Teacher.objects.get(id=pk)
user=User.objects.get(id=teacher.user_id)
user.delete()
teacher.delete()
return HttpResponseRedirect('/admin-view-pending-teacher')
#login_required(login_url='adminlogin')
def admin_view_teacher_salary_view(request):
teachers= TMODEL.Teacher.objects.all().filter(status=True)
return render(request,'exam/admin_view_teacher_salary.html',{'teachers':teachers})
#login_required(login_url='adminlogin')
def admin_student_view(request):
dict={
'total_student':SMODEL.Student.objects.all().count(),
}
return render(request,'exam/admin_student.html',context=dict)
#login_required(login_url='adminlogin')
def admin_view_student_view(request):
students= SMODEL.Student.objects.all()
return render(request,'exam/admin_view_student.html',{'students':students})
#login_required(login_url='adminlogin')
def update_student_view(request,pk):
student=SMODEL.Student.objects.get(id=pk)
user=SMODEL.User.objects.get(id=student.user_id)
userForm=SFORM.StudentUserForm(instance=user)
studentForm=SFORM.StudentForm(request.FILES,instance=student)
mydict={'userForm':userForm,'studentForm':studentForm}
if request.method=='POST':
userForm=SFORM.StudentUserForm(request.POST,instance=user)
studentForm=SFORM.StudentForm(request.POST,request.FILES,instance=student)
if userForm.is_valid() and studentForm.is_valid():
user=userForm.save()
user.set_password(user.password)
user.save()
studentForm.save()
return redirect('admin-view-student')
return render(request,'exam/update_student.html',context=mydict)
#login_required(login_url='adminlogin')
def delete_student_view(request,pk):
student=SMODEL.Student.objects.get(id=pk)
user=User.objects.get(id=student.user_id)
user.delete()
student.delete()
return HttpResponseRedirect('/admin-view-student')
#login_required(login_url='adminlogin')
def admin_course_view(request):
return render(request,'exam/admin_course.html')
#login_required(login_url='adminlogin')
def admin_add_course_view(request):
courseForm=forms.CourseForm()
if request.method=='POST':
courseForm=forms.CourseForm(request.POST)
if courseForm.is_valid():
courseForm.save()
else:
print("form is invalid")
return HttpResponseRedirect('/admin-view-course')
return render(request,'exam/admin_add_course.html',{'courseForm':courseForm})
#login_required(login_url='adminlogin')
def admin_view_course_view(request):
courses = models.Course.objects.all()
return render(request,'exam/admin_view_course.html',{'courses':courses})
#login_required(login_url='adminlogin')
def delete_course_view(request,pk):
course=models.Course.objects.get(id=pk)
course.delete()
return HttpResponseRedirect('/admin-view-course')
#login_required(login_url='adminlogin')
def admin_question_view(request):
return render(request,'exam/admin_question.html')
#login_required(login_url='adminlogin')
def admin_add_question_view(request):
questionForm=forms.QuestionForm()
if request.method=='POST':
questionForm=forms.QuestionForm(request.POST)
if questionForm.is_valid():
question=questionForm.save(commit=False)
course=models.Course.objects.get(id=request.POST.get('courseID'))
question.course=course
question.save()
else:
print("form is invalid")
return HttpResponseRedirect('/admin-view-question')
return render(request,'exam/admin_add_question.html',{'questionForm':questionForm})
#login_required(login_url='adminlogin')
def admin_view_question_view(request):
courses= models.Course.objects.all()
return render(request,'exam/admin_view_question.html',{'courses':courses})
#login_required(login_url='adminlogin')
def view_question_view(request,pk):
questions=models.Question.objects.all().filter(course_id=pk)
return render(request,'exam/view_question.html',{'questions':questions})
#login_required(login_url='adminlogin')
def delete_question_view(request,pk):
question=models.Question.objects.get(id=pk)
question.delete()
return HttpResponseRedirect('/admin-view-question')
#login_required(login_url='adminlogin')
def admin_view_student_marks_view(request):
students= SMODEL.Student.objects.all()
return render(request,'exam/admin_view_student_marks.html',{'students':students})
#login_required(login_url='adminlogin')
def admin_view_marks_view(request,pk):
courses = models.Course.objects.all()
response = render(request,'exam/admin_view_marks.html',{'courses':courses})
response.set_cookie('student_id',str(pk))
return response
#login_required(login_url='adminlogin')
def admin_check_marks_view(request,pk):
course = models.Course.objects.get(id=pk)
student_id = request.COOKIES.get('student_id')
student= SMODEL.Student.objects.get(id=student_id)
results= models.Result.objects.all().filter(exam=course).filter(student=student)
return render(request,'exam/admin_check_marks.html',{'results':results})
def aboutus_view(request):
return render(request,'exam/aboutus.html')
def contactus_view(request):
sub = forms.ContactusForm()
if request.method == 'POST':
sub = forms.ContactusForm(request.POST)
if sub.is_valid():
email = sub.cleaned_data['Email']
name=sub.cleaned_data['Name']
message = sub.cleaned_data['Message']
send_mail(str(name)+' || '+str(email),message,settings.EMAIL_HOST_USER, settings.EMAIL_RECEIVING_USER, fail_silently = False)
return render(request, 'exam/contactussuccess.html')
return render(request, 'exam/contactus.html', {'form':sub})

view function is not being executed

I was trying to make a basic banking system using Django, in which a user can transfer money to other user. But when I tried to transfer money nothing happens, probably because transfer function in views.py is not being executed.
Here are transaction.html file and transfer function from views.py :
transaction.html
{% extends 'bank/base.html' %}
{% block content %}
<div class="container">
<h2>Transfer Money</h2>
<form action="{% url 'transaction' %}" method="post">
{% csrf_token %}
<label for="s_acc">Select sender details</label>
<select name="s_acc" required>
<option value="select">Select</option>
{% for cust in customer %}
<option value="{{cust.account_number}}">{{cust.name}}: {{cust.account_number}} : {{cust.balance}}</option>
{% endfor %}
</select>
<br>
<label for="amt">Enter amount</label>
<input type="number" name="amt" required>
<br>
<label for="r_acc">Select receiver details</label>
<select name="r_acc" required>
<option value="select">Select</option>
{% for cust in customer %}
<option value="{{cust.account_number}}">{{cust.name}}: {{cust.account_number}} : {{cust.balance}}</option>
{% endfor %}
</select>
<br>
<button type="submit" name="button">TRANSFER</button>
</form>
</div>
{% endblock %}
transfer function from views.py:
def Transfer(request):
customer = Customer.objects.all();
if request.method=="POST":
s_acc = request.POST.get('s_acc')
amt = request.POST.get('amt')
r_acc = request.POST.get('r_acc')
print(s_acc)
print(amt)
print(r_acc)
amt = int(amt)
if((s_acc=='select')or(amt=='select')or(r_acc=='select')or(s_acc==r_acc)):
messages.warning(request,"Account not selected or both the accounts are same")
elif(amt<=0):
messages.warning(request,"Enter valid amount")
else:
for c in customer:
if(c.account_number == s_acc):
s_name = c.name;
if(amt>c.balance):
messages.warning(request,"Insufficient balance")
break
for x in customer:
if(x.account_number == r_acc):
r_name = x.name
r_bal = x.balance
break;
for c in customer:
if c.account_number == s_acc and r_acc!=s_acc and r_acc!= 'select' and amt<=c.balance and amt>0:
q1 = Transaction(sender_name = s_name, amount = amt, receiver_name = r_name )
q1.save()
acc_bal = c.balance - amt
q2 = Customer.objects.filter(account_number = s_acc).update(balance = acc_bal)
q2.save()
acc_bal = r_bal+amt
q3 = Customer.objects.filter(account_number = r_acc).update(balance = acc_bal)
q3.save()
messages.success(request,"Transfer Complete")
return redirect('tranfer_list')
return render(request,'bank/transaction.html',{'customer':customer})
urls.py
from django.urls import path
from bank import views
urlpatterns = [
path('',views.AboutView.as_view(),name = 'about' ),
path('about/', views.AboutView.as_view(),name = 'about'),
path('customers/', views.CustomerListView.as_view(),name = 'customer_list'),
path('transfer_list/', views.TransactionListView.as_view(), name = 'transfer_list'),
path('transaction/', views.Transfer, name = 'transaction'),
path('customers/new', views.CustomerCreateView, name = 'customer_new'),
]
Thanks in advance :)

Passing my select id to route controller and show to another blade file

I'm trying to pass the selected id to controller using a route. But nothing happen shown at another blade file. Here, is my code
my blade contain that script
$("#state").on("change", function() {
var id = $(this).val();
console.log(id)
var cuid = document.getElementById("cu").value;
console.log(cuid)
});
state select
<div class="col-md-12 form-group" id="stateBranch">
<label for="sm" class="control-label">{{ __('messages.state') }}</label>
<select name="state" id="state" class="input-sm form-control">
<option value="">{{ __('messages.select') }}</option>
#if(!empty(request()->session()->get('stateList')))
#foreach(request()->session()->get('stateList') as $state)
<option value="{{ $state->st_state_code }}">{{ $state->st_state_desc }}</option>
#endforeach
#endif
</select>
</div>
cu select
<div class="col-md-12 form-group" id="custbranchreport">
<label for="sm" class="control-label">{{ __('messages.module.customer') }}<span class="compulsory"> * </span></label>
<select name="cu" id="cu" class="input-sm form-control" onchange="">
<option value="">{{ __('messages.select') }}</option>
#if(!empty($custList))
#foreach($custList as $cu)
<option value="{{ $cu->cu_customer_ID }}">{{ $cu->cu_customer_Shortname }}-{{ $cu->cu_customer_Name }}</option>
#endforeach
#endif
</select>
<input id="hid" type="hidden" name="hid" value=""/>
</div>
open new window route via onclick
<a class="btn btn-sm btn-default pull-right" type="button" title="Search Branch" onclick="openNewWindow('{{ route('reporting.branchCheckBoxList', ['cu' ,'state']) }}')" ><i class="fa fa-hand-o-up"></i> Choose Branch</a>
routes/web.php
Route::get('reporting/branchCheckBoxList/{cuid}/{stid?}','GenReportController#branchCheckBoxList')->name('reporting.branchCheckBoxList');
Controller
public function branchCheckBoxList(Request $request) {
$cuid = $request->get('cuid');
$stid = $request->get('stid');
return view('report.BranchCheckBoxList', compact('cuid','stid'));
}
You cannot used request in your method arguments considering that you are using a get request in your route, to access those parameters change your controller to this.
public function branchCheckBoxList($cuid, $stid = '') {
$cuid = $cuid;
$stid = $stid;
return view('report.BranchCheckBoxList', compact('cuid','stid'));
}
$(document).on('change','#cu',function(){
{
var state = $('#state option:selected').val();
var cu = $('#cu option:selected').val();
var viewurl = '{{ route("admin.booking.view", [":state",":cu"]) }}';
viewurl = viewurl.replace(':state',state );
var finalurl = viewurl.replace(':cu',cu );
$('a.btn').attr('href',finalurl);
});
and in you route
Route::get('reporting/branchCheckBoxList/{cuid}/{stid?}','GenReportController#branchCheckBoxList')->name('reporting.branchCheckBoxList');
and final in your controller
public function branchCheckBoxList($cuid, $stid = '')
{
$cuid = $cuid;
$stid = $stid;
return view('report.BranchCheckBoxList', compact('cuid','stid'));
}

How can I put json's data to form?

I wanna put json's data to form.I wrote in index.html
{% load staticfiles %}
<html lang="ja">
<head>
<meta charset="utf-8">
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<main>
<form class="form-horizontal" action="/accounts/regist_save/" method="POST">
 

 
<label for="id_email">Email</label>

 {{ regist_form.email }} 
 
{% include 'registration/sex.html' %}
<button type="submit" class="regist">REGIST</button>
<input name="next" type="hidden"/>
{% csrf_token %}
</form>
</main>
</body>
</html>
in forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm
from .models import User
from .models import NewUser
class RegisterForm(UserCreationForm):
class Meta:
model = User
fields = ('email',)
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.fields['email'].widget.attrs['class'] = 'form-control'
class ProfileForm(forms.ModelForm):
class Meta:
model = NewUser
fields = (
"sex"
)
in models.py
#coding:utf-8
from django.db import models
from django.contrib.auth.models import User
class NewUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
sex = models.CharField(max_length=100,null=True, blank=True, default=None)
in sex.html
<form class="form-horizontal" method="post" action="#">
<div class="form-group-lg">
<label for="sex">SEX</label>
<select class="form-control sex" name="sex">
<option value="">--</option>
<option value="male">MAN</option>
<option value="female">FEMALE</option>
</select>
</div>
 
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function showSex() {
var num = document.forms[0].sex.selectedIndex;
var sex = document.forms[0].sex.options[num].value;
console.log(sex);
}
document.addEventListener("DOMContentLoaded", showSex);
for (var i = 0, e = document.querySelectorAll(".form-horizontal select"); i < e.length; i++) {
e[i].addEventListener("change", showSex);
}
</script>
Now REGIST button cannot be sent,so I cannot regist these data.Why does such thing happen?I wanna put var sex data to regist in form.How should I fix this?
how can i sent js data to python?is it impossible?I think I should convert javascript data to python one,but I cannot understand how to do it.

Categories