-2

My python code keeps returning the following error:

Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/geo_gas/edit_sale/ Raised by: geo_gas.views.edit_sale No Sales matches the given query.

class Sales(models.Model):
        gas_qty = models.CharField(max_length=20)
        amount = models.CharField(max_length=20)
        date_added = models.DateTimeField(auto_now_add=True)

        def __str__(self):
        """Return a string representation of the model."""
            return self.gas_qty

        class Meta:
            verbose_name_plural = 'Sales'

View.py

    def edit_sale(request):
        """Edit an existing sales record."""
        entry = get_object_or_404(Sales, pk=1)

        if request.method != 'POST':
            form = SalesForm(instance=entry)
        else:
            form = SalesForm(instance=entry, data=request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(reverse('geo_gas:sales'))

        context = {'entry': entry, 'form': form}
        return render(request, 'ht/edit_sale.html', context)

Urls.py

    .......

    # Page for editing a sale entry
        path('edit_sale/', views.edit_sale, name='edit_sale'),

    .......

ht/templates/ht/edit_sale.html

Edit entry:

             <form action="{% url 'geo_gas:edit_entry' %}" method='post'>

            {% csrf_token %}

            {{ form.as_p }}

        <button name="submit">save changes</button>

         </form>

I have not been able to identify what part of the code is causing the error to occur.

sebasp
  • 11
  • 3
Chinedu Obi
  • 33
  • 1
  • 2
  • 3
  • did you add the namespace `geo_gas` ? – YGouddi Jan 25 '18 at 14:26
  • Can you share the detailed version of `urls.py`? – dvnguyen Jan 25 '18 at 14:27
  • post your complete `urls.py`. Where this url `'geo_gas:sales'` is defined? – Arpit Solanki Jan 25 '18 at 14:28
  • Try different id, that exists in your db `entry = get_object_or_404(Sales, pk=1)` instead of one. i guess you have deleted some of instance – Sumeet Kumar Jan 25 '18 at 14:29
  • You are hardcoding `pk=1` in your view, so you're going to get an error if that doesn't exist. I showed you how to add the primary key to the url and view in your question yesterday - https://stackoverflow.com/a/48426092/113962 – Alasdair Jan 25 '18 at 14:32
  • you have to make your url dynamic, by passing a parameter and calling it in your view, ex: path('articles/(?P\w+)/', views.special_case_2003), and in your view: def edit_sale(request, pk): – alex Jan 25 '18 at 14:34
  • @NitaAlexandru you shouldn't use regexes with `path()`. – Alasdair Jan 25 '18 at 14:51
  • path('edit_sale/(?P\w+)/ is returning- - NoReverseMatch at /geo_gas/sale/ – Chinedu Obi Jan 25 '18 at 14:55
  • @Alasdair now i've seen their example – alex Jan 25 '18 at 15:31
  • @ChineduObi don't use regexes like `\w+` in path. As I said, I already wrote how to change your code in my answer yesterday - https://stackoverflow.com/a/48426092/113962 – Alasdair Jan 25 '18 at 15:33
  • @Alasdair, I used the same syntax on other functions, which returns a value per query . – Chinedu Obi Jan 25 '18 at 15:38
  • Trust me, using `\w+` inside `path()` is incorrect - https://stackoverflow.com/questions/47334486/#47334557 – Alasdair Jan 25 '18 at 15:40

1 Answers1

1

The error is saying that no Sales instance with pk=1 exists, as the error is likely thrown by get_object_or_404(Sales, pk=1). So you might want to check if that's really the case.

You can try checking the pk of your instance by doing Sales.objects.first().pk to see.

Update: How to make it dynamic

Before going into that, it might be useful to understand what RESTful API endpoints are like. But briefly in this context you might want to have something like this

# urls.py
path('sale/', views.list_sale, name='list_sale'),
path('sale/<int:pk>/', views.retrieve_update_delete_sale, name='retrieve_update_delete_sale')  # names of the view can be whatever you want

What happens here is that the pk argument is passed from the URL (<int:pk>) to the view as an argument in the function-based view.

Accessing the arguments passed from URLs in your view

def retrieve_update_delete_sale(request, pk):  # <-- you will be able to access it here
    """Edit an existing sales record."""
    entry = get_object_or_404(Sales, pk=pk)  # this is now dynamic!

    if request.method != 'POST':
        form = SalesForm(instance=entry)
    else:
        form = SalesForm(instance=entry, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('geo_gas:sales'))

    context = {'entry': entry, 'form': form}
    return render(request, 'ht/edit_sale.html', context)

So now if you want to access the Sale instance with pk=1, all you need to do is visit the url with /sale/1/, and so on.

Thomas Jiang
  • 1,303
  • 11
  • 16
  • Thanks, @Thomas Jiang. How can I make dynamic? – Chinedu Obi Jan 25 '18 at 19:55
  • Updated the answer – Thomas Jiang Jan 26 '18 at 01:47
  • Hi @Thomas Jiang, I implemented as suggested. please check urls.py path('sale//', views.retrieve_update_delete_sale, name='retrieve_update_delete_sale'), html -->
    Reverse for 'retrieve_update_delete_sale' with no arguments not found. 1 pattern(s) tried: ['geo_gas\\/sale\\/(?P[0-9]+)\\/$']
    – Chinedu Obi Jan 27 '18 at 16:46