Answer the question
In order to leave comments, you need to log in
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)
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__'
<!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
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>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question