How to resolve "NoReverseMatch" Error in Django? - python

So I'm trying to create a table of hosts, and as one of the fields of that table include a clickable link to an update page. Which will pass the host_id to the update page. I was hoping someone could tell me what I'm doing wrong with regards to passing the correct parameter to upate/<host_id>. As I'm not quite sure as to how to fix the issue and make it so I can direct people via a clickable button in the table rendered to the appropriate update page. When I attempt to render the page with that added in I'm getting the following error:
NoReverseMatch at /website/home/
Reverse for 'update' with arguments '(1,)' not found. 1 pattern(s) tried: ['website/update/<host_id>']
Request Method: GET
Request URL: http://127.0.0.1:8000/website/home/
Django Version: 4.0.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'update' with arguments '(1,)' not found. 1 pattern(s) tried: ['website/update/<host_id>']
It is also spiecificlly pointing to the following line of code as the issue:
<td><a href="{% url 'update' beacon.host_id %}"</a>Issue Command</td>
This line is found in the following HTML segment.
Relevant HTML Section
{% for beacon in hosts %}
<tr>
<td>{{ beacon.host_id }}</td>
<td>{{ beacon.hostname }}</td>
<td>{{ beacon.internalIp }}</td>
<td>{{ beacon.externalIp }}</td>
<td>{{ beacon.current_user }}</td>
<td>{{ beacon.os }}</td>
<td>{{ beacon.admin }}</td>
<td><a href="{% url 'update' beacon.host_id %}"</a>Issue Command</td>
</tr>
{% endfor %}
My urls.py section looks like the following.
urls.py
urlpatterns = [
re_path('home/', views.home),
re_path('host-detailed', views.host_detailed),
re_path('update/<host_id>', views.update, name='update'),
]
Relevant Models.py
class Command_Node(models.Model):
host_id = models.ForeignKey(Beacon, on_delete=models.CASCADE)
current_commands = models.CharField(
choices=CHOICES, max_length=50, null=True)
def __str__(self):
return str(self.host_id)
Relevant Views.py
def home(request):
hosts = Beacon.objects.all()
return render (request, 'home.html', {'hosts':hosts})
def host_detailed(request):
return render (request, 'hosts-detailed.html')
def update(request, host_id):
host_id = Command_Node.objects.get(pk=host_id)
form = Command_Node(request.POST or None, instance=host_id)
if form.is_valid():
form.save()
return redirect('home.html')
return render (request, 'update.html', {'host_id':host_id,'form':form})

Try something like this:
Urls:
path('update/<int:pk>',views.update,name='update'),
Template
href="{% url 'update' pk = beacon.host_id %}"
As the other comment also mentioned, I don't think re_path is the way to go
How to pass an id to a view as an argument in Django?

Related

django.core.exceptions.ImproperlyConfigured: uses parameter name 'order.id' which isn't a valid Python identifier

when i'm running the command python manage.py runserver i'm getting an error:
django.core.exceptions.ImproperlyConfigured: URL route 'order_detail/<int:order.id>/' uses parameter name 'order.id' which isn't a valid Python identifier.
views.py
def order_detail(request, order_id):
if request.user.is_authenticated:
email = str(request.user.email)
order = Order.objects.get(id=order_id, emailAddress=email)
order_items = OrderItem.objects.filter(order=order)
return render(request, 'store/order_detail.html', {'order': order, 'order_items': order_items})
urls.py
urlpatterns = [
path('', views.home, name='home')
path('order/<int:order.id>/', views.order_detail, name='order_detail'),
]
template file detail.html
{% for order in order_details %}
<tr>
<td>{{ order.id }}</td>
<td>{{ order.created|date:"d M Y" }}</td>
<td>{{ order.total }}</td>
<td><i class="fas fa-check"></i> Complete</td>
<td>View Order</td>
</tr>
{% endfor %}
order.id is not a valid python identifier, and thus not valid as parameter for route. ., - among others are not accepted characters in python identifiers.
it should be order_id as it's defined in your view function order_detail(request, order_id)
change this route
path('order/<int:order.id>/', views.order_detail, name='order_detail'),
to
path('order/<int:order_id>/', views.order_detail, name='order_detail'),
and in your template it should be
<td>View Order</td>
You can simply change your path from this:
path('order/int:order.id/', views.order_detail, name='order_detail')
To this:
path('order/int:order.id', views.order_detail, name='order_detail')

Trying to implement HTML Template into first Django project. Movies not showing

I am following along an online Python tutorial and I am have to create an HTML template in which creates a table for the end user to see the movies in the inventory. I have followed the teachers instructions step-by-by step but when I refresh the browser page, it only shows the class attributes that I listed in the HTML. The code that I wrote is below:
index.html file:
<table class="table">
<thead>
<tr>
<th>Title</th>
<th>Genre</th>
<th>Stock</th>
<th>Daily Rate</th>
</tr>
</thead>
<tbody>
{% for movie in movies %}
<tr>
<td>{{ movie.title }}</td>
<td>{{ movie.genre }}</td>
<td>{{ movie.number_in_stock }}</td>
<td>{{ movie.daily_rate }}</td>
</tr>
{% endfor %}
</tbody>
</table>
and the views.py file:
from django.http import HttpResponse
from django.shortcuts import render
from .models import Movie
def index(request):
movies = Movie.objects.all()
return render(request, 'index.html', {' movies': movies})
Here is what results on my web browser:
enter image description here
If someone knows why this is not working, any help would be awesome!
You seem to have a space where you are passing the context:
return render(request, 'index.html', {' movies': movies})
You need to replace ' movies' with 'movies', otherwise the variable will not be available with the correct name while rendering the template.
As the other user #le.chris mentioned, you seem to have a space where you are passing the context.
This would be the right context : return render(request, 'index.html', {' movies': movies}).
However, in your views file, I highly suggest having Class-based views, start by importing the ListView in this case and create a post_list.html or specify a template_name and since you are using movies as your context object, you also need to specify that in the context_object_name attribute. Maybe like this :
class MovieListView(ListView):
model = Movie
template_name = 'appname/index.html' #appname is the name of your app
context_object_name = 'movies'
ordering = # optional
paginate_by = 3
in your urls.py file of the app :
path('', MovieListView.as_view(), name='movie-index') #adjust the name as you please

Retrieve data from database without using extra page

In my 'django' project, I need to retrieve / insert data from multiple tables of my (mysql)database. However because of the code I used, I had to use an extra .html page for each table operation. I want to be able to access multiple tables on a single html page. In order to better explain the situation, I write the relevant codes of the project below.
Project/views.py
def home_view(request, *args, **kwargs):
print(args, kwargs)
print(request.user)
return render(request, "home.html", {})
#login_required()
def admin_view(request, *args, **kwargs):
print(args, kwargs)
print(request.user)
return render(request, "adminPage.html", {})
#login_required()
def doctor_view(request):
return render(request, 'doctorPage.html', {'doctors': doctor_view()})
appointments/views.py
from django.views.generic import DetailView, ListView
class list_of_appointments(ListView):
model = Appointment
template_name = 'appointments/appointment_list.html'
class list_of_patients(ListView):
model = Patient
template_name = 'appointments/patient_list.html'
appointments/urls.py
urlpatterns=[
url(r'^appointment_list/$', list_of_appointments.as_view(), name='list1'),
url(r'^patient_list/$', list_of_patients.as_view(), name='list2')
]
So, in order to access the operations related to the tables, I have to use the following url code.
<a href={% url 'appointments:list2' %}>
Therefore, I can create a second html file and extract the data I want to extract from the database with this method.
{% for appointment in object_list %}
<tr>
<td>{{ appointment.patient.name }}</td>
<td>{{ appointment.doctor.name }}</td>
<td>{{ appointment.Date }}</td>
<td>{{ appointment.time }}</td>
<td>{{ appointment.province }}</td>
<td><a href="#">
<button type="button" class="btn btn-default"><span class="glyphicon glyphicon-pencil"
aria-hidden="true"></span>Edit
</button>
</a></td>
</tr>
{% endfor %}
But I want to do this database interaction on an existing html link (eg adminPage) without going to another link. Nowhere could I find out how to do this, can you help me? Thank you all!
If you want pass more than one model to ListView, you can override get_context_data method of MultipleObjectTemplateResponseMixin. But be carefull, it should be a QuerySet object. The example look like this:
views.py
from django.views.generic.list import ListView
from .models import FirstModel, SecondModel, ThirdModel
class MyListView(ListView):
template_name = 'my_app/what-ever.html'
model = Article
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['my_first_model'] = FirstModel.objects.all()
context['my_second_model'] = SecondModel.objects.all()
context['my_third_model'] = ThirdModel.objects.all()
return context
what-ever.html
{% for object in my_first_model %}
<h1>{{ object.title }}</h1>
<p>{{ object.pk }}</p>
{% endfor %}
You can find more information here.

Delete user directly from html template

I want to create a management page where an admin can delete users. I have succesfully made it list created users, but now i'm struggeling with how to create a deleteView to delete the user entirely from my django project.
Views.py
def index(request):
users = User.objects.all()
return render(request, 'EditUser.html',{'userlist':users})
def deletefunction(request,User =None):
object = User.objects.get(id=User)
object.delete()
return render(request,'EditUser.html')
Project urls.py
from edit_user.views import deletefunction
urlpatterns = [
path('admin/', admin.site.urls),
path('management', include('management.urls')),
path('management/create', include('signup.urls')),
path('management/edit', include('edit_user.urls')),
path('^delete/(?P<User>[0-9]+)/$', deletefunction, name='delete_view'),
]
HTML code
<div class="container">
{% for item in userlist %}
<tr>
<td>{{ item.username }}</td>delete
</tr>
{% endfor %}
</div>
As of right now when i'm trying to load my page i'm receiving this exception.
Reverse for 'deletefunction' not found. 'deletefunction' is not a
valid view function or pattern name.
def deletefunction(request, user_id):
object = User.objects.get(id=user_id)
object.delete()
users = User.objects.all()
return render(request,'EditUser.html', {'userlist': users})
and
<div class="container">
{% for item in userlist %}
<tr>
<td>{{ item.username }}</td>delete
</tr>
{% endfor %}
</div>
I think you should delete EditUser in href. Because you url in project urls.py(not EditUser urls ). So django looks EditUser app_name but they cant find.
Also you had not determineted 'User'.And you url name "delete_view" but you send view name.Can you change like this?Maybe work.
<td>{{ item.username }}</td>delete

Does not exist. No exception supplied error

I have the following class based view.
class AllPluginsView(ListView):
queryset = get_models(get_app('plugins'))
template_name="console/plugins/plugins.html"
context_object_name = "objects"
And following template,
{% for object in objects %}
<tr>
{% if object %}
<td>{{ object }}</td>
{% endif %}
</tr>
{% endfor %}
When I ask for the page, i get DoesNotExist at /path/to/plugins
No exception supplied. error. Any ideas ?
urlpatterns = patterns('',
url(r'^$', AllPluginsView.as_view(),name='all-plugins'),
)
Perhaps it's an import order thing? Try using get_queryset instead.
class AllPluginsView(ListView):
template_name="console/plugins/plugins.html"
context_object_name = "objects"
def get_queryset(self):
return get_models(get_app('plugins'))

Categories

Resources