Django中如何变更用车请求的状态(WAITING/CONFIRMED/DENIED)
Solution to Update RequestCar Situation on Approval
To update the RequestCar's situation to "CONFIRMED" when the request is approved, you'll need to modify your replyGeneralRequest view to check the approval status after saving the ResponseRequest instance, then update the linked RequestCar.
Modified views.py Code
def replyGeneralRequest(request, template_name="answer/reply_request.html"): form = AnswerRequestForms(request.POST or None, request.FILES or None) if form.is_valid(): # Save the response and capture the saved instance response = form.save() # Update RequestCar situation if approved if response.accepted is True: request_car = response.request request_car.situation = "CONFIRMED" request_car.save() # Optional: Handle denied requests (remove if not needed) elif response.accepted is False: request_car = response.request request_car.situation = "DENIED" request_car.save() return redirect('listGeneralRequest') else: form = AnswerRequestForms() return render(request, template_name, {'form': form})
Key Breakdown:
- Capture the Saved Response: When you call
form.save(), it returns the savedResponseRequestobject. We store this inresponseto access its fields later. - Check Approval Status: We verify if
response.acceptedisTrue—this means the request was approved. - Update the Linked RequestCar: Using
response.request, we get the associatedRequestCarinstance (sincerequestis the ForeignKey inResponseRequestpointing toRequestCar). We then set itssituationto "CONFIRMED" and save the changes. - Optional Denied Handling: Added an optional section to set
situationto "DENIED" if the request was rejected—feel free to remove this if you don't need it.
Important Notes:
- Make sure your
AnswerRequestForms(a ModelForm forResponseRequest) includes theacceptedfield so users can select the approval status. - If your view is meant to reply to a specific
RequestCar, you should modify the view to accept arequest_idparameter. For example:
This ensures thedef replyGeneralRequest(request, request_id, template_name="answer/reply_request.html"): target_request = RequestCar.objects.get(id=request_id) if request.method == 'POST': form = AnswerRequestForms(request.POST, instance=ResponseRequest(request=target_request)) # ... rest of the validation logic ... else: form = AnswerRequestForms(initial={'request': target_request}) # ... rest of the view code ...ResponseRequestis automatically linked to the correctRequestCarwithout requiring the user to select it manually.
内容的提问来源于stack exchange,提问作者Aníbal Filho
相关产品推荐
相关产品推荐

