我有两个模型ProductionProcess
和ProductsMaster
当我使用{{ object.ProductName }}
时,它附带了所有ForeignKey
数据。但我只想选择url
在Models.py
ProductionProcess
中有ProductsMaster
forwignKey
models.py
class ProductsMaster(models.Model):
Name = models.CharField(max_length=40)
SalesPrice = models.FloatField()
FabricCode = models.CharField(max_length=30)
SizeType = models.CharField(max_length=30)
RequiredFabric = models.CharField(max_length=30)
def __str__(self):
return self.Name
class Meta:
verbose_name_plural = "ProductsMaster"
class ProductionProcess(models.Model):
ProductName = models.ForeignKey(ProductsMaster,on_delete=models.CASCADE)
Name = models.CharField(max_length=30)
PerformAtProduction = models.BooleanField()
def __str__(self):
return self.Name
class Meta:
verbose_name_plural = "ProductionProcess"
在Viwes中,获取pk的get方法重写 Views.py
class ProductionProcessCreateView(CreateView):
model = ProductionProcess
form_class = ProductionProcessForm
ExampleFormSet = formset_factory(ProductionProcessForm,)
template_name="master/productionprocess_form.html"
def get_success_url(self):
return reverse_lazy('tailoring-products')
def get(self, request, *args, **kwargs):
product = get_object_or_404(ProductsMaster, pk=self.kwargs['pk'])
print(self.kwargs['pk'])
context={'ProductionProcessForm':self.ExampleFormSet(),'id':product}
return render(request,self.template_name,context)
def post(self,request,*args,**kwargs):
ExampleFormSet = self.ExampleFormSet(self.request.POST)
product = get_object_or_404(ProductsMaster, pk=self.kwargs['pk'],)
# product_id = self.kwargs['pk']
# print(product_id)
if ExampleFormSet.is_valid():
for docs in ExampleFormSet:
# docs.Name = docs.cleaned_data['Name']
# docs.ProductName = docs.cleaned_data['ProductName']
# docs.PerformAtProduction = docs.cleaned_data['PerformAtProduction']
docs.save(commit=False)
docs.instance.ProductName_id = self.kwargs.get('pk')
# print(docs.instance.ProductName_id)
docs.save()
return HttpResponseRedirect(self.get_success_url())
else:
context={
'ExampleFormSet':self.ExampleFormSet(),
# 'form':form
}
return render(request,self.template_name,context)
HTML
<th class="column-title">ProductName </th>
<th class="column-title">PROCESS NAME</th>
<th class="column-title">PERFORM AT PRODUCTION</th>
<th class="column-title">Action </th>
</tr>
</thead>
<tbody >
{% for object in ProductionProcessForm %}
{{ ProductionProcessForm.management_form }}
<tr id="formset" class="even pointer">
<td class=" ">{{ object.ProductName }} </td>
<td class=" ">{{ object.Name }}</td>
<td class=" ">{{ object.PerformAtProduction }}</td>
<td class=""></td>
</tr>
{% endfor %}
</tbody>
</table>
<button id="send" type="submit" class="btn btn-success">Submit</button>
</div>
答案 0 :(得分:0)
docs.save(commit=False)
docs.instance.ProductName_id = self.kwargs.get('pk')
docs.instance.user = self.request.user
docs.save()