Django - view, weirdness

I noticed strange behavior with the way Django handles my url patterns. The user must log in and then be redirected to his profile page. I also have the ability for the user to edit their profile.

Here are my URL patterns for one of my applications:

urlpatterns=patterns('student.views',
    (r'profile/$', login_required(profile,'student')),
    (r'editprofile/$', login_required(editprofile,'student')),
)

This is for an app called a student. If the user goes to / student / profile, they should get a profile view. If they go to / student / editprofile, they should get an editprofile view. I am setting up the login_required function, which performs some checks for the user. This is a bit more complicated than I could handle with annotations only.

Here login_required:

def login_required(view,user_type='common'):
    print 'Going to '+str(view)
    def new_view(request,*args,**kwargs):
        if(user_type == 'common'):
            perm = ''
        else:
            perm = user_type+'.is_'+user_type
        if not request.user.is_authenticated():
            messages.error(request,'You must be logged in.  Please log in.')
            return HttpResponseRedirect('/')
        elif request.user.is_authenticated() and user_type != 'common' and not request.user.has_perm(perm):
            messages.error(request,'You must be an '+user_type+' to visit this page.  Please log in.')
            return HttpResponseRedirect('/')
        return view(request,*args,**kwargs)
    return new_view

, , , /student/profile, , login_required :

Going to <function profile at 0x03015DF0>
Going to <function editprofile at 0x03015BB0>

? ?

, /student/editprofile, - , , , :

Going to <function profile at 0x02FCA370>
Going to <function editprofile at 0x02FCA3F0>
Going to <function view_profile at 0x02FCA4F0>

view_profile - .

+3
3

:

(r'profile/$', login_required(profile,'student')),
(r'editprofile/$', login_required(editprofile,'student')),

http://your-site/student/editprofile.

:

(r'^profile/$', login_required(profile,'student')),
(r'^editprofile/$', login_required(editprofile,'student')),

Django , (. 3).

+2

, @login_required - , , , \, .

, , , print , , , urlconf. new_view, , , .

+2

login_required python. , urls.py?

I think the string print 'Going to '+str(view)gets a reading grade urlpatternsto determine which view to perform. It looks weird, but I don’t think it will hurt you.

The line print 'Going to '+str(view)will not be executed every time the image is deleted, only when the url pattern is evaluated (I think). Code in new_viewis the only code that will definitely execute as part of a view.

+1
source

Source: https://habr.com/ru/post/1787511/


All Articles