假设我有一个具有两个模型的应用程序,模型汽车和轮胎模型,每个模型都有一个表单,汽车通过ForeignKey与Tire关联。
#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时,它们将被重定向到Car的DetailView。
#forms.py
class CarCreateForm(forms.ModelForm):
class Meta:
model = Car
fields = (
'car_name',
'car_make'
)
在DetailView页面上,有一个“添加轮胎”按钮,通过单击它可以将用户转移到TireCreateView(具有表单)。
#forms.py
class TireCreateForm(forms.ModelForm):
class Meta:
model = Tire
fields = (
'car',
'tire_name',
'tire_make'
)
但是问题是,在此视图中,用户必须从许多汽车(已经在数据库中)中进行选择,然后输入Tyre详细信息。我要实现以下过程:
如何在TireCreateForm和TireCreateView中定义汽车零件,以自动获取用户想要将Tire添加到的汽车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"),
]
答案 0 :(得分:0)
点击添加轮胎按钮时,通过网址发送汽车的pk ID以创建视图
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")
答案 1 :(得分:0)
我想我是通过修改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()