DjangoManyToMany.add()不会向创建的对象添加元素

muk1a3rh  于 2022-12-30  发布在  Go
关注(0)|答案(2)|浏览(117)

这是在我的模板:

<form hx-post="{% url 'orders:create' %}">
    {% csrf_token %}
    {% for service in venue.services.all %}
            <input type="checkbox" name="services" value="{{ service.id }}"> {{ service.name }}<br>
    {% endfor %}
        <button
          hx-include="[name='id']"
          type="submit"
          class="btn btn-primary btn-lg ">
          <input type="hidden" value="{{ venue.id }}" name="id">
          Submit
        </button>
  </form>

这是一个观点:

class OrderCreateView(CreateView):
    model = Order
    form_class = OrderForm
    template_name = "orders/order_page.html"
    success_url = reverse_lazy("orders:success")

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["venues"] = Venue.objects.all()
        return context

    def form_valid(self, form):
        if self.request.htmx:
            # Get the IDs of the chosen services
            service_ids = self.request.POST.getlist('services')

            # Set the venue field of the form
            form.instance.venue = Venue.objects.get(id=self.request.POST.get("id"))

            # Save the form
            self.object = form.save()

            # Add the chosen services to the Order object
            for service_id in service_ids:
                service = Service.objects.get(id=service_id)
                self.object.chosen_services.add(service)

            return super().form_valid(form)

问题是对象正在创建,但只有form. instance. venue行有效,添加choose_services的部分不起作用,对象创建时没有任何一个。service_ids变量填充了前端的信息,它有我需要的id,只是没有将它们添加到对象中。
This is models.py:

class Order(models.Model):
   venue = models.ForeignKey(Venue, on_delete=models.SET_NULL, null=True)
   chosen_services = models.ManyToManyField(Service, null=True, blank=True)
5lhxktic

5lhxktic1#

试试这个代码
这里m2m字段已经由form处理了,你只需要用form的save()方法设置venue字段的值

def form_valid(self, form):
    if self.request.htmx:
        # Get the IDs of the chosen services
        service_ids = self.request.POST.getlist('services')
        fm = form.save()
        # Set the venue field of the form
        fm.venue = Venue.objects.get(id=self.request.POST.get("id"))
        fm.save()
        
        return super().form_valid(form)
up9lanfz

up9lanfz2#

问题是,在forms.py我有这个:

class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ["chosen_services"]

我删除了它,现在它的工作!

相关问题