Answer the question
In order to leave comments, you need to log in
Why is the ManyToManyField field not being written when processing the form?
I display the form, fields: Date (data), people selection field (people) and Status (status), accepting a post request, add a value to the school_class field equal to pk and save. Date, status and school_class are saved, but people are not, what's wrong?
models.py:
class SchoolClass(models.Model):
school_class = models.CharField(max_length=10, help_text = 'Класс')
def __str__(self):
return self.school_class
# Возвращает id 0_о
def get_absolute_url(self):
return reverse('class-detail', args=[str(self.id)])
class Meta:
ordering = ['school_class']
class People(models.Model):
first_name = models.CharField(max_length=100, help_text = 'Имя учащегося')
last_name = models.CharField(max_length=100, help_text = 'Фамилия учащегося')
school_class = models.ForeignKey(SchoolClass, help_text = 'Класс ученика', on_delete = models.SET_NULL, null=True)
def __str__(self):
return '{} {}'.format(self.first_name, self.last_name)
class State(models.Model):
date = models.DateField(help_text = 'Дата')
status = models.CharField(max_length=10, choices = (
('+', '+'),
('-', '-')
))
people = models.ManyToManyField(People,
help_text = 'Фамилия и имя учащегося',
related_name="peoples",
blank = 'true')
school_class = models.CharField(max_length=10)
def __str__(self):
return '{} {}'.format(self.date, self.people.__str__())
def get_absolute_url(self):
return reverse('date-detail', args=[str(self.id)])
class Meta:
ordering = ['date']
class StateForm(forms.ModelForm):
class Meta:
model = State
fields = ('date', 'people', 'status')
@login_required
def newwrite(request, pk):
if request.method == 'POST':
form = StateForm(request.POST)
if form.is_valid():
state = form.save(commit=False)
state.school_class = pk
state.save()
return redirect('writeindex')
else:
form = StateForm()
return render(
request,
'app/newwrite.html',
context = {'form':form})
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question