[Answered ]-Django-How to deny access to a logged user directly to a specific URL

1πŸ‘

I think foreign key is the solution you are looking for make β€˜A’ as the foreign-key of β€˜B’ and in the url of the β€˜B’ pass the id of β€˜A’ as argument like this url(r'^A/(?P<A_id>[0-9]+) this way first user will input data in β€˜A’ it will get stored in database then accesing your β€˜B’ will be available through id of β€˜A’. Read more about foreign-key here.

πŸ‘€abhi

1πŸ‘

Currently, I’m working on a mathematics homework project. There are three types of users. Professors, students, and admins. The following snippet will deny user to access a url based on the users’ type. After you modify it, you will have to add this method decorator to your request method that serve the http request.

def deny_a_thing(function):
    def wrapper(request, *args, **kw):
        try:
            test = User.objects.get(username=request.user)   # This will get the username
        except ObjectDoesNotExist:
            raise Http404                                    # return 404, if the user doesn't exist. You can change it to anything
        if not request.user.is_authenticated():              # If the user is not authenticated, return to the rootm. You can also change this.
            return HttpResponseRedirect("/")
        try:
            if test.groups.filter()[0].name != "professors": # Add your test here. E.g: If user saved A, don't go B.
                raise Http404
        except IndexError:
            raise Http404
        else:
            return function(request, *args, **kw)
    return wrapper

Add the following to your method

@deny_a_thing                   # This will deny the user from doing the thing you didn't want the user to do.
def some_page_request(request):
    return HttpResponse("OMG")

Check this link for a simpler decorator

πŸ‘€Ahmed

Leave a comment