在我的应用中,我想实现一项功能,用户可以选择创建一个以上具有多个产品的预订。 我的问题是,尽管我可以创建内联表单,但无法在我的view.py
中保存引用预购的实例。我的表单显示为Preorder模型,而我的表单集显示为Preorder_Has_Products关系hp。
预订和产品是具有以下关系的模型:
models.py
class Preorder(models.Model):
client = models.ForeignKey(Client,verbose_name=u'Πελάτης')
preorder_date = models.DateField("Ημ/νία Προπαραγγελίας",null=True, blank=True, default=datetime.date.today)
notes = models.CharField(max_length=100, null=True, blank=True, verbose_name="Σημειώσεις")
preorder_has_products=models.ManyToManyField(Product,blank=True)
def get_absolute_url(self):
return reverse('preorder_edit', kwargs={'pk': self.pk})
我的form.py
class PreorderForm(ModelForm):
class Meta:
model = Preorder
fields=('preorder_date','notes',)
def __init__(self, *args, **kwargs):
super(PreorderForm, self).__init__(*args,**kwargs)
self.fields['preorder_date'].widget = MyDateInput(attrs={'class':'date'})
class PreorderHasProductsForm(ModelForm):
class Meta:
model=Preorder.preorder_has_products.through
exclude=('client',)
def __init__(self, *args, **kwargs):
super(PreorderHasProductsForm, self).__init__(*args, **kwargs)
#self.fields['preorder_date'].widget = MyDateInput(attrs={'class':'date'})
self.fields['product'].label = "Ονομα Προϊόντος"
PreorderProductFormSet = inlineformset_factory(Preorder,Preorder.preorder_has_products.through,
form=PreorderHasProductsForm, extra=1)
我的view.py
class PreorderProductCreateView(LoginRequiredMixin, CreateView):
model = Preorder
fields=['preorder_date','client',]
template_name='test/test.html'
def get_success_url(self, **kwargs):
return reverse('client_list)
def form_valid(self, form):
context = self.get_context_data()
Preorder_Preorder_Has_ProductsFormset = context['Preorder_Preorder_Has_ProductsFormset']
if Preorder_Preorder_Has_ProductsFormset.is_valid() and form.is_valid():
self.object = form.save() # saves Father and Children
#products = Preorder_Preorder_Has_Products_CreateView.save(commit=False)
products=Preorder_Preorder_Has_ProductsFormset.save_m2m()
print(len(products))
for instance in products:
instance.preorder = self.object
instance.save() #douleuei, to self.object anaferetai sto preorder
#Preorder_Preorder_Has_Products_CreateView.save_m2m()
print(instance.id)
print(instance.preorder.id)
print(instance.product_id)
return redirect(self.get_success_url())
else:
return self.render_to_response(self.get_context_data(form=form))
return super(ProductCreateView, self).form_valid(form)
def form_invalid(self, form):
return self.render_to_response(self.get_context_data(form=form))
def get_context_data(self,**kwargs):
data = super(PreorderProductCreateView, self).get_context_data(**kwargs)
self.client=Client.objects.get(pk=self.kwargs['client_pk'])
data['client']= self.client
if self.request.POST:
data['form'] = PreorderForm(self.request.POST)
data['Preorder_Preorder_Has_ProductsFormset'] = PreorderProductFormSet(self.request.POST)#bound the formset with data
else:
data['form'] = PreorderForm(self.request.POST)
data['Preorder_Preorder_Has_ProductsFormset'] = PreorderProductFormSet()#empty formset
return data
最后是我的模板
{% extends 'base.html' %}
{% load bootstrap3 %}
{% load static %}
<!-- Latest compiled and minified JavaScript -->
{% block content %}
<div class="col-md-12 text-center">
<h2>Δημιουργία / Επεξεργασία Προπαραγγελίας </h2>
<div>Πελάτης: <strong>{{client}} </strong></div>
</div>
<hr>
<form class="well" method="post" action="">
{% csrf_token %}
{% bootstrap_form form %}
<table class="table book">
{{ Preorder_Preorder_Has_ProductsFormset.management_form }}
{% for form in Preorder_Preorder_Has_ProductsFormset.forms %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tr class="{% cycle row1 row2 %} formset_row">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'jquery.formset.js' %}"></script>
<script type="text/javascript">
$('table.book tr.formset_row').formset({
addText: 'Πρόσθεσε Προϊόν',
deleteText: 'διαγραφή',
prefix: 'preorder_has_products_set',
animateForms: true
});
</script>
{% buttons %}
<button type="submit" class="btn btn-primary">
Submit
</button>
{% endbuttons %}
</form>
<hr>
{{ form.media }}
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/forms.css' %}"/>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/base.css' %}"/>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/widgets.css' %}"/>
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="/static/admin/js/core.js"></script>
<!-- <script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"></script> -->
<script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.min.js"></script>
<script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
<script type="text/javascript" src="/static/admin/js/actions.min.js"></script>
<script type="text/javascript" src="/static/admin/js/calendar.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/DateTimeShortcuts.js"></script>
{% endblock %}
为什么我不能保存preorder_has_products实例? 模板中前缀的名称是否起作用?
有什么想法吗?
看起来如何