Обработка форм динамической длины и сбор данных в Django
У меня есть форма, в которой количество полей ввода постоянно меняется и зависит от параметра, который я передаю. Это означает, что я не могу перейти в forms.py и создать класс Form, потому что для этого нужно заранее определить входные параметры.
Вот как я определяю форму.
<!-- Table to Display the original sentence and take the input of the translation -->
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Original Sentence</th>
<th scope="col">Translation</th>
</tr>
</thead>
<form name="translated-text-form" class="form-control" action="" method="post">
{% csrf_token %}
<tbody>
{% for sentence in sentences %}
<tr>
<th scope="row">{{ forloop.counter }}</th>
<td>{{ sentence.original_sentence }}</td>
<td><input type="text" name="translated-{{sentence.id}}" value="{{ sentence.translated_sentence }}" /></td>
</tr>
{% endfor %}
<tr>
<td colspan="2">
<br>
<p style="text-align: center;">
<input class="btn btn-secondary" type="submit" value="Save Translations"/>
</p>
</td>
</tr>
</tbody>
</form>
</table>
Пользователь добавит некоторый текст в самый правый столбец, и я хочу сохранить этот текст с определенным sentence.id в моей модели Sentence. Вот как выглядит моя модель
class Sentence(models.Model):
""" Model which holds the details of a sentence. A sentence is a part of a Wikipedia article which is tokenized.
Fields:
project_id: The ID of the project to which the sentence belongs
original_sentence: The original sentence tokenized from from the Wikipedia article.
translated_sentence: The translated sentence in the target language.
"""
# Define the sentence model fields
project_id = models.ForeignKey(Project, on_delete=models.CASCADE)
original_sentence = models.CharField(max_length=5000)
translated_sentence = models.CharField(max_length=5000, default="No Translation Found")
Я знаю, как мне к этому подойти. В моем views.py я хочу запустить цикл for и собрать данные из формы, имя которой указано как translated-{{sentence.id}}. Однако я не могу сделать обработчик запроса POST, который мог бы напрямую собирать данные из формы и сохранять их в модели Sentence на основе id предложения. Мне нужна помощь в написании такого обработчика запроса в моих представлениях.
Я нашел исправление, которое вообще не использует forms.py. Вот как будет выглядеть обработчик почтового запроса.
# Handle the post request
if request.method == 'POST':
# Get the project details from the database
all_sentence_data = Sentence.objects.filter(project_id=pk)
sentence_ids = [sentence.id for sentence in all_sentence_data]
# Iterate through all the input fields in the form
for i in range(len(sentence_ids)):
# Get the translated text from the form
try:
translated_text = request.POST[f"translated-{str(sentence_ids[i])}"]
if translated_text:
# Update the Sentence object with the translated text
Sentence.objects.filter(id=sentence_ids[i]).update(translated_sentence=translated_text)
except:
continue
messages.success(request, "Your translations have been saved successfully!")
return redirect('/translation/' + str(pk)+'/')
else:
return redirect('/translation/' + str(pk)+'/')
