英文:
saving checkbox values in django form
问题
我的HTML(带有每个项目的复选框):
<form method='POST' action="{% url 'create-boards' %}">
<div class="select-display">
<h3 id="select-text">选择</h3>
<div class="select-container">
{% for item in clothes %}
<div class="column stacked featured">
<input class="checkbox" id="mycheckbox" type="checkbox" name="selected_clothes">
<label for="mycheckbox">
<img class="gallery column__img" src="{{ item.image.url }}">
</label>
</div>
{% endfor %}
</div>
</div>
</form>
模型:
class Clothes(models.Model):
# ...(略)
class Boards(models.Model):
# ...(略)
selected_clothes = models.ManyToManyField('Clothes', null=True)
表单:
class BoardsForm(forms.ModelForm):
selected_clothes = forms.ModelMultipleChoiceField(
queryset=Clothes.objects.all(),
widget=forms.CheckboxSelectMultiple(),
required=True)
class Meta:
model = Boards
fields = ('title', 'description', 'selected_clothes')
视图:
def create_board(request):
if request.method == 'POST':
form = BoardsForm(request.POST or None)
if form.is_valid():
title = request.POST['title']
description = request.POST['description']
selected_clothes = form.save(commit=True)
create_boards = Boards(title=title, description=description, selected_clothes=selected_clothes)
create_boards.save()
return HttpResponseRedirect(reverse(boards))
else:
return HttpResponse('表单无效')
英文:
I'm trying to make a boards function, where you select the clothes you want (in checkboxes), but i'm not being able to save the checked items into my django model because the form is invalid
my html (with checkboxes for each item):
<form method='POST' action="{% url 'create-boards' %}">
<div class="select-display">
<h3 id="select-text">Select</h3>
<div class="select-container">
{% for item in clothes %}
<div class="column stacked featured">
<input class="checkbox" id="mycheckbox" type="checkbox" name="selected_clothes">
<label for="mycheckbox">
<img class="gallery column__img" src="{{ item.image.url }}">
</label>
</div>
{% endfor %}
</div>
</div>
</div>
</form>
models.py
class Clothes(models.Model):
title = models.CharField(max_length=50)
image = models.ImageField(default='', upload_to='wardrobe/')
category = models.CharField(max_length=200, null=True, blank=True)
brand = models.CharField(max_length=200, null=True, blank=True)
color = models.CharField(max_length=200, null=True, blank=True)
time = models.DateTimeField(default=datetime.datetime.now())
deleted = models.BooleanField(default=False)
class Meta:
verbose_name_plural = 'Clothes'
def __str__(self):
return f'{self.color} {self.title} from {self.brand}'
class Boards(models.Model):
title = models.CharField(max_length=50)
description = models.CharField(max_length=500)
selected_clothes = models.ManyToManyField('Clothes', null=True)
forms.py
from django import forms
from .models import User, Clothes, Boards
class BoardsForm(forms.ModelForm):
forms.ModelMultipleChoiceField(
queryset=Clothes.objects.all(),
widget=forms.CheckboxSelectMultiple(),
required=True)
class Meta:
model = Boards
fields = ('title','description','selected_clothes')
views.py
def create_board(request):
if request.method == 'POST':
form = BoardsForm(request.POST or None)
if form.is_valid():
title = request.POST['title']
description = request.POST['description']
selected_clothes = form.save(commit=True)
create_boards = Boards(title=title, description=description, selected_clothes=selected_clothes)
create_boards.save()
return HttpResponseRedirect(reverse(boards))
else:
return HttpResponse('the form is invalid')
答案1
得分: 1
上述代码看起来不错,但您还没有指定要通过表单提交的复选框的值,而且还要在您的表单中添加{% csrf_token %}。
最终的代码如下:
<input class="checkbox" id="mycheckbox" type="checkbox" name="selected_clothes" value="{{item.image.id}}">
或者
<input class="checkbox" id="mycheckbox" type="checkbox" name="selected_clothes" value="{{item.image.url}}">
使用图像的ID更好,根据您的要求随意修改,并更新views.py如下:
selected_clothes = request.POST.getlist('selected_clothes')
然后遍历所有选定的项目列表并手动保存它们,以避免意外错误。
希望这对您有帮助。
英文:
The above code looks good but you haven't specified the value of the checkbox which you are actually need to submit through your form and also add the {% csrf_token %} to your form.
the final code looks like
<input class="checkbox" id="mycheckbox" type="checkbox" name="selected_clothes" value="{{item.image.id}}">
or
<input class="checkbox" id="mycheckbox" type="checkbox" name="selected_clothes" value="{{item.image.url}}">
using the id of the image is better feel free to modify according to your requirements and the updates views.py as
selected_clothes = request.POST.getlist('selected_clothes')
and iterate through the list of all elected items and save them manually its better to avoid unintended errors
Hope this works for you
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论