Django将记录添加到许多领域

时间:2018-12-04 14:18:45

标签: python django many-to-many

我在创建新记录并将其添加到manytomanyfield时遇到问题。使用我拥有的代码,我可以添加新服务。而且工作正常。问题是如何传递参数Car_id并将新的Service添加到服务。

我的模型。py:

class Service(models.Model):
mileage_number = models.DecimalField(max_digits=8, decimal_places=0)
cash_float = models.DecimalField(max_digits=6, decimal_places=2)
note_text = models.CharField(max_length=256, null=True)
title_text = models.CharField(max_length=32)
created_date = models.DateField(default=timezone.now)

def __str__(self):
    return f"{self.title_text}"

class Car(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
mark_text = models.CharField(max_length=32, null=False, default='mark')
model_text = models.CharField(max_length=32, null=False, default='model')
services = models.ManyToManyField(Service)
refueling = models.ManyToManyField(Fueling)

def __str__(self):
    return f"{self.mark_text} {self.model_text}"

我的urls.py:

path("", views.index, name='index'),
path('register', views.register, name='register'),
path('logout/', views.LogoutView.as_view(), name='logout'),
path('car/<int:Car_id>/', views.CarView, name="car"),
path('car/<int:Car_id>/serv/<int:Service_id>/', views.ServiceView, name="service"),
path('car/<int:Car_id>/fuel/<int:Fuel_id>/', views.FuelView, name="fuel"),
path('add_car/', views.CarEntry.as_view(), name="add_car"),
path('car/<int:Car_id>/add_service', views.ServiceEntry.as_view(C_id='Car_id'), name="add_service"),

我的html:

<div class="mx-auto" style="width: 300px;">
<form method="post" class="form" >
    {% csrf_token %}
    {% bootstrap_form form %}
    {% buttons %}
        <button type="submit" class="btn btn-primary" style="width: 300px;">
            Submit
        </button>
    {% endbuttons %}
</form>

我的views.py

class ServiceEntry(CreateView):
model = Service
success_url = "/"
template_name = "Site/add_service.html"
fields = [
    'mileage_number',
    'cash_float',
    'note_text',
    'title_text',
    'created_date',
]
enter code here

1 个答案:

答案 0 :(得分:0)

在您的网址中添加views.ServiceEntry.as_view(C_id='Car_id')毫无意义;不管怎样,Django都会从URL传递Car_id。只要拥有views.ServiceEntry.as_view()

要将相关汽车自动添加到新服务中,您需要在ServiceEntry中覆盖form_valid

def form_valid(self, form):
    service = form.save()
    car = Car.objects.get(pk=self.kwargs['Car_id'])
    service.car_set.add(car)
    return redirect(self.success_url)