I have the following urls:
# urls.py
url(r'^proposal/(?P<pk>\d+)/$', ProposalDetail.as_view(), name='proposal_detail'),
url(r'^contract/(?P<pk>\d+)/$', ContractDetail.as_view(), name='contract_detail'),
url(r'^proposal/edit/contract/$', 'create_contract', name='create_contract_url'),
It means that I have /proposal/1/
,
but in my example I will not have /contract/3/
yet,
that is, /contract/3/
is a contract that does not exist yet,
and when it exists it will have a pk
that can be different from proposal
.
# views.py
class ProposalDetail(DetailView):
template_name = 'core/proposal/proposal_detail.html'
model = Proposal
For contract
exists I will execute the following function ...
def create_contract(request, pk):
if request.user.is_authenticated:
proposal = Proposal.objects.get(pk=pk)
if proposal.status != 'co':
return HttpResponse('O status do orçamento deve ser concluido.')
else:
contractor = proposal.work.customer
obj = Contract(
proposal=proposal,
contractor=contractor
)
obj.save()
proposal.status = 'a'
proposal.save()
return redirect('/contract/%d' % obj.id)
... from this button.
# proposal_detail.html
<form class="navbar-form navbar-right" action="." method="get">
<a class="btn btn-primary" href="{% url 'create_contract_url' proposal.id %}"><i class="icon-edit icon-white"></i> Criar Contrato</a>
</form>
The problem is that I can not control the pk
correctly.
Question: How do I improve this code to inform pk
of proposal
in function create_contract
and redirect the page to /contract/3
, where 3
will be a new pk
of contract
, but it does not exist yet?