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.
Related
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})
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 :)
I am new to django and I'm trying to build a to do list
so what I click on "✓" button it turn the item to green from red using javascript
and now Iam trying to make the button "X" delete objects from the django database
so I stuck here
this is my code I am waiting for your help
my views
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from .forms import *
# Create your views here.
def index(request):
tasks = Task.objects.all()
form = TaskForm()
if request.method == "POST" :
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect("/")
context = {
'tasks' : tasks , 'form' : form
}
return render(request,"tasks/list.html", context)
def deletetask(request, pk):
if request.method == "POST" and "delete" in request.POST:
print(request.POST)
print("good work")
item = request.POST.get(id=pk)
Task.objects.delete(id=item)
return render(request,"tasks/list.html")
my forms.py
from django import forms
from django.forms import ModelForm
from .models import *
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = '__all__'
my models.py
from django.db import models
# Create your models here.
class Task(models.Model):
title = models.CharField(max_length=200)
complete = models.BooleanField(default=False)
creted = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
my template
<h3>Hello world from templates</h3>
<form action="/" method="POST"> {% csrf_token %}
{{form.title}}
<input type="submit" name="Ajout medoc">
</form>
{% for task in tasks %}
<div >
<form action="/" method="POST">
<p style="color: red" id="{{task.id}}">
<input type="button" name="cmd" value="✓" onclick="document.getElementById( '{{ task.id }}').style.color = 'green'">
<input type="button" name="delete" value="X" id="{{task.id}}">
{{ task }}
</p>
</form>
</div>
{% endfor %}
What i would do instead is this:
def deletetask(request, pk):
instance = Task.objects.delete(id=pk)
instance.delete()
return redirect('index')
and then in your template:
{% for task in tasks %}
<div >
<p style="color: red" id="{{task.id}}">
<input type="button" name="cmd" value="✓" onclick="document.getElementById( '{{ task.id }}').style.color = 'green'">
<a href="{% url 'delete_item' task.id %}">
<button>X</button>
</a>
{{ task }}
</p>
</div>
{% endfor %}
In your urls.py:
urlpatterns = [
path("delete_item/", views.delete_item, name="delete_item"),
]
The code in the template is calling a function from a "a" html tag instead of using a form.
In my project, the Profile model has Foreign Key relation with Education instance. Here are my models:
class Profile(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, blank=True)
full_name = models.CharField(max_length=30, null=True, blank=True)
education = models.ForeignKey(Education, on_delete=models.SET_NULL, null=True, blank=True, related_name="education")
class Education(models.Model):
degree = models.CharField(max_length=100, null=True, blank=True)
school = models.CharField(max_length=100, null=True, blank=True)
edu_start_date = models.DateField(null=True, blank=True)
edu_end_date = models.DateField(null=True, blank=True)
def __str__(self):
return str(self.degree)
Now, using the Django ListView, I am not being able to display the data of foreign key. My views:
class EducationView(CreateView):
form_class = EducationForm
pk_url_kwarg = 'pk'
template_name = "profile_settings.html"
class EducationList(ListView):
model = Profile
queryset = Profile.objects.all()
context_object_name = 'object'
pk_url_kwarg = 'pk'
template_name = "profile_settings.html"
Template
{% for obj in profile.education.all %}
<div class="col-lg-12">
<h2>{{ obj.degree }}</h2>
<br>
<div>
{{ obj.school }}
</div>
</div>
<br>
{% endfor %}
Education form saves data to the database but I couldn't fetch it using the template code.
Note: I'm using single template for CreateView and ListView.
In ListView you specified context_object_name as 'object'. So inside the template, the context is referred to an object.
So the code look like
{% for each_profile in object %}
{% for obj in each_profile.education.all %}
<div class="col-lg-12">
<h2>{{ obj.degree }}</h2>
<br>
<div>
{{ obj.school }}
</div>
</div>
<br>
{% endfor %}
{% endfor %}
You need to do it like this:
{% for obj in object %} <!-- as your context_object_name is `object` -->
<div class="col-lg-12">
<h2>{{ obj.education.degree }}</h2> <!-- accessed foreign key -->
<br>
<div>
{{ obj.education.school }} <!-- accessed foreign key -->
</div>
</div>
<br>
{% endfor %}
Update
If you are using this template in create view then update the View like this:
class EducationView(CreateView):
form_class = EducationForm
pk_url_kwarg = 'pk'
template_name = "profile_settings.html"
def get_context_data(self, **kwargs):
context = super(EducationView, self).get_context_data(**kwargs)
context['profiles'] = Profile.objects.all() # I don't want to mix up `object` here. so using profiles
return context
Now in ListView and template, we are going to update context object as well:
# view
class EducationList(ListView):
model = Profile
queryset = Profile.objects.all()
context_object_name = 'profiles'
template_name = "profile_settings.html"
# template
{% for obj in profiles %}
<div class="col-lg-12">
<h2>{{ obj.degree }}</h2>
<br>
<div>
{{ obj.school }}
</div>
</div>
<br>
{% endfor %}
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()