Форма Django с повторяющимися полями
Мне нужна форма django с некоторыми полями уникальными (id_станции и название станции) и полями: sensor_unity, id_sensor и sensor_name повторяющимися. При загрузке формы есть эти поля и рядом с полями sensor_unity, id_sensor и sensor name есть ссылка на добавление еще одной строки с теми же полями. Я пробовал с помощью этого руководства:
но мой код не работает, потому что я получаю ошибку:
ValueError: The view station.views.new_station didn't return an HttpResponse object. It
returned None instead.
[20/Sep/2021 18:00:16] "GET /station/new_station/ HTTP/1.1" 500 69039
Вот мой код:
models.py
from django.db import models
nr_unities = [(x, x) for x in range(1, 10)]
class Station(models.Model):
id_station = models.IntegerField(blank=False)
station_name = models.CharField(max_length=30, blank=False)
units_number = models.IntegerField(choices = nr_unities, blank=False)
nr_sensor_unity = models.IntegerField(blank=False)
id_sensor = models.IntegerField(blank=False)
sensor_name = models.CharField(max_length=50, blank=False)
def __str__(self):
return self.name
forms.py
from django import forms
from .models import Station
nr_unities = [(x, x) for x in range(1, 10)]
class StationForm(forms.ModelForm):
class Meta:
model=Station
fields = ['id_station'] #, 'station_name', 'units_number', 'nr_sensor_unity', 'id_sensor', 'sensor_name']
widgets = {
'id_station': forms.IntegerField(),
'station_name': forms.CharField(),
'units_number': forms.ChoiceField(choices = nr_unities),
'nr_sensor_unity': forms.IntegerField(),
'id_sensor': forms.IntegerField(),
'sensor_name': forms.CharField(),
}
id_station = forms.IntegerField(label='id della stazione')
station_name = forms.CharField(label='nome della stazione', max_length=30)
units_number = forms.ChoiceField(label='numero unita', choices = nr_unities) # deve generare dinamicamente il numero di blocchi per unità
nr_sensor_unity = forms.IntegerField(label='numero sensori per unita') # deve generare tanti blocchi quanti sono il numero dei sensori
id_sensor = forms.IntegerField(label='id sensore')
sensor_name = forms.CharField(label='nome sensore', max_length=50)
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import StationForm
from django.forms import formset_factory
from django.views import View
from django.urls import reverse
def new_station(request):
class StationFormView(View):
# We are creating a formset out of the ContactForm
Station_FormSet = formset_factory(StationForm)
# The Template name where we are going to display it
template_name = "static/templates/station.html"
# Overiding the get method
def get(self, request, *args, **kwargs):
# Creating an Instance of formset and putting it in context dict
context = {
'station_form': self.Station_FormSet(),
}
return render(request, self.template_name, context)
#Overiding the post method
def post(self,request,*args,**kwargs):
station_formset=self.Contact_Formset(self.request.POST)
#Checking the if the form is valid
if station_formset.is_valid():
#To save we have loop through the formset
for contacts in station_formset:
#Saving in the contacts models
contacts.save()
return HttpResponseRedirect(reverse("success-url"))
else:
context={
'contact_form':self.Station_FormSet(),
}
return render(request,self.template_name,context)
station.html
{% extends "base.html" %}
{% load static from staticfiles %}
{% block content %}
<div>
<form method="post" action="{% url 'submit' %}">
{% csrf_token %}
<fieldset>
<legend>Contact Details</legend>
<div>
{{ station_form.management_form }}
{% for ele in station_form %}
<div class="link-formset">
{{ ele.as_p }}
</div>
{% endfor %}
</div>
</form>
</fieldset>
</script>
<!-- Include formset plugin - including jQuery dependency -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'path_to/jquery.formset.js' %}"></script>
<script>
$('.link-formset').formset({
addText: 'add new sensor',
deleteText: 'remove'
});
</script>
</div>
{% endblock content %}
Любой другой учебник или предложения". Спасибо.