我想使用此edit_student.html页面编辑和更新学生信息。当我进入编辑页面时,所有存储的值都会出现,但复选框项目和日期字段除外 我如何在编辑时显示已选中的项目和已添加的日期
models.py
class Student(models.Model):
name = models.CharField(max_length=100)
courses = models.CharField(max_length=500)
address = models.CharField(max_length=200)
email = models.EmailField()
phone = models.CharField(max_length=15)
image = models.ImageField(upload_to='Students',blank=True)
joined_date = models.DateTimeField()
views.py
def editstudent(request,id):
student = Student.objects.get(id=id)
courses = Course.objects.all()
try:
for course in courses:
course.has_checked = student.filter(courses=course) # this didn't worked for me
except Exception:
pass
return render(request,'students/edit_student.html',{'student':student,'courses':courses})
def updatestudent(request,id):
student = Student.objects.get(id=id)
form = AddStudentForm(request.POST,instance=student)
if form.is_valid():
student = form.save(commit=False)
student.save()
messages.success(request,'Student with name {} updated'.format(student.name))
return redirect('students:view_student')
else:
messages.error(request,'Error in form.Try Again')
return render(request,'students/edit_student.html',{'student':student})
edit_student.html
<div class="form-group">
<h5>Joined Date <span class="text-danger">*
</span></h5>
#it doesnot display already added value <div class="controls">
<input type="date" name="joined_date"
value=" {{student.joined_date|date:'m-d-Y'}}"
data-validation-required-message="This field is required"
class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Courses <span class="text-danger">*</span></h5>
<div class="controls">
{% for course in courses %}
<input name ="courses" type="checkbox" id="course-
{{course.id}}"
value="{{course.title}}">#
it doesnot display already checked courses
<label for="course-{{course.id}}">{{course.title}}
</label>
{% endfor %}
</div>
</div
</div>
答案 0 :(得分:0)
浏览器使用YYYY-mm-dd
格式的<input type="date">
。
<input type="date" name="joined_date" value="{{ student.joined_date|date:'Y-m-d' }}">
要显示复选框,请在为每个课程计算值has_checked
之后,按如下所示呈现每个复选框:
<input name="courses" type="checkbox" id="course-{{ course.id }}"
value="{{ course.id }}" {% if course.has_checked %} checked {% endif %}>
更新
如果您在ManyToManyField
和Student
之间有Course
,则可以使用注释来计算has_checked
。
from django.db.models import Q, Count
courses = Course.objects.annotate(
has_checked=Count('students', filter=Q(students=student))
)