#python #django
Вопрос:
Поэтому я пытаюсь сохранить класс в своей модели, которая представляет собой поле «многие ко многим», и когда я пытаюсь сохранить его из своей пользовательской формы с помощью множественного выбора, он сохраняет только одно значение
Это мое views.py
@login_required()
def create_class(request):
tea_user = request.user.username
validate = teacher_validation(tea_user)
if validate:
if request.method == 'POST':
Link = request.POST.get('link')
Subject = request.POST.get('Subject')
Class = request.POST.get('Class')
teacher_user = Teacher.objects.get(User=request.user)
teacher = Teacher.objects.get(id=teacher_user.id)
created_class = Online_Class.objects.create( Link=Link, Subject=Subject,Created_by
=teacher )
created_class.Class.set([Class])
return redirect('home')
return render(request, 'online_class/Teacher/class-create.html')
else:
messages.warning(request, 'Sorry You Dont have Permission to access this page')
return redirect('logout')
И Мой models.py выглядит так
class Online_Class(models.Model):
Created_by = models.ForeignKey(Teacher, on_delete=models.DO_NOTHING)
Class = models.ManyToManyField(Classes)
Subject = models.CharField(max_length=100)
Link = models.CharField(max_length=200)
Joined_by = models.ManyToManyField(Student, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
choice = (('Yes','Yes'),('No', 'No'))
Class_Ended = models.CharField(choices=choice, default='No', max_length=10)
И мой шаблон выглядит так
{% extends 'dashboard/teacher/base.html' %}
{% block title %} Create Class {% endblock title %}
{% block class %} active {% endblock class %}
{% block body %}
<div class="pc-container">
<div class="pcoded-content">
<div class="row">
<form method="POST">
{% csrf_token %}
<div class="form-group">
<label >Zoom Link</label>
<input type="url" class="form-control" name="link" placeholder="URL"
required="">
</div>
<div class="form-group">
<label>Subject</label>
<select class="form-control" name="Subject" required="">
{% for subject in teacher.Subject.all %}
<option>{{subject}}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label >Select Class</label>
<select multiple class="form-control" name="Class" required="">
{% for class in teacher.Class.all %}
<option value="{{class.id}}">{{class}}</option>
{% endfor %}
</select>
<p class="help-text">Hold on ctrl to select multiple class in whindow and command
in mac</p>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
{% endblock %}
I don’t know what’s the problem but when I save the form, It only save one class , even! when 2 classes are selected