Home > Software engineering >  Django No Reverse Match Error - Nothing is working
Django No Reverse Match Error - Nothing is working

Time:02-11

When rendering a new page, the html form action on that new page is stopping the page from being rendered... even though it has nothing to do with the page itself being rendered (if I remove that one line of HTML code, the page loads just fine). I've been working on solving this problem for over 3 days, tried hundreds of possible solutions, nothing works. Please help

This is the error:

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 >
18    
19      <div  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 >
27            <label style="margin-right: 20px;">Public Gallery</label>
28            {{form.public_gallery}}
29        </div>
30      
31          <div >

This is the line of code being highlighted as cause for error (form action):

<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)

New Gallery HTML (page where user enters basic information regarding New Gallery that he or she is creating... when this form is submitted, the user is brought to a page where they can edit the gallery that was just created (by edit, I mean add new NFT's to that gallery):


<div >
  <div >
    <h1
      
      style="font-size: 2.4rem; color: rgb(231, 114, 208)"
    >
      Create new gallery
    </h1>
  </div>
</div>


<div >
  
    <div  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 >
          <label style="margin-right: 20px;">Public Gallery</label>
          {{form.public_gallery}}
      </div>
    
        <div >
            <label>Gallery Name </label>
            {{form.gallery_name}}
        </div>

        <div >

          <label>Wallett Address</label>   
          
          <span  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 >
            <label style="margin-right: 20px;">Category </label>
            {{form.gallery_category}}
        </div>
  

       
          <button
          type="submit"
          
          
          style="
          font-size: 1.1rem;
            height: 50px;
            width:fit-content;
          "
        >
          Add NFT's &nbsp <i ></i>
        </button>
      


    </form>



</div>

</div>

User Profile HTML (page where user clicks on an a tag to bring them to the the New Gallery HTML (the other HTML I have listed above). That is when the code breaks and gives that error. The url in that a tag is href="{% url 'gallery_app:newgallery' user.username %}":

<h1  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  style="font-size: 2.4rem; color: rgb(231, 114, 208);"></i></span
  >
</h1>
{% endif %}


<div >
  <div >
    <div >
      <img
        src="{% static user.avatar.url %}"
        alt="{{user.username}}'s avatar"
        
        height="300"
        width="275"
      />
    </div>
    {% if request.user == user %}
    <span>
      <div >
        <a
          href="{% url 'users_app:update' user.username %}"
          style="
            color: rgb(226, 81, 197);
            -webkit-text-stroke: 1px black;
            text-decoration: none;
          "
        >
          <i ></i>
        </a>
      </div>
    </span>
    {% endif %}

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

    <table >
      <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 >
    {% if request.user.is_authenticated %}


      <h3  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  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  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 >
        <table  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'),
]

CodePudding user response:

It looks like the url argument new_gallery.id is empty when you render the html template

CodePudding user response:

You need to pass the gallery as context into the view that has the edit form. I don't see in the views that you posted that you have a detail view but I do see a detail view url. So I'm assuming you're passing the edit form to your create view instead? That view doesn't return a context with new_gallery as a context variable. I would create a detail view for your gallery instead and pass the edit form, user and gallery as context to the template.

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

New context

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

Also, when you instantiate an unbound form you should add parenthesis after it.

form = NewGalleryForm()
  • Related