问题
I'm new to django (and programming in general). Sorry if I used the wrong vocabulary (and please correct me). This is what i'm trying to do:
I have this model:
Class A(models.Model):
name = models.CharField(max_length=100, null=True, default='John')
first_number = models.FloatField(blank=True, default=1)
second_number = models.FloatField(blank=True, default=2)
third_number = models.FloatField(blank=True, default=3)
And I have this form:
class Numbers(ModelForm):
class Meta:
model = A
fields = ['first_number', 'second_number']
In my template, I created a for for x in a (given that 'a' is A.objects.all()):
{% for x in a %}
{{form}}
{% endfor %}
When I submit the form, though, I cant get the corresponding numbers. I only saves the last number I enter in both 'first_number' and 'second_number' for the both objects that I created.
How can I save the correct values?
回答1:
When you render forms like this in a loop you get a number of identical forms in your page code with a number of inputs with the same "name" attributes. If you include your loop into a single tag your POST request will always send the last values found inside form for each field name.
<form>
<input name="first_number" value="1">
<input name="first_number" value="2">
<input name="first_number" value="3">
</form>
POST dict will contain {"first_number": "3"}
This will render each of your form but you'll be able to submit only one at once:
{% for x in a %}
<form>
{{form}}
</form>
{% endfor %}
If you want to deal with identical data and send it as a list you'll need to use "prefix" arg in your form instances:
a = [Numbers(instance=x, prefix=str(x.pk)) for x in A.objects.all()]
#and then in a view
a = [Numbers(request.POST, instance=x, prefix=str(x.pk))
for x in A.objects.all()]
if all([f.is_valid() for f in a]):
for f in a:
f.save(commit=True)
This is a slightly primitive example. In real life you would probably like to add some hidden field to your form to pass a list of ids (as json maybe) to a form, and then iterate over it instead of all instances in your db
来源:https://stackoverflow.com/questions/64030787/django-forms-create-a-form-for-each-object-in-model-and-then-save-to-the-corr