Django 没有反向匹配错误 - 没有任何效果

Django No Reverse Match Error - Nothing is working

呈现新页面时,新页面上的 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>

Urls.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'),
]

当您渲染 html 模板时,url 参数 new_gallery.id 似乎是空的。

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

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

  1. 要实例化表单,请在 NewGalleryForm 之后添加 ()。没有你就把一个link交给class.
  2. 在此 view/template 中,您还没有 newgallery 的实例(只有表单)。所以你不能使用newgaller.id。在 newgallery 中实现一个 POST 分支以保存它并从表单操作中删除 newgallery.id 并将该操作指向 newgallery 视图。
  3. 保存后你有一个带有 id 的新画廊实例,如果你需要在上下文中使用新画廊,你可以调用编辑视图
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 .... >

您需要将图库作为上下文传递到具有编辑表单的视图中。我在您发布的视图中没有看到您有详细视图,但我确实看到了详细视图 url。所以我假设您将编辑表单传递给您的创建视图?该视图不 return 具有 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()