我有两个相关的模型(Sim和Payment-一个Sim可以有很多Payment)。在搜索Sim(通过ID)时,我希望其详细信息以表格形式(我可以)填充。但是使用相同的表格,我也要保存付款模型的详细信息,同时也要更新Sim模型。
我只能使用id填充Sim表单,但不会填充AddPaymentForm。
def updatePayment(request, id):
sim = get_object_or_404(Sim, pk=id)
payment = AddPaymentForm()
sim_form = UpdatePayment(request.POST, instance=sim)
if request.method == "POST":
# sim_form = UpdatePayment(request.POST, instance=payment)
payment_form = AddPaymentForm()
try:
if payment_form.is_valid():
payment_form.save()
sim_form.save()
messages.success(request, ("Payment has been updated"))
else:
messages.warning(request, ("Data in fields is incorrect, please try again"))
except Exception as e:
messages.warning(request, ("Error: {}".format(e)))
else:
form = UpdatePayment(instance=sim)
payment = AddPaymentForm()
context = {'payment': payment, 'form': form,}
return render(request, 'payment/updatePayment.html', context)
答案 0 :(得分:1)
在第7行的代码中,payment_form = AddPaymentForm()是一个空表格,尚未收到任何数据。应该是
payment_form = AddPaymentForm(request.POST)
确保实例从POST操作接收信息。
payment_form = AddPaymentForm(request.POST)
payment_form = payment_form.save(commit=False) ----> (1)
try:
if payment_form.is_valid():
// Add some logic that links your payment form with SIM form,
//for example, like, payment_form(sim=sim_form.id) -------> (2)
payment_form.save()
sim_form.save()
messages.success(request, ("Payment has been updated"))
else:
messages.warning(request, ("Data in fields is incorrect, please try again"))
except Exception as e:
messages.warning(request, ("Error: {}".format(e)))
答案 1 :(得分:-2)
您需要使用基于类的视图!
处理多种表单时有两个显着变化。
这是在一个Django视图中使用多种表单的快速示例。
from django.contrib import messages
from django.views.generic import TemplateView
from .forms import AddPostForm, AddCommentForm
from .models import Comment
class AddCommentView(TemplateView):
post_form_class = AddPostForm
comment_form_class = AddCommentForm
template_name = 'blog/post.html'
def post(self, request):
post_data = request.POST or None
post_form = self.post_form_class(post_data, prefix='post')
comment_form = self.comment_form_class(post_data, prefix='comment')
context = self.get_context_data(post_form=post_form,
comment_form=comment_form)
if post_form.is_valid():
self.form_save(post_form)
if comment_form.is_valid():
self.form_save(comment_form)
return self.render_to_response(context)
def form_save(self, form):
obj = form.save()
messages.success(self.request, "{} saved successfully".format(obj))
return obj
def get(self, request, *args, **kwargs):
return self.post(request, *args, **kwargs)
在此示例中,我在线找到了,我们使用TEMPLATE VIEW。基于类的视图是解决此问题的方法。这是有关如何在Django上使用基于类的视图的最新文档的链接。祝您阅读愉快,最重要的是要有耐心。 https://docs.djangoproject.com/en/2.2/topics/class-based-views/
希望这可以帮助您指导正确的方向。期待听到它的进展。