简体   繁体   中英

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.

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():

I believe this can help solve this issue. Also check django.sessions documentation.

if request.user.is_authenticated(): ...

required settings.py:

INSTALLED_APPS = [
    ...
    'django.contrib.sessions',
    ...
]

MIDDLEWARE_CLASSES = [
    ...
    # middleware attaches user object to request
    'django.contrib.sessions.middleware.SessionMiddleware'
    ...
]

I write this here because i'm not able to post comments yet.

In newer versions of Django , you have to use is_authenticated without the parentheses (at least when doing this on a view):

if request.user.is_authenticated:
    # Do something for authenticated users.
    ...
else:
    # Do something for anonymous users.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM