pass 2 variables in an href URL pattern

Date: March 31st 2016
Last updated: March 31st 2016

I need to send two arguments in a URL pattern. This is required because I have two different models being used in the URL. This is better shown rather than explained. Follow the comments inside each code block.

views.py (sending context to profile.html)

@login_required
def profilepage(request, surfer_id):
    surfer = get_object_or_404(Surfer, pk=surfer_id)
    #<- snipped ->
    boardstest = (surfer.boards.all())
    return render(request, 'surferprofile/profile.html',
    {'boardslist': boardslist, 'surfer': surfer})

profile.html (edit button: the point of this example)

<!-- I have a boardslist. For each board I want an edit button 
Note that the boardslist is a queryset of the Surfer model, and there is 
a many to many relationship between Surfer and Boards -->

{% for board in boardslist %}
    {{board}}
    <!-- make sure you assign each argument to a variable e.g. surfer_id -->
    <a href="{% url 'surferprofile:editboard' 
                surfer_id = surfer.id 
                board_id = board.id %}">
        edit
    </a>

<!-- I want the url pattern to be http://http://127.0.0.1:8080/1/boards/1 where 
the first '1' is the surfer id and the second '1' is the board id.-->

urls.py (using name = editboard)

from django.conf.urls import url
from . import views

app_name = 'surferprofile'
urlpatterns = [
    url(r'^(?P<surfer_id>[0-9]+)/boards/(?P<board_id>[0-9]+)$', 
            views.editboard, name='editboard'),]

## Note the url pattern uses both surfer_id and board_id (both are numbers)
## Go to views.py...

views.py

## board_id captures the object instance 
## surfer_id is used for the redirect back to their profile page

@login_required
def editboard(request, surfer_id, board_id):
    # Get the object instance
    board = get_object_or_404(Board, pk=board_id)

    # BoardForm is already created for users to ADD boards 
    # The difference here is the "instance=board" argument
    form = BoardForm(request.POST or None, instance=board)
    if form.is_valid():
        board = form.save()
        # Redirect
        return redirect('/{}/'.format(surfer_id))
    return render(request, 'surferprofile/updateboard.html', 
    {'board': board, 'form': form})

results matching ""

    No results matching ""