【问题标题】:Django No Reverse Match Error - Nothing is workingDjango没有反向匹配错误 - 没有任何工作
【发布时间】:2022-02-11 12:00:04
【问题描述】:

当呈现一个新页面时,该新页面上的 html 表单操作正在阻止页面被呈现......即使它与正在呈现的页面本身无关(如果我删除那一行 HTML 代码,页面加载得很好)。我一直在努力解决这个问题超过 3 天,尝试了数百种可能的解决方案,但没有任何效果。请帮忙

这是错误:

NoReverseMatch at /newgallery/rodneyadmin
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P<username>[^/]+)/(?P<new_gallery>[0-9]+)\\Z']
Request Method: GET
Request URL:    http://127.0.0.1:8000/newgallery/rodneyadmin
Django Version: 4.0
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P<username>[^/]+)/(?P<new_gallery>[0-9]+)\\Z']
Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/urls/resolvers.py, line 729, in _reverse_with_prefix
Python Executable:  /Library/Frameworks/Python.framework/Versions/3.9/bin/python3
Python Version: 3.9.7
Python Path:    
['/Users/rodneyrussell/Desktop/github/Capstone/Capstone',
 '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip',
 '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9',
 '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload',
 '/Users/rodneyrussell/Library/Python/3.9/lib/python/site-packages',
 '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages']
Server time:    Thu, 10 Feb 2022 16:41:21 -0500
Error during template rendering

In template /Users/rodneyrussell/Desktop/github/Capstone/Capstone/templates/galleries/newgallery.html, error at line 21
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P<username>[^/]+)/(?P<new_gallery>[0-9]+)\\Z']
11        Create new gallery
12      </h1>
13    </div>
14  </div>
15  
16  
17  <div class="row mb-3 d-flex justify-content-center">
18    
19      <div class="col-lg-4 col-med-8 col-sm-8 text-primary" style="height: fit-content;">
20  
21        <form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'>
22       
23          {% csrf_token %}
24  
25  
26          <div class="form-group mb-5">
27            <label style="margin-right: 20px;">Public Gallery</label>
28            {{form.public_gallery}}
29        </div>
30      
31          <div class="form-group mb-5">

这是被突出显示为错误原因的代码行(表单操作):

<form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'>

Views.py:

@login_required
def newgallery(request, username):

    if request.method == 'GET':
            
        form = NewGalleryForm
        
        context = {
        'form': form,
        'username': username,
        }

        return render(request, 'galleries/newgallery.html', context)

def editgallery(request, username):

    if request.method == "POST":
    
        form = NewGalleryForm(request.POST)

        if form.is_valid():

            new_gallery = form.save(commit = False)
            ## connect the new gallery with the user (foreign key)
            new_gallery.user = request.user        
            new_gallery.save()
            url = "https://api.opensea.io/api/v1/assets?order_direction=desc&offset=0&limit=5"

            params={'owner': new_gallery.wallett_address}
            headers = {
                "Accept": "application/json",
                "X-API-KEY": ""
            }
            response = requests.request("GET", url, headers=headers, params=params)
            response = response.json()["assets"]

            list_of_nfts =  []
            for dictionary in response:
                token_id = dictionary["token_id"]
                token_address = dictionary["asset_contract"]["address"]
                contract_address = 'https://api.opensea.io/api/v1/asset/' + token_address + '/' + token_id + '/'
                name = dictionary["name"]
                if len(name) > 50:
                    name = (name[:50] + '...')
                nft_created_date = dictionary["asset_contract"]["created_date"]
                nft_created_date = nft_created_date[:10]
                nft_created_date = datetime.strptime(nft_created_date, '%Y-%m-%d').strftime('%m/%d/%Y')
                image = dictionary["image_url"]
                description = dictionary["description"]
                if description is not None and '*' in description:
                    head, sep, tail = description.partition('*')
                    description = head
                if description is not None and len(description) > 50:
                    description = (description[:150] + '...')
                if isinstance(description, str) != True:
                    description = 'No description provided'
                link = dictionary["permalink"]
                nft_dict = {
                'contract_address': contract_address,
                'name': name,
                'image': image,
                'description': description,
                'link': link,
                'nft_created_date': nft_created_date,
                }
                list_of_nfts.append(nft_dict)
        

            context = {
            'new_gallery': new_gallery,
            'list_of_nfts': list_of_nfts,
            'raw_nft_data': json.dumps(list_of_nfts),
            'new_gallery_name': new_gallery.gallery_name,
            'user': new_gallery.user,
            username:username,
            }
 
          
            return render(request, 'galleries/editgallery.html', context)

新画廊 HTML(用户输入有关他或她正在创建的新画廊的基本信息的页面...提交此表单后,用户将被带到一个页面,他们可以在其中编辑刚刚创建的画廊(通过编辑,我的意思是向该画廊添加新的 NFT):


<div class="row mb-3">
  <div class="col-lg-12 col-sm-12 text-primary  d-flex justify-content-center align-items-center">
    <h1
      class="homepagetitle mt-4 mb-5"
      style="font-size: 2.4rem; color: rgb(231, 114, 208)"
    >
      Create new gallery
    </h1>
  </div>
</div>


<div class="row mb-3 d-flex justify-content-center">
  
    <div class="col-lg-4 col-med-8 col-sm-8 text-primary" style="height: fit-content;">

      <form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'>
     
        {% csrf_token %}


        <div class="form-group mb-5">
          <label style="margin-right: 20px;">Public Gallery</label>
          {{form.public_gallery}}
      </div>
    
        <div class="form-group mb-5">
            <label>Gallery Name </label>
            {{form.gallery_name}}
        </div>

        <div class="form-group mb-5">

          <label>Wallett Address</label>   
          
          <span class="hovertext" style="color: rgb(231, 114, 208); font-weight: normal;" data-hover="You will be adding NFT's from this wallet. Max wallet size: 50 NFT's">?</span>
          {{form.wallett_address}}
      </div>

        <div class="form-group mb-5">
            <label style="margin-right: 20px;">Category </label>
            {{form.gallery_category}}
        </div>
  

       
          <button
          type="submit"
          class="btn btn-dark mt-4 mb-4"
          
          style="
          font-size: 1.1rem;
            height: 50px;
            width:fit-content;
          "
        >
          Add NFT's &nbsp <i class="far fa-arrow-alt-circle-right"></i>
        </button>
      


    </form>



</div>

</div>

用户配置文件 HTML(用户单击 a 标签以将其带到新图库 HTML(我在上面列出的其他 HTML)的页面。那是代码中断并给出该错误的时候。其中的 url标签是 href="{% url 'gallery_app:newgallery' user.username %}":

<h1 class="homepagetitle mt-4 mb-5 d-flex justify-content-center align-items-center" style="font-size: 2.4rem; color: rgb(231, 114, 208);">
  Hello&nbsp
  <span style="font-size: 2.4rem; color: rgb(231, 114, 208);"
    >{{user.username}}&nbsp<i class="far fa-hand-paper" style="font-size: 2.4rem; color: rgb(231, 114, 208);"></i></span
  >
</h1>
{% endif %}


<div class="row col-12">
  <div class="col-lg-6">
    <div class="pt-3 profile-image">
      <img
        src="{% static user.avatar.url %}"
        alt="{{user.username}}'s avatar"
        class="rounded-circle shadow"
        height="300"
        width="275"
      />
    </div>
    {% if request.user == user %}
    <span>
      <div class="editicon">
        <a
          href="{% url 'users_app:update' user.username %}"
          style="
            color: rgb(226, 81, 197);
            -webkit-text-stroke: 1px black;
            text-decoration: none;
          "
        >
          <i class="fas fa-user-edit"></i>
        </a>
      </div>
    </span>
    {% endif %}

    <!-- 'users_app:update' user.username -->

    <table class="table profile-margin">
      <tbody>
        {% if request.user == user %}
        <tr>
          <th scope="row"></th>
          <td>Name:</td>
          <td>{{user.first_name}} {{user.last_name}}</td>
        </tr>

        <tr>
          <th scope="row"></th>
          <td>Email:</td>
          <td>{{user.email}}</td>
        </tr>
        {% endif %}
        <tr>
          <th scope="row"></th>
          <td>Username:</td>
          <td>{{user.username}}</td>
        </tr>

        <tr>
          <th scope="row"></th>
          <td>Profile created:</td>
          <td>{{user.date_joined|date}}</td>
        </tr>

        <tr>
          <th scope="row"></th>
          <td>Galleries:</td>
          <td>0</td>
        </tr>

        <tr>
          <th scope="row"></th>
          <td>Followers:</td>
          <td>0</td>
        </tr>

        <tr>
          <th scope="row"></th>
          <td>Following:</td>
          <td>0</td>
        </tr>
      </tbody>
    </table>
  </div>

  <div class="col-lg-6">
    {% if request.user.is_authenticated %}


      <h3 class=" d-flex homepagetitle" style="justify-content:center; margin-top: 30px; margin-bottom: 0px; padding:10px; height: 75px; font-size: 2.2rem; color: rgb(231, 114, 208);">
        <i><a class="homepagetitle far fa-plus-square" href="{% url 'gallery_app:newgallery' user.username %}" style="text-decoration: none; font-size: 2.2rem; color: rgb(231, 114, 208); position:relative; left: -70px; font-size: 2rem;"></i></a>
           Your Galleries:
      </h3>


   

    {% else %}
    <h3 class=" d-flex justify-content-center homepagetitle" style="margin-top: 30px; margin-bottom: 0px; padding:10px; height: 75px; font-size: 2.2rem; color: rgb(231, 114, 208);">
        {{user.username}}'s Galleries:
    </h3>

    {% endif %}

    

    <div class='user-galleries d-flex justify-content-center'  style="background-color: rgb(247, 229, 243); border-radius: 8px;">

      <div class="gallery-posts py-3">
        <table class="table profile-margin" style="color:rgb(231, 114, 208); font-weight: bolder;">
          <tbody>


    {% for gallery in user.newgallery.all %}

    

    <tr>
      <th scope="row"></th>
      <td>{{ gallery.gallery_name }}</td>
      <td>NFT's: 0</td>
    </tr>
        
    {% endfor %}

         
      </tbody>
        </table>
      </div>

      </div>
        
    </div>



  </div>
</div>

网址.py:

app_name = 'gallery_app'


urlpatterns = [
    path('newgallery/<str:username>', views.newgallery, name='newgallery'),
    path('editgallery/<str:username>/<int:gallery_id>', views.editgallery, name='editgallery'),
    path('galleryview/<str:username>/<int:gallery_id>', views.galleryview, name='galleryview'),
]

【问题讨论】:

    标签: python html django jinja2


    【解决方案1】:

    渲染 html 模板时,url 参数 new_gallery.id 似乎为空。

    更新:因此从视图 newgallery 调用模板。

    在您的原始代码中,有两点需要更改:

    1. 要实例化表单,请在NewGalleryForm后添加()。如果没有你,只需交出课程链接即可。
    2. 在此视图/模板中,您还没有 newgallery 的实例(只是表单)。所以你不能使用newgaller.id。在 newgallery 中实现一个 POST 分支以保存它并从表单操作中删除 newgallery.id 并将操作指向新画廊视图。
    3. 保存后,您有一个带有 id 的 newgallery 实例,如果需要在上下文中使用 newgallery,您可以调用编辑视图
    def newgallery(request, username):
        if request.method == 'POST':
           # save newgallery here
    
        if request.method == 'GET':
                
            form = NewGalleryForm()
            
            context = {
            'form': form,
            'username': username,
            }
    
            return render(request, 'galleries/newgallery.html', context)
    
    <form action="{% url 'gallery_app:newgallery' user.username %} " style .... >
    

    【讨论】:

    • 没错。我不明白为什么它是空的,因为它是在那个editgallery视图的上下文中传递的
    • 看起来不像您从视图编辑库呈现该页面。如果是这样,您应该得到一个错误,因为 editgallery 的路径语句提供了一个 gallery_id,但视图不将其作为参数。你实际上是在打电话给galleryview吗?你没有提供那个观点。你能发布完整的错误信息吗?
    • 我编辑了原始帖子以包含您要求的所有信息
    • 它的一个变体帮助修复了错误,唷!谢谢!
    【解决方案2】:

    您需要将图库作为上下文传递到具有编辑表单的视图中。我在您发布的视图中没有看到您有详细视图,但我确实看到了详细视图 url。所以我假设您将编辑表单传递给您的创建视图?该视图不会返回以 new_gallery 作为上下文变量的上下文。我会为您的画廊创建一个详细视图,并将编辑表单、用户和画廊作为上下文传递给模板。

    Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found.
    

    新上下文

    def galleryview(request, username, gallery_id):
        # Logic
        gallery = get_object_or_404(Gallery, pk=gallery_id)
        context = {
        'form': form,
        'username': username,
        'new_gallery': gallery,
        }
        # return an html response with context
    

    另外,当你实例化一个未绑定的表单时,你应该在它之后添加括号。

    form = NewGalleryForm()
    

    【讨论】:

    • 非常感谢您的回复。也许我错过了你在说什么,但你建议的修复似乎并没有解决问题:/
    • 您在新图库页面上有指向编辑图库视图的链接,这毫无意义。没有画廊上下文被传递给该模板,因此 new_gallery.id 为空。另外,为什么用户会去新的画廊页面来编辑现有的画廊。您可能需要一个全新的详细视图/模板来显示各个画廊(您已经有一个网址)。在该视图中,您应该将图库作为上下文传递给模板,然后在该页面上链接到您的编辑图库视图。从新图库页面中删除编辑图库的链接。
    猜你喜欢
    • 1970-01-01
    • 2012-10-21
    • 2017-04-25
    • 1970-01-01
    • 2013-01-04
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多