Python 在django中同时保存多个数据,如复选框
我在ang django项目在线投票中工作。在我的模板中,我使用 循环以循环所有位置和候选人。我在一个属性中一次保存多个数据时遇到问题,例如,在我的模型中,我有:Python 在django中同时保存多个数据,如复选框,python,html,django,Python,Html,Django,我在ang django项目在线投票中工作。在我的模板中,我使用 循环以循环所有位置和候选人。我在一个属性中一次保存多个数据时遇到问题,例如,在我的模型中,我有: class Vote(models.Model): candidate_id = models.ForeignKey('Candidate', blank=True, null=True) election_id = models.ForeignKey('Election', blank=True, null=True) user_i
class Vote(models.Model):
candidate_id = models.ForeignKey('Candidate', blank=True, null=True)
election_id = models.ForeignKey('Election', blank=True, null=True)
user_id = models.ForeignKey('User', blank=True, null=True)
def __str__(self):
return "%s %s" % (user_id.first_name, election_id.year)
在my template vote.html中:
<form method="POST" class="form-horizontal" role="form">
{% if success %}
<div class="alert alert-success">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Success!</strong> {{ success }}
</div>
{% endif %}
{% if exist %}
<div class="alert alert-warning">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Warning!</strong> {{ exist }}
</div>
{% endif %}
{% csrf_token %}
<div class="form-group ">
{% for position in positions %}
<label for="cname" class="control-label col-lg-2">{{ position }}<span class="required">*</span></label>
{% for candidate in candidates %}
{% if position.pk == candidate.position_id.pk %}
<div class="col-lg-3">
<input type="checkbox" name="candidate_id" value="{{ candidate.pk }}">{{ candidate }}<br>
</div>
{% endif %}
{% endfor %}
</div>
{% endfor %}
<button class="btn btn-primary" type="submit">Save</button>
<button class="btn btn-default" type="button">Cancel</button>
</div>
</div>
</form>
为什么在更改每个字段后保存投票?设置好所有字段后保存不会改变这里的任何内容。因为我需要一次获得他们所有的赌注并保存它。比如总统和副总统。之后,将其交给views.py并保存在candidate_id属性中。
def vote(request):
if request.user.is_authenticated and request.user.is_admin:
candidates = Candidate.objects.all()
election = Election.objects.all().filter(is_active=True)
positions = Position.objects.all()
user = get_object_or_404(User, pk=request.user.pk)
try:
if request.method == 'POST':
candidate_id = request.POST['candidate_id']
vote = Vote.objects.create(candidate_id=candidate_id)
vote.save()
vote.election_id = election
vote.save()
vote.user_id = user
vote.save()
else:
form = VoteForm()
return render(request,'system/vote.html', {'form':form, 'candidates': candidates,
'election': election, 'user': user,
'positions': positions})
except:
exist = "ERROR!"
form = VoteForm()
return render(request,'system/vote.html', {'form':form, 'exist': exist})
elif not request.user.is_authenticated:
return redirect('system.views.user_login')