L
L
LXSTVAYNE2022-01-11 17:36:19
Django
LXSTVAYNE, 2022-01-11 17:36:19

How to link two forms in Django?

I want to create a form through which I could add a Lecture object, but I don't know how to correctly connect two models in one form. Here is the code I have:
models.py

from django.contrib.postgres.fields import ArrayField
from django.db import models


class Content(models.Model):
    text = models.TextField(blank=True)
    videos = ArrayField(
        models.FileField(),
        blank=True
    )
    photos = ArrayField(
        models.ImageField(),
        blank=True
    )
    audios = ArrayField(
        models.FileField(),
        blank=True
    )


class Lecture(models.Model):
    subject = models.CharField(max_length=50)
    topic = models.CharField(max_length=100)
    content = models.ForeignKey(Content, on_delete=models.CASCADE)
    lecturer = models.CharField(max_length=50)
    date = models.DateField()
    faculty = models.CharField(max_length=100)
    direction = models.CharField(max_length=100)

forms.py
from django import forms

from .models import Lecture, Content


class AddContentForm(forms.ModelForm):
    class Meta:
        model = Content
        fields = '__all__'


class AddLectureForm(forms.ModelForm):
    class Meta:
        model = Lecture
        fields = '__all__'


How to add the AddContentForm form in the AddLectureForm form so that everything is displayed correctly in such a template?
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="{% url 'add_lecture' %}" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Добавить</button>
</form>
</body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Nesterov, 2022-01-11
@lxstvayne

Add the second one just like the first one:

article_form = AddLectureForm()
        content_form = AddContentForm()

    context = {
        'article_form ': article_form,
        'content_form ': content_form 
    }
    return render(request, 'main/render.html', context)

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form_one.as_p }}
    {{ form_two.as_p }}
    <input type="submit" value="ok">
</form>

Concretely, this is purely an example of the output of forms . You need to process two forms in the same way as one, only after saving the first form, you need to get the id from it and pass it to the second.
PS:
Specifically, the section about the save() method
can help. In the comments, there are a few points regarding the current implementation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question