【问题标题】:NoReverseMatch at /<url>/<url> 处的 NoReverseMatch
【发布时间】:2015-04-15 01:25:34
【问题描述】:

Django 1.7.0 beta 4
Python 2.7.9

我目前正在尝试使用 Django 的 CBV 来创建模态。我对 ListView 没有任何问题,但是在尝试使用 url 标签调用我的 UpdateView 时我被卡住了。 我收到以下错误:

/dashboard_usuario_list/ 处的 NoReverseMatch
未找到带有参数“(u'test2',)”和关键字参数“{}”的“dashboard_usuario_edit”的反向操作。尝试了 1 种模式:['dashboard_usuario_edit/(?Pd+)/?$']

views.py:

class UserProfileListView(ListView):
    model = UserProfile
    template_name = 'dashboard_usuario_list.html'
    def get_queryset(self):
        return UserProfile.objects.all()

class UserProfileUpdateView(UpdateView):
    model = UserProfile
    form_class = UserProfileForm
    template_name = 'dashboard_usuario_edit.html'

    def dispatch(self, *args, **kwargs):
        self.username = kwargs['username']
        return super(UserProfileUpdateView, self).dispatch(*args, **kwargs)

    def form_valid(self, form):
        """
        If the form is valid, redirect to the supplied URL.
        """
        form.save()
        user_profile = UserProfile.objects.get(username = self.username)
        return HttpResponse(render_to_string('dashboard_usuario.html', {'username':user_profile}))


    def get_context_data(self, **kwargs):
        context = super(UserProfileUpdateView, self).get_context_data(**kwargs)
        return context

url.py:

url(r'^dashboard_usuario_list/', views.UserProfileListView.as_view(), name = 'dashboard_usuario_list'),
url(r'^dashboard_usuario_edit/(?P<username>d+)/?$', views.UserProfileUpdateView.as_view(), name = 'dashboard_usuario_edit'),

dashboard_usuario_list.html:
&lt;a href="{% url 'dashboard_usuario_edit' user.user.username %}"&gt;&lt;/a&gt;

提前致谢!

【问题讨论】:

    标签: django


    【解决方案1】:

    dashboard_usuario_edit 的 url 具有正则表达式模式,只接受整数 \d+username,这是错误的,用户名可以由字母数字字符组成,因此您的模式应该是:

    url(r'^dashboard_usuario_edit/(?P<username>[\w.@+-]+)/?$', views.UserProfileUpdateView.as_view(), name = 'dashboard_usuario_edit'),
    

    【讨论】:

      猜你喜欢
      • 2020-02-23
      • 1970-01-01
      • 2013-09-26
      • 2013-01-19
      • 2015-07-18
      • 2018-12-09
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多