0

所以我試圖做一個簡單的更新配置文件的應用程序但是,當我嘗試訪問更新頁面我必須手動編寫鏈接+在這種情況下的id是2例如'accounts/update/2'否則當我嘗試使用 「{%URL 'edit_user' %}」 我得到這個NoReverseMatch在/

`NoReverseMatch at/

Reverse for 'edit_user' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['accounts/update/(?P<pk>\\d+)/']` 

url.py它不會工作

url(r'^admin/', admin.site.urls), 
url(r'^$', main_views.home, name='home'), 
url(r'^uprofile$', main_views.uprofile, name='uprofile'), 
url(r'^accounts/update/(?P<pk>\d+)/', User_Profile_views.edit_user, name='edit_user'), 
url(r'^accounts/', include('allauth.urls')), 

views.py

@login_required() # only logged in users should access this 
def edit_user(request, pk): 
    # querying the User object with pk from url 
    user = User.objects.get(pk=pk) 

    # prepopulate UserProfileForm with retrieved user values from above. 
    user_form = UserForm(instance=user) 

    # The sorcery begins from here, see explanation below 
    ProfileInlineFormset = inlineformset_factory(User, UserProfile, fields=('website', 'bio', 'phone', 'city', 'country', 'organization')) 
    formset = ProfileInlineFormset(instance=user) 

    if request.user.is_authenticated() and request.user.id == user.id: 
     if request.method == "POST": 
      user_form = UserForm(request.POST, request.FILES, instance=user) 
      formset = ProfileInlineFormset(request.POST, request.FILES, instance=user) 

      if user_form.is_valid(): 
       created_user = user_form.save(commit=False) 
       formset = ProfileInlineFormset(request.POST, request.FILES, instance=created_user) 

       if formset.is_valid(): 
        created_user.save() 
        formset.save() 
        return HttpResponseRedirect('/accounts/profile/') 

     return render(request, "account/account_update.html", { 
      "noodle": pk, 
      "noodle_form": user_form, 
      "formset": formset, 
     }) 
    else: 
     raise PermissionDenied 

HTML表單

<div class="col s12 m8 offset-m2"> 
     <div class="card"> 
     <div class="card-content"> 
     <h2 class="flow-text">Update your information</h2> 
      <form action="." method="POST" class="padding"> 
      {% csrf_token %} {{ noodle_form.as_p }} 
      <div class="divider"></div> 
      {{ formset.management_form }} 
       {{ formset.as_p }} 
      <button type="submit" class="btn-floating btn-large waves-light waves-effect"><i class="large material-icons">done</i></button> 
      <a href="#" onclick="window.history.back(); return false;" title="Cancel" class="btn-floating waves-effect waves-light red"><i class="material-icons">history</i></a> 

     </form> 
     </div> 
    </div> 
</div> 
+0

我沒有看到你在發佈的代碼中的任何地方調用'{%url'edit_user'%}''。 – Marcs

+0

that's True因爲我在Navbar中使用它位於base.html – LeLouch

回答

1

由於錯誤說,edit_user需要一個參數:該用戶的ID進行編輯。您需要通過url標記。

{% url 'edit_user' pk=my_user.pk %} 

或任何您的用戶對象的名稱。

+0

謝謝隊友{%url'edit_user'pk = user.pk%}解決了它 – LeLouch