Передать переменную в URL из views.py

#python #django #django-views

#python #django #django-представления

Вопрос:

Обычно при передаче переменной в шаблонах вы бы сделали это:

 {% url 'sw_app:test_editor' code=mycode %}
  

Однако, как я могу сделать то же самое в моем views.py ?

Я пытался:

 def go_to_test_editor(code):
    return reverse('sw_app:test_editor', code)
  

Говорит:

  No module named 'vQ6SMpo'
 # 'vQ6SMpo' is the code passed
  

И:

 def go_to_test_editor(code):
    return reverse('sw_app:test_editor',code=code)
  

Говорит:

 reverse() got an unexpected keyword argument 'code'
  

Я довольно новичок в Django. Большое спасибо!

Ошибка обратной трассировки:

 Traceback (most recent call last):
  File "/Users/myuser/opt/anaconda3/envs/MyDjangoEnv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/Users/myuser/opt/anaconda3/envs/MyDjangoEnv/lib/python3.8/site-packages/django/utils/deprecation.py", line 116, in __call__
    response = self.process_response(request, response)
  File "/Users/myuser/opt/anaconda3/envs/MyDjangoEnv/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 26, in process_response
    if response.get('X-Frame-Options') is not None:
AttributeError: 'str' object has no attribute 'get'
  

Ответ №1:

Вы должны перейти args к reverse следующему.

 reverse('sw_app:test_editor', args=[code])
  

Чтобы узнать больше, посетите документы.

Комментарии:

1. Он вернул 'str' object has no attribute 'get'

2. Какой путь в urls.py подать на это заявление?

3. path('test_editor/<str:code>', views.test_editor, name = 'test_editor'),

4. Это должно просто работать, что такое отслеживание ошибки?

5. Ошибка не для reverse , она связана с views.test_editor возвращаемым ответом. Можете ли вы добавить определение views.test_editor too .