【问题标题】:Django Get full url path from app_nameDjango 从 app_name 获取完整的 url 路径
【发布时间】:2022-01-25 10:20:57
【问题描述】:

有没有办法从 app_name 获取完整的 url?像 reverse('myapp:bio') 在类 ItemForm(forms.ModelForm) 中

from django.urls import include, path
app_name = 'myapp'

urlpatterns = [
    path('index/', views.index, name='main-view'),
    path('bio/<username>/', views.bio, name='bio'),
]

我正在尝试在 MyForm(ModelForm) 中使用它,但我得到了那个错误

File "D:\Development\SiteDJCentral\.venv\lib\site-packages\django\urls\resolvers.py", line 607, in url_patterns
    raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
django.core.exceptions.ImproperlyConfigured: The included URLconf 'website.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

print( reverse('myapp:bio') )

我尝试调用它的表单

class ItemForm(forms.ModelForm):

relase_date = forms.DateField(required=False, input_formats=settings.DATE_INPUT_FORMATS,  help_text='opzionale formato yyyy-mm-dd')

tags = OdsTaggerMultipleChoiceField( queryset = None, required=True, json_url= HttpRequest.request.build_absolute_uri(reverse('myapp:bio' )) )

【问题讨论】:

  • 我正在尝试在 MyForm(ModelForm) 中使用它,但我收到错误文件“D:\Development\SiteDJCentral\.venv\lib\site-packages\django\urls\resolvers.py ",第 607 行,在 url_patterns 中从 e django.core.exceptions.ImproperlyConfigured 中引发 ImproperlyConfigured(msg.format(name=self.urlconf_name)):包含的 URLconf 'website.urls' 中似乎没有任何模式。如果您在文件中看到有效模式,则问题可能是由循环导入引起的。 print(反向('items:list', args=['Orléans']))
  • 您将表单添加到问题中?
  • 什么是`OdsTaggerMultipleChoiceField,它来自哪里,你能展示它的代码吗?您应该避免在视图或表单类的正文中使用反向链接,在这些情况下应该使用 reverse_lazy docs.djangoproject.com/en/4.0/ref/urlresolvers/#reverse-lazy

标签: django url


【解决方案1】:

简单:

from django.urls import reverse

reverse('main-view') == 'myapp/index/'
reverse('bio', kwargs={'username': UserObject.username}) == 'myapp/bio/<username>/'

【讨论】:

  • 不能在myForm(ModelForm)中使用
  • 你改了问题!为什么在forms 中需要它?网址主要用于viewstemplates
  • 对不起,只是添加细节,bcz reverse 在其他文件中工作正常
  • 现在你没有name='items:list' 的路径,所以不能这样。在reverse 函数中,您必须从path 粘贴一个有效的name。在您的情况下,它只是 main-viewbio
  • 已编辑,你说得对,我的 exeple 代码有一些错误......但是正确的 reverse('myapp:bio') 错误是 HttpRequest.request.build_absolute_uri
猜你喜欢
  • 1970-01-01
  • 2014-04-02
  • 1970-01-01
  • 2011-12-11
  • 2014-12-08
  • 1970-01-01
  • 2010-10-14
  • 2018-08-13
  • 2017-03-16
相关资源
最近更新 更多