假设我有一个应用程序,有两种模型,模型汽车和模型轮胎,每个模型都有一个表单,并且汽车通过外键与轮胎相关联。
#models.py
class Car(models.Model):
car_name = models.CharField(max_length=500, verbose_name="Car")
car_make = models.CharField(max_length=500, verbose_name="Make")
class Tire(models.Model):
car = models.ForeignKey(Car, on_delete=models.CASCADE, default="", related_name="Car")
tire_name = models.CharField(max_length=500, verbose_name="Car")
tire_make = models.CharField(max_length=500, verbose_name="Make")
当用户使用下面的示例表单创建 Car 时,他们将被重定向到汽车的详细信息视图。
#forms.py
class CarCreateForm(forms.ModelForm):
class Meta:
model = Car
fields = (
'car_name',
'car_make'
)
在详细信息视图页面上有一个按钮"添加轮胎",通过单击它,用户将被转移到TireCreateView(具有表单(。
#forms.py
class TireCreateForm(forms.ModelForm):
class Meta:
model = Tire
fields = (
'car',
'tire_name',
'tire_make'
)
但问题是,在此视图中,用户必须从许多汽车(已经在数据库中(中进行选择,然后输入轮胎详细信息。我想实现以下过程:
- 用户访问CarDetailView
- 用户点击"添加轮胎"按钮
- 窗体仅显示tire_name和tire_make字段
- 用户填写这些字段并提交表单
- 轮胎详细信息从步骤 1 添加到汽车中
如何在 TireCreateForm 和 TireCreateView 中定义汽车部件,以自动获取用户希望添加轮胎的汽车 ID?
编辑:
#car_detail.html
<div class="row">
<div class="col-sm-12">
<div class="btn-group pull-right m-t-15">
<div class="button-list">
<a href="{% url 'ap:tire-create' car.id%}" class="btn btn-default waves-effect waves-light">
<span class="btn-label">
<i class="ti-flag"></i>
</span> Add Tire</a>
</div>
</div>
#views.py
class CarDetailView(DetailView):
template_name = 'car_detail.html'
queryset = Car.objects.all()
def get_object(self):
id_ = self.kwargs.get("id")
return get_object_or_404(Car, id=id_)
class TireCreateView(CreateView):
template_name = 'tire_create.html'
form_class = TireForm
queryset = Tire.objects.all()
def get_initial(self):
return dict(car=self.kwargs.get("id"))
def form_valid(self, form):
#Meta information
form.instance.created_by = self.request.user
form.instance.created_date = timezone.now()
return super().form_valid()
#urls.py
urlpatterns = [
path('create/<int:id>', TireCreateView.as_view(), name="tire-create"),
]
当您单击添加轮胎按钮时,发送汽车的 pk id 以通过 url 创建视图
car_detail.html
<a href="{% url 'app_name:add_tires' car.pk %}" class="btn btn-info" role="button">Add Tire</a>
urls.py
urlpatterns = [
path('add_tires/<pk:uuid>', views.TireCreateView.as_view()),
]
views.py重写get_initial
方法以将初始值发送到表单
class CreateTireView(CreateView)
# your CreateTireView
#####
def get_initial(self):
"""Return the initial data to use for forms on this view."""
return dict(car=self.kwargs.get("pk")
我想我通过修改 views.py 来修复它:
views.py
class TireCreateView(CreateView):
template_name = 'tire_create.html'
form_class = TireForm
queryset = Tire.objects.all()
def form_valid(self, form):
car = get_object_or_404(Car, id=self.kwargs.get("id"))
form.instance.car = car
#Meta information
form.instance.created_by = self.request.user
form.instance.created_date = timezone.now()
return super().form_valid()