1π
β
It is a bit hard to understand what is attempting to be done because of the generic names, but I will attempt to rewrite your code using a few recommended conventions, and it should hopefully clear up any errors you are having:
def editFoo(request, foo_id):
try:
foo_obj = Foo.objects.get(id=foo_id)
except Foo.DoesNotExist:
... # Handle error here
... # More code here?
print foo_obj.linked_bar.count() # Prints current linked_bar count
linked_bar_id = request.POST.get('linked-bar-id', '')
try:
bar_obj = Bar.objects.get(id=linked_bar_id)
except Bar.DoesNotExist:
... # Handle error here
if bar_obj:
foo_obj.linked_bar.add(bar_obj)
print foo_obj.linked_bar.count() # Prints current linked_bar count
return redirect("/foo/" + foo_id) # Calls showFoo()
def showFoo(request, foo_id):
foo_obj = Foo.objects.get(id=foo_id)
... # More code here?
print foo_obj.linked_bar.count() # Prints current linked_bar count
return render(request, 'TEMPLATE.html', {'foo': foo_obj}) # Replace 'TEMPLATE.html' with your template name
π€Hybrid
1π
The solution turned out to be that there was some other code elsewhere in the application which wiped out foo.linked_bar after Iβd added to it, which I did not spot initially. So, a trivial matter in the end, but most annoying.
Iβll accept the other answer due to the useful coding convention suggestions.
π€knirirr
- [Answered ]-Django downloading a csv file with variable in name
- [Answered ]-Django Tables2 Display Multiple Tables
Source:stackexchange.com