update another table via form
Date: March 24th 2016
Last updated: March 24th 2016
The title is about the best I could come up with for this entry. This is the example: I have three models; 1) User, 2) Surfers and 3) Boards. Surfers can be considered a profile page for each surfer. I have a foreign key linking Surfer profiles to Users (OneToOne relationship), and Boards to Surfers (ManyToMany relationship). Any user can add a Board to the database. The objective of this example is to update a surfer profile with a new board if they are the currently logged in User.
views.py
@login_required
def addboard(request, surfer_id):
""" Add a board to the website and associate with current profile """
surfer = get_object_or_404(Surfer, pk=surfer_id)
if request.method == "POST":
form = BoardForm(request.POST)
if form.is_valid():
board = form.save()
############## solution ########################
surfer.boards.add(board)
surfer.save()
################################################
return redirect('/{}/'.format(surfer_id))
else:
form = BoardForm()
# also return the surfer object so it is available in the html
return render(request, 'surferprofile/addboard.html',
{'surfer': surfer, 'form': form})
forms.py
class BoardForm(forms.ModelForm):
class Meta:
model = Board
fields = ['boardtail','boardlength', 'boardwidth',
'boardthickness','boardvolume', 'boardrocker',
'boardmake', 'boardshaper']
addboard.html
{% extends 'surferprofile/base.html' %}
{% block title_block %} Add boards {% endblock %}
{% block body_block %}
<h1>Add a new board</h1>
<!-- check if the user id matches the surfer trying to be updated -->
{% if user.id == surfer.user.id %}
<form method="POST" class="post-form">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% else %}
<!-- show the missmatch in IDs -->
<p>user.id ={{ user.id}}</p>
<p>surfer.user.id = {{ surfer.user.id}}</p>
{% endif %}
{% endblock %}