在Django表单中保存复选框的值。

huangapple go评论101阅读模式
英文:

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

                &lt;form method=&#39;POST&#39; action=&quot;{% url &#39;create-boards&#39; %}&quot;&gt;
                    &lt;div class=&quot;select-display&quot;&gt;
                        &lt;h3 id=&quot;select-text&quot;&gt;Select&lt;/h3&gt;
                            &lt;div class=&quot;select-container&quot;&gt;
                                {% for item in clothes %}
                                    &lt;div class=&quot;column stacked featured&quot;&gt;
                                        &lt;input class=&quot;checkbox&quot; id=&quot;mycheckbox&quot; type=&quot;checkbox&quot; name=&quot;selected_clothes&quot;&gt;
                                        &lt;label for=&quot;mycheckbox&quot;&gt;
                                            &lt;img class=&quot;gallery column__img&quot;  src=&quot;{{ item.image.url }}&quot;&gt;
                                        &lt;/label&gt;
                                    &lt;/div&gt;
                                 {% endfor %}
                            &lt;/div&gt;
                        &lt;/div&gt;
                    &lt;/div&gt;
               &lt;/form&gt;

models.py

class Clothes(models.Model):
    title = models.CharField(max_length=50)
    image = models.ImageField(default=&#39;&#39;, upload_to=&#39;wardrobe/&#39;)
    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 = &#39;Clothes&#39;
    
    def __str__(self):
        return f&#39;{self.color} {self.title} from {self.brand}&#39;
    
class Boards(models.Model):
    title = models.CharField(max_length=50)
    description = models.CharField(max_length=500)
    selected_clothes = models.ManyToManyField(&#39;Clothes&#39;, 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 = (&#39;title&#39;,&#39;description&#39;,&#39;selected_clothes&#39;)

views.py

def create_board(request):
    if request.method == &#39;POST&#39;:
        form = BoardsForm(request.POST or None)
        if form.is_valid():
            title = request.POST[&#39;title&#39;]
            description = request.POST[&#39;description&#39;]
            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(&#39;the form is invalid&#39;)

答案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

                                    &lt;input class=&quot;checkbox&quot; id=&quot;mycheckbox&quot; type=&quot;checkbox&quot; name=&quot;selected_clothes&quot; value=&quot;{{item.image.id}}&quot;&gt;

or

        &lt;input class=&quot;checkbox&quot; id=&quot;mycheckbox&quot; type=&quot;checkbox&quot; name=&quot;selected_clothes&quot; value=&quot;{{item.image.url}}&quot;&gt;

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

huangapple
  • 本文由 发表于 2023年7月27日 22:42:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76780883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定