[Answered ]-Updating single Django model field

2๐Ÿ‘

โœ…

you must create a specific view with a specific url to handle this, for example:

# urls.py
url(r'^movetounknown/(?P<notecard_id>[\w|\W]+)/', notecard_move_to_unknown)

# views.py
@require_POST
def notecard_move_to_unknown(request, notecard_id):
    notecard = Notecard.objects.get(pk=notecard_id)
    notecard.known = False
    notecard.save()
    return HttpResponseRedirect(request.POST['next'])


# template
{% for notecard in known.object_list %}
    <h1 class='notecard'>{{ notecard.notecard_name }}</h1>
    <h3 class='notecard'>{{ notecard.notecard_body }}</h3>
    <form action="{% url views.move_to_unknown notecard.pk %}" method="post">
        <input type="hidden" name="next" value="{% url known_list known.section.section_name %}?page={{known.paginator.number}}"/>
        <input type="submit" value="Move to unknown list"/>
    </form>
{% endfor %}

You also can pass the notecard id as a post parameter.
The next parameter tells where to go after the change, here I choose the same page of the known list because once the current card is removed the next one is at this index

๐Ÿ‘คClaude Vedovini

0๐Ÿ‘

Capturing the pk of a specific notecard object can be done by defining a specific url for that notecard. For example:-

# urls.py
url(r'^notecard/(?P<notecard_id>\d+)/$',
    'notecard',
    name='notecard'),

# corresponding views.py
def notecard(request, note_card_id):
    notecard = get_object_or_404(Notecard, pk=note_card_id)
    template = 'notecard/notecard.html'
    template_vars = {'notecard': notecard}
    render(request, template, template_vars)

# notecard/notecard.html
<h2>{{ notecard.notecard_name }}</h2>
<p>{{ notecard.notecard_body }}</p>

You can also define a form with the notecard id/pk being a hidden field for submission and updating into your database (and of course, you will need to update your view function correspondingly).

In essence, to update a specific notecard object, you will simply do in your view function (with form submission or, if you prefer, a pure ajax implementation in your listing page) like this

notecard.known = False
notecard.save()
๐Ÿ‘คCalvin Cheng

Leave a comment