Answer the question
In order to leave comments, you need to log in
How to work with ManyToMany in Django?
Who can explain on the fingers, and not in the interpreter, how to work with ManyToMany in Django?
Provided
models.py
class Specialization(models.Model):
spec_name = models.CharField(
verbose_name="Специализация",
max_length=150,
null=False,
blank=False,
)
class Person(models.Model):
author = models.ForeignKey(
User,
default=1,
on_delete=models.PROTECT,
)
first_name = models.CharField(
verbose_name="Имя",
max_length=150,
null=False,
blank=False,
)
last_name = models.CharField(
verbose_name="Фамилия",
max_length=150,
null=False,
blank=False,
)
spec = models.ManyToManyField(
Specialization,
)
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = (
'first_name',
'last_name',
)
def new_person(request):
if request.method == "POST":
person_form = PersonForm(request.POST or None)
if person_form.is_valid():
instance = person_form.save(commit=False)
instance.author = request.user
instance.save()
messages.success(request, "Создана запись в базе данных!")
return HttpResponseRedirect('/person/new/')
else:
person_form = PersonForm()
context = {
'person_form': person_form
}
return render(request, 'form.html', context)
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