Skip to content
Advertisement

Django – login required for POST but not GET?

So I’m trying to do a site with user editable tags on items. I want users to be able to edit tags on the page only if they are logged in, but everyone should be able to view the page. The edits are done through a modelform. I can’t use the login_required decorator on the whole view because then only authenticated users would be able to see the page at all, which is not what I want. The edit element will be a little slide out dongle that will be done with AJAX later on, is there any way to make sure if a user is logged in if they click the edit button? What my view looks like for the page:

def show_gallery(request, gallery_id):
    gallery = get_object_or_404(Gallery, id=gallery_id)
    print gallery.name

    if request.method == 'POST':
        form = GalleryEditForm(request.POST, instance=gallery)

        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
        else:
            print "invalid"
    else:
        form = GalleryEditForm(instance=gallery)

        return render(request, "gallerypage.html", {
            'gallery': gallery,
            'tags': gallery.misc_tags.names(),
            'form': form
        })

Thanks.

Advertisement

Answer

You can use is_authenticated property of user in template in this way by making field readonly:

{% if user.is_authenticated %}
    fields
{% else %}
    read only value
{% endif %}

OR

replace a code in view

if request.method == 'POST' and request.user.is_authenticated():
Advertisement