How to pass a variable from the url to a view in django?

前端 未结 4 365
忘了有多久
忘了有多久 2021-01-16 10:23

Simple question.

How can I pass a variable from the URL to the view? I\'m following the Date Example.

My view needs to arguments:

def hours_         


        
相关标签:
4条回答
  • 2021-01-16 10:52

    you can add additional variables like this:

    (r'^plus/\d{1,2}/$', {'hours' : 5},  hours_ahead),
    

    Best regards!

    0 讨论(0)
  • 2021-01-16 10:53

    From chapter 3 of the django book:

    Now that we've designated a wildcard for the URL, we need a way of passing that wildcard data to the view function, so that we can use a single view function for any arbitrary hour offset. We do this by placing parentheses around the data in the URLpattern that we want to save. In the case of our example, we want to save whatever number was entered in the URL, so let's put parentheses around the \d{1,2}, like this:

    (r'^time/plus/(\d{1,2})/$', hours_ahead),
    

    If you're familiar with regular expressions, you'll be right at home here; we're using parentheses to capture data from the matched text.

    0 讨论(0)
  • 2021-01-16 10:59

    I am not sure I understand your question clearly. Here is my shot at answering based on what I understood.

    Adding a named regex group to your URL configuration should help:

    (r'^plus/(?P<offset>\d{1,2})/$', hours_ahead),
    

    This will let you keep the existing view:

    def hours_ahead(request, offset):
        ...
    
    0 讨论(0)
  • 2021-01-16 11:12

    You could use Named groups in the regex

    (r'^plus/(?P<offset>\d{1,2})/$', hours_ahead),
    
    0 讨论(0)
提交回复
热议问题