URL Patterns and Views - python

I have an application which requests data based on certain parameters. I use two functions to handle the requests and then create two objects from the responses. I am able to iterate through each object individually and display the data of a particular object on my webpage, but when I try to use both functions simultaneously, only one function iterates through the object. It is my understanding that this issue has something to do with URL patterns, but I am not as to what the best approach would be. Below you will find my urlpatterns, my functions, and the HTML I use to access the view.
urls.py
urlpatterns = [
path('', views.customer, name='customer'),
path('', views.information, name='information'),
]
views.py
def customer(request):
for i, contact in enumerate(contactObj):
try:
contacts = contactObj
context = {'contacts': contacts}
except KeyError:
print()
return render(request, 'uccx/home.html', context)
def information(request):
for i, ticket in enumerate(ticketObj):
try:
tickets = ticketObj
context = {'tickets': tickets}
except KeyError:
print()
return render(request, 'uccx/home.html', context)
home.html
<tbody>
{% for ticket in tickets %}
<tr class="{% cycle 'row1' 'row2'">
<td> {{ ticket.id }} </td>
<td> {{ ticket.company.name }} </td>
<td> {{ ticket.summary }} </td>
</tr>
{% endfor %}
</tbody>

Your URL patterns should be different for every view. otherwise, it will always call the view which is defined above either you call it by customer or information
So your URL patterns should be
urlpatterns = [
path('customer/', views.customer, name='customer'),
path('information/', views.information, name='information'),
]
UPDATE
You don't have to create separate views for fetching objects from different tables to
show in a webpage
Create a single view and send as many objects in context dictionary.
def table_content(request):
...
# fetch objects here from model
contacts = Contact.objects.all()
tickets = Ticket.objects.all()
# set objects to context dictionary
context = {'contacts': contacts, 'tickets' : tickets}
return render(request, 'uccx/home.html', context)
Now in your template, you can easily loop over tickets and contacts
{% for ticket in tickets %}
<tr>
<td> {{ ticket.id }} </td>
...
</tr>
{% endfor %}
{% for contact in contacts %}
<tr>
<td> {{ contact.id }} </td>
...
</tr>
{% endfor %}

Related

Django Render List of Dictionaries to a template

I have a list of dictionaries with same key information. How can I pass this list of dictionaries to a Django template ?
listdict = [{'product':'specs','price':'12'}, {'product':'shoes','price':'30'}]
When trying to send this list via views file to template it fails with an error indicating that only dictionaries are allowed.
Here is the code from views file
return render(request, 'recordings/extensionrecording.html',listDict)
Here is the html block-
<tbody>
{%for list in listDict%}
{%for elements in list%}
<tr>
<td class="body-item fonts-style display-4">{{elements.product}}</td>
<td class="body-item fonts-style display-4">{{elements.price}}</td>
</tr>
Just pass these as an entry of the dictionary:
return render(request, 'recordings/extensionrecording.html',{'listDict': listDict})
Then in the template, you can render these with:
{%for item in listDict %}
{{ item.product }}
{{ item.price }}
{% endfor %}

Django - how to make a link in an html template open an app and pass a objects value as a parameter

Hello I have an app that displays some database information in a table. Inside of the html template I am making an edit link that I want to open another app(page viewLit) while passing a value to it's view. I have added my code below. My question is I am unsure of how to make this links url and pass the object data located inside circuit.circuitid along with it. I haven't been able to find the right way to code this yet and this is just how I thought that this should be done. If anyone has a better idea I am open to suggestions.
search_custom.html(code for link)
{% for circuit in filter.qs %}
<tr>
<td class="actions">
View
</td>
<td>{{ circuit.circuitid }}</td>
</tr>
{% endfor %}
myapp/myapp/urls.py
urlpatterns = [
path('viewLit/', include('viewLit.urls')),
]
myapp/viewLit/urls.py
urlpatterns=[
path('viewLit/circuitid.id', views.viewLit, name='viewLit'),
]
myapp/viewLit/views.py
def viewLit(request, circuitid):
#display records fields here
return HttpResponse("You are at the viewLit page!")
Have a look at the documentation:
Django documentation
myapp/viewLit/urls.py
urlpatterns=[
path('viewLit/(?P<circuit_id>\w+)', views.viewLit, name='viewLit'),
]
html- template:
search_custom.html(code for link)
{% for circuit in filter.qs %}
<tr>
<td class="actions">
View
</td>
<td>{{ circuit.circuitid }}</td>
</tr>
{% endfor %}

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

Using the slice filter with context data from a Django QuerySet

I am trying to split a list from my model across two columns, using this html code in the template:
< div class ="col-md-6" >
{%for value in object_list %}
<ul>< ahref="/sites/{{value.url}}/">{{value.Site}}</a></ul>
{% endfor %}
I was planning to achieve this with the slice tag to filter the list, e.g.:
{%for value in object_list|slice:"10:20" %}
It does not work however, and I think it might be because I have context data i.e. {{value.Site}}, instead of just {{Site}} for example. This is the corresponding view:
class homeview(ListView):
template_name = 'annual_means/home.html'
def get_queryset(self):
return AnnualMean.objects.values("Site", "url").distinct()
What do I need to do to get the slice to work?
I think, what you need is this:
<table>
<tr>
<th>URL</th>
<th>SITE</th>
</tr>
{% for value in object_list %}
<tr>
<td>{{value.url}}</td>
<td>{{value.Site}}</td>
</tr>
{% endfor %}
</table>
URLs and Sites will be displayed as a table.

Django form field issue with model formset

I'm having an issue with rendering individual form fields in a template. I have a model formset that I'm re-ordering after creation to make displaying a little easier on the template. Nothing too complicated, but rendering the form fields isn't working. You can see in the template where I try and render {{ form.train }}, but nothing shows up in the output. However, the form is definitely there because {{ form.instance.user.name }} works correctly.
I opened up PDB and inspected the form variable that I'm adding into the dictionary, and it says <django.forms.widgets.ScheduleForm object at 0x10c58bc50>. I'm not sure if that helps or not, but I wanted to provide as much info as possible.
The Model Form
class ScheduleForm(ModelForm):
class Meta:
model = models.Schedule
fields = [
'train',
'semi',
'tri_axle',
'flow_boy',
'misc',
'material',
'notes'
]
views.py
formset_fields = ('train','semi','tri_axle','flow_boy','misc','material','notes')
ScheduleFormSet = modelformset_factory(models.Schedule, fields=formset_fields, extra=0)
formset = ScheduleFormSet(queryset=queryset)
# Getting form in the right format
ordered_forms = {}
for form in formset:
# Make sure the job exists on the object
if not form.instance.job.number in ordered_forms:
ordered_forms[form.instance.job.number] = {}
# Make sure the user exists on the object
if not form.instance.user.name in ordered_forms[form.instance.job.number]:
ordered_forms[form.instance.job.number][form.instance.user.name] = []
# Append to correct place.
ordered_forms[form.instance.job.number][form.instance.user.name].append(form)
# Dict will look like
# { 'jobID' : { 'user' : [form1,form2,form3] } }
Template
{% for job, users in ordered_forms.items %}
<h2>{{ job }}</h2>
{% for user, forms in users %}
<table class='table striped'>
<thead>
<tr>
<th>{{ user }}</th>
<th>Train</th>
<th>Semi</th>
<th>Tri-Axle</th>
<th>Flow Boy</th>
<th>Misc</th>
<th>Material</th>
<th>Notes</th>
<th></th>
</tr>
</thead>
<tbody>
{% for form in forms %}
<tr>
<td>{{ form.instance.broker.name }}</td>
<td>{{ form.train }}</td>
<td>Semi</td>
<td>Tri-Axle</td>
<td>Flow Boy</td>
<td>Misc</td>
<td>Material</td>
<td>Notes</td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endfor %}
{% endfor %}
Turns out I forgot to add .items to {% for user, forms in users %}.
{% for job, users in ordered_forms.items %}
<h2>{{ job }}</h2>
{% for user, forms in users.items %}
<table class='table striped'>
....
{% endfor %}
{% endfor %}

Categories

Resources