以django形式保存复选框值

k2arahey  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(104)

我试图使一个boards功能,在那里你选择你想要的衣服(在复选框中),但是我不能保存选中的物品到我的Django模型中,因为表单是无效的
我的html(每个项目都有复选框):

<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')

v1uwarro

v1uwarro1#

上面的代码看起来不错,但您还没有指定复选框的值,您实际上需要通过表单提交该复选框,并将{% 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')
并循环访问所有选定项的列表,然后手动保存它们,这样可以更好地避免意外错误
希望这对你有用

相关问题