0
我希望父母的變量之一可以在孩子的模型表格中預先填充,具體爲序列號。我設法將序列號作爲URL的一部分,但想弄清楚它如何在表單頁面上作爲變量實現。在Django的childs對象模型表單中設置父項值?
Models.py
class Product(models.Model):
serial_number = models.CharField(unique=True, max_length=15)
class ProductInstance(models.Model):
serial_number = models.ForeignKey('Product', on_delete=models.SET_NULL, null=True)
Views.py
class ProductInstanceCreate(CreateView):
model = ProductInstance
template_name = 'myapp/edit_productinstance.html'
form_class = GunInstanceForm
def get_success_url(self):
return reverse_lazy ('product-detail', kwargs={'pk': self.object.serial_number.pk})
Forms.py
class ProductInstanceForm(forms.ModelForm):
class Meta:
model = ProductInstance
fields = '__all__'
個模板/ MYAPP/product_detail.html
...
<a href="{% url 'productinstance_create' serial_number=product.serial_number %}">New</a>
...
urls.py
urlpatterns += [
url(r'^productinstance/(?P<serial_number>[-\w]+)/create/$', views.ProductInstanceCreate.as_view(), name='productinstance_create'),]
模板/ MYAPP/edit_productinstance_form.html
{% extends "base_generic.html" %}
{% block content %}
<h2>Serial Number: {{ serial_number }}</h2>
</br>
<form action="" method="post">
{% csrf_token %}
<table>
{{ form }}
</table>
<input type="submit" value="Submit" />
</form>
</br>
<a href="">Back</a>
{% endblock %}
所以目前我可以創造一個URL例如:productinstance/D1430913/create/
我現在需要知道:
如何使用它作爲標題的變量?
如何設置窗體的默認值呢?