Django-处理表单,其中包含具有ManyToMany关系的复选框

时间:2019-01-19 18:14:27

标签: python django django-models django-forms django-views

我一直试图使它起作用,但是我似乎做错了事。

我想完成的事情:

我有一个名为Venue的模型,它具有许多便利设施:

class Venue(TimeStampedModel):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=250)
    type = models.ForeignKey(VenueType, on_delete=models.CASCADE)

    def __str__(self):
        return self.name


class Amenity(TimeStampedModel):
    category = models.ForeignKey(AmenitiesCategory, on_delete=models.CASCADE)
    venues = models.ManyToManyField(Venue, blank=True)
    name = models.CharField(max_length=250)
    description = models.TextField()

    def __str__(self):
        return self.name

当用户创建场所时,我希望他们能够查看所有创建的设施并选择适用于其场所的设施。

在我的模板中,我当前显示所有便利设施选项,如下所示:

我首先使用的东西(我更喜欢这样做,因为我可以先遍历每种便利设施的类别):

<div class="ui container">
    <h2>Select all that are applicable</h2>

    <form method="POST" class="ui form">
        {% csrf_token %}
        {% for category in categories %}
        <h4 class="ui horizontal divider header">
            <i class="list icon"></i>
            {{category.category}}
        </h4>
        <p class="ui center aligned text"><u>{{category.description}}</u></p>

        {% for amenity in category.amenity_set.all %}

        <div class="inline field">
            <div class="ui checkbox">
                <input type="checkbox" value="{{amenity.id}}" name="choices">
                <label><span data-tooltip="{{amenity.description}}" data-position="top left">{{amenity}}</span></label>
            </div>

        </div>
        {% endfor %}
        {% endfor %}
        <button type="submit" name="submit" class="ui button primary">Next</button>

    </form>

我之后使用的内容:

    <form method="POST" class="ui form" action=".">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" name="next" class="ui button primary">Next</button>
    </form>
</div>

对于第二种情况,我使用了此ModelForm:

class AmenitiesForm(ModelForm):
    class Meta:
        model = Amenity
        fields = ['choices']

    choices = forms.ModelMultipleChoiceField(Amenity.objects.all(), widget=forms.CheckboxSelectMultiple,)

在此之前,我使用常规表格。但由于某种原因,我无法处理该表格。

这是我现在使用的视图:

class AddAmenitiesView(LoginRequiredMixin, CreateView):

    model = Venue
    form_class = AmenitiesForm
    template_name = 'venues/add_amenities.html'

    def parent_venue(self):
        parent_venue = Venue.objects.get(id=self.kwargs["venue_id"])
        return parent_venue

    def form_valid(self, form):
        # I AM VERY CONFUSED ON WHAT TO DO HERE
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["parent_venue"] = self.parent_venue()
        return context

    def get_success_url(self):

        if 'add-another-space' in self.request.POST:
            return reverse('add-venue-images', kwargs={'venue_id': self.object.venue.id, })
        else:
            return reverse('home')

在我的form_valid()中,我不知道如何处理表单。单击复选框后,它应该添加该设施和场所之间的关系。

我希望我不要让我像迷惑自己那样困惑。

非常感谢您抽出宝贵的时间!

0 个答案:

没有答案