S
S
sazhyk2016-12-01 12:10:49
Django
sazhyk, 2016-12-01 12:10:49

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,
    )

forms.py
class PersonForm(forms.ModelForm):

    class Meta:
        model = Person
        fields = (
            'first_name',
            'last_name',
        )

views.py
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)

My mosk refuses to understand the interpreter.
UPD:
All 3 tables are created in the database. The table of specializations is filled with three records. The page displays a form with the fields: First Name, Last Name, Specializations. Fill it out, hit submit. But the relation in the 'person_specialization' table is not stored in the database. What am I doing wrong? I probably don't keep that same attitude. But how to save it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question