accessing foreignKey inside the template - django

well it's quiet simple.
2 models with ManyToMany relation:
class Artist(models.Model):
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True,
help_text='Uniq value for artist page URL, created from name')
birth_name = models.CharField(max_length=100, blank=True)
class Song(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True,
help_text='Unique value for product page URL, create from name.')
youtube_link = models.URLField(blank=False)
artists = models.ManyToManyField(Artist)
my view suppose to display latest 5 songs:
def songs(request, template_name="artists/songs.html"):
song_list = Song.objects.all().order_by('-created_at')[:5]
return render_to_response(template_name, locals(),
context_instance=RequestContext(request))
and the problem is in the template... i want to display the artist name
but just dont realy know how to do it, i tried:
{% for song in song_list %}
{{ artists__name }} - {{ song.title }}
{% endfor %}
would appreciate any help !

Try changing your template code to:
{% for song in song_list %}
{% for artist in song.artists.all %}
{{ artist.name }} - {{ song.title }}
{% endfor %}
{% endfor %}

artists is another type of manager, so you have to iterate through artists.all and print the name attribute of each element.

Well, I worked on above solution of Mr #Dominic Rodger, but because am using Django version 3.2 it did not worked for me. Therefore, the problem may remain the same but according to how Django version changes, the way to solve them sometimes become different. If you're using Django 3.x use below solution.
In views.py
def songs(request):
song_list = Song.objects.all().order_by('-created_at')[:5]
song_list = {'song_list':song_list}
return render(request, 'artists/songs.html', song_list)
In your HTML Template use code below
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Artist - Song Title</th>
</tr>
</thead>
<tbody>
{% for song in song_list %}
</tr>
<td>{{ song.artist.name }} - {{ song.title }}</td>
<tr>
{% endfor %}
</tbody>
</table>
In urls.py
path('songs/', views.songs, name='songs'),
If you're running source code from localhost, then type on your browser http://127.0.0.1:8000/songs/
Thank you ....

Related

Django templates - how to run a method on a variable?

I'm new to Django, so maybe my attempts are pure heresy ;)
I'm trying to make a view which lists disponible conference rooms with its attributs, availability included.
I have 2 models: Room and Reservation. I'd like in the view to have a column saying if the room is available the day the page is displayed.
My models.py:
from django.utils import timezone
from django.db import models
class Room(models.Model):
name = models.CharField(max_length=255, unique=True)
capacity = models.IntegerField()
projector = models.BooleanField()
class Reservation(models.Model):
room = models.ForeignKey(Room, on_delete=models.CASCADE)
date = models.DateField()
comment = models.CharField(max_length=255)
class Meta:
unique_together = ('room', 'date',)
my views.py:
class ShowRoom(View):
def get(self, request):
rooms = Room.objects.all()
time_now = timezone.now().date()
context = {
'rooms': rooms,
'time_now': time_now
}
return render(request, 'rooms/list_rooms.html', context)
My template:
{% extends 'rooms/base.html' %}
{% block block_title %} Home {% endblock %}
{% block block_content %}
{% if rooms %}
<table class="table">
<thead>
<td> Name </td>
<td> Capacity </td>
<td> Available </td>
<td> Projector </td>
</thead>
<tbody>
{% for room in rooms|dictsort:'capacity' %}
<tr>
<td> {{ room.name }} </td>
<td> {{ room.capacity }} </td>
<td> Available? </td>
<td> {{ room.projector|yesno:'yes,no' }} </td>
</tbody>
{% endfor %}
</table>
{% else %}
<h1> You have no registered rooms yet. </h1>
{% endif %}
{% endblock %}
Everything works fine, I need just to replace this <td> Available? </td> line with a code, which would display "free" or "occupied" according to existing room reservations.
I've found out that maybe I should write a custom filter.
Here is my filter:
from django import template
from rooms.models import Room, Reservation
register = template.Library()
#register.filter
def check_reservation(queryset, now):
return queryset.filter(date=now)
(I wanted first to make it working, and after make it display this "free" or "occupied".)
I've added to the template {% load my_extras %} and replaced the line I want to change with
<td> {{ room.reservation_set.all|check_reservation:'time_now' }} </td>
The output is:
ValidationError at /room/ ["'time_now' value has an invalid date
format. It must be in YYYY-MM-DD format."]
Before adding the filter, I was trying this solution in the shell and it was working.
I don't know if there is something wrong with the filter, or I try to approach the issue from wrong side.
Thanks in advance for any tips.
Try adding another field to the the Room class:
occupied = model.BooleanField(default=False)
In the views you can check the date associated with the reservation and today's date.
if reservation.date == time_now:
room.occupied = true
You can then filter with rooms that are available and which are not.
rooms_occupied = room.objects.filter(occupied=True)
rooms_available = room.object.filter(occupied=False)
In the template:
{% if rooms_occupied %}
Available
{% endif %}

Can't render attributes of an objecte linked with M2M field

Trying to render attributes of objects that are linked with another object via m2m field.
#models
class Arm(models.Model):
cmrs = models.ManyToManyField(CMR, null=True)
class CMR(models.Model):
client = models.ForeignKey('Client', on_delete=models.CASCADE,
null=True, default="", blank=True)
The view
if us.groups.filter(name__in = ['prime']):
query_set = Plan.objects.order_by('-pk')
query_ys = Arm.objects.filter(date=ys)
query_rn = Arm.objects.filter(date=rn)
query_tm = Arm.objects.filter(date=tm)
client_rn = query_rn.prefetch_related('cmrs')
args = {'query_rn': query_rn,
'cl_rn': client_rn,
'query_tm': query_tm,
'query_ys': query_ys,
'query_set': query_set
}
return render(request, 'personnel/schedule/test-schedule-full.html', args)
And the template
<tbody id="add">
{% for query in query_rn %}
<tr class="row100 body {{ query.status }}" data-href="/personnel/arm/{{ query.id }}">
<td class="cell100 column1">{{ query.driver }}</td>
<td class="cell100 column2">{% for idem in cl_rn.cmrs.all %} {{ idem.client }} {% endfor %}</td>
<td class="cell100 column3">{{ query.des_from}}</td>
<td class="cell100 columnarrow"><i class="fas fa-arrow-circle-right"></i></td>
<td class="cell100 column4">{{ query.des_to }}</td>
</tr>
{% endfor %}
</tbody>
What I am trying to do is to show all the values of the client field of an CMR objects that are linked with Arm in <td class="cell100 column2"></td> but it shows nothing instead.
It doesn't make sense to have separate querysets for the prefetch_related call. You're iterating through query_rn, you need to define the prefetch_related on that same queryset and then iterate through the related objects from there; you don't need client_rn at all. So:
query_rn = Arm.objects.filter(date=rn).prefetch_related('cmrs')
...
{% for query in query_rn %}
{% for idem in query.cmrs.all %} {{ idem.client }} {% endfor %}
{% endfor %}
Note also, the first line of your code is a bit off. You shouldn't use __in with a single-list element, just check for equality; and since you just want to check that the related group exists, you should use the exists() method, which is slightly more efficient:
if us.groups.filter(name='prime').exists():

Django - How to delete a object directly from a button in a table

(sorry for my bad english)
I need to delete an object, but directly from a list of the objects that y have in my template.
I have a work orders, that have spare parts but i don't know how to create the deleteview for the spare parts using only a buton in the detailview of the work order. The idea is that the user make click in the Delete button.
This is the model of the Spare Parts
class OrderSparePart(models.Model):
# Relations
workorder = models.ForeignKey(
WorkOrder,
verbose_name=_('order'),
)
# Attributes - Mandatory
spare_part = models.CharField(
max_length=80,
verbose_name=_('spare part'),
)
# Attributes - Optional
price = models.DecimalField(
max_digits=6,
decimal_places=2,
null=True,
blank=True,
verbose_name=_('price'),
)
# Object Manager
# Custom Properties
# Methods
def get_absolute_url(self):
return reverse('work_orders:detail', kwargs={'order_id': self.workorder.id})
# Meta and String
class Meta:
verbose_name = _("order spare part")
verbose_name_plural = _("order spare parts")
This is where is showed in the template
{% if spare_parts %}
<table class="table">
<thead>
<tr>
<th>{% trans "Spare Part" %}</th>
<th>{% trans "Price" %}</th>
<th>{% trans "Delete" %}</th>
</tr>
</thead>
<tbody>
{% for part in spare_parts %}
<tr>
<td><i class="fa fa-gear"></i> {{ part.spare_part }}</td>
{% if part.price %}
<td>$ {{ part.price }}</td>
{% else %}
<td></td>
{% endif %}
<td><i class="fa fa-trash"></i></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>NO HAY REPUESTOS ASENTADOS AÚN</p>
{% endif %}
The the idea is use the to delete the spare part.
how i have to make the deleteview and the link to this???
Thanks!
here in fa fa-thrash pass the id and the URL as I did it:-
{% if spare_parts %}
<table class="table">
<thead>
<tr>
<th>{% trans "Spare Part" %}</th>
<th>{% trans "Price" %}</th>
<th>{% trans "Delete" %}</th>
</tr>
</thead>
<tbody>
{% for part in spare_parts %}
<tr>
<td><i class="fa fa-gear"></i> {{ part.spare_part }}</td>
{% if part.price %}
<td>$ {{ part.price }}</td>
{% else %}
<td></td>
{% endif %}
<td></i></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>NO HAY REPUESTOS ASENTADOS AÚN</p>
{% endif %}
ur url would be sonething like that:
url(r'^delete/(?P<part_id>[0-9]+)/$', view.function, name='delete_view'),
in ur view:
def function(request,part_id =None):
object = YourModel.objects.get(id=part_id)
object.delete()
return render(request,'ur template where you want to redirect')
In your html template inside for loop use the form tag inside <td> to create delete button as below (css class will work if you are using bootstrap3):
<form action="{% url 'delete_view' pk=part.pk %}" method="POST">
{% csrf_token %}
<input class="btn btn-default btn-danger" type="submit" value="Delete"/>
</form>
add urlpattern in urls.py
url(r'^delete-entry/(?P<pk>\d+)/$', views.DeleteView.as_view(), name='delete_view'),
delete view will be like below in views.py
class DeleteView(SuccessMessageMixin, DeleteView):
model = OrderSparePart
success_url = '/'
success_message = "deleted..."
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
name = self.object.name
request.session['name'] = name # name will be change according to your need
message = request.session['name'] + ' deleted successfully'
messages.success(self.request, message)
return super(DeleteView, self).delete(request, *args, **kwargs)
Note: import necessary imports shown in links or you need not to worry if you are using IDE such as pyCharm it will prompt you which import to make.
My solutions works best for django 4.0.3 and is the combination of gahan and Abi waqas answers. Use this one if you are using django 3 or above
Add the following to views.py
def delete_object_function(request, id):
# OrderSparePart is the Model of which the object is present
ob = OrderSparePart.objects.get(id=id)
ob.delete()
return redirect('page-delete.html') # for best results, redirect to the same page from where delete function is called
Add the following to urls.py
path('page-delete/<int:id>', views.delete_object_function, name='delete_object'),
Add the following code to the django template from where the delete function is to be called.
Let's say page-delete.html
<form action="{% url 'delete_object' id=part.id %}" method="post">
{% csrf_token %}
<button class="btn btn-danger" type="submit" ><i class="fa fa-trash"></i></button>
</form>
This works as I've used this solution in my own code.

Django ORM usage in template

I have created and object which contains a few students. I am trying to use each student to pull his data from another model as I iterate through my origianl student object known as student_list. I didn't post the view I made because I know that the object works fine.
I have the following models:
class StudentDetail(Base):
student = models.OneToOneField('Usr', limit_choices_to={'user_type': 'Student'})
klass = models.ForeignKey('Klass', related_name='kara_pore')
class Usr(AbstractUser, Base):
type_choices = (
('Student', 'Student'),
('Teacher', 'Teacher'),
)
user_type = models.CharField(max_length=10,
choices=type_choices,
default='Student')
class Score(Base):
student = models.ForeignKey(Usr, limit_choices_to={'user_type': 'Student'}, related_name='scored')
subject = models.ForeignKey(Subject)
teacher = models.ForeignKey(Usr, limit_choices_to={'user_type': 'Teacher'}, related_name='marked')
exam = models.CharField(max_length=50)
exam_date = models.DateField()
score = models.IntegerField()
out_of = models.IntegerField()
The template file:
{% for student in student_list %}
<tr>
<td> <a href=#>{{ student }}</a> </td>
<td> {{ student.student.scored.score }} </td> <-- this line doesn't work.
<td></td>
</tr>
{% endfor %}
The student_list object works and I can easily iterate through it. I am using that object to filter out data from the Score class. I have never used Zip in my view before. And I don't know whether this is an ideal situation for using that. As far as I know, using the dots to jump through classes should work and get me the value I need. I must be doing something wrong here. The template renders, but the score is not displayed.
Note: Here is my view.
def View(request, pk):
this_klass = Klass.objects.get(id=pk)
student_list = this_klass.kara_pore.all()
return render(request, "grades/view.html", {'this_klass': this_klass, 'student_list': student_list})
The following solved the problem:
{% for student in student_list %}
{% for score in student.student.scored.all %}
<tr>
<td> <a href=#>{{ student }}</a> </td>
<td> {{ score.score }} </td>
<td></td>
</tr>
{% endfor %}
{% endfor %}

How I get data from "third" related model in django?

Hi guys,
I have this models:
class Pais(models.Model):
nome = models.CharField('Nome', max_length=50)
class Brinq(models.Model):
descricao = models.CharField('Nome', max_length=50)
class Filhos(models.Model):
nome = models.CharField('Nome', max_length=50)
idade = models.IntegerField('Idade')
pai = models.ForeignKey('Pais')
brinq = models.ForeignKey('Brinq', related_name='Brinq')
This view:
def editPai(request, idpai=None):
if idpai:
pai = Pais.objects.get(id=idpai)
else:
pai = None
ItensInlineFormSet = inlineformset_factory(Pais, Filhos, form=FilhosForm, extra=1)
formPais = PaisForm()
formsetItens = ItensInlineFormSet(instance=pai)
return render_to_response("base.html", {
"formPais": formPais, "formsetItens": formsetItens
}, context_instance=RequestContext(request), )
and this forms:
class PaisForm(ModelForm):
class Meta:
model = Pais
class FilhosForm(ModelForm):
class Meta:
model = Filhos
Ok, How can I get "descricao" value from "Brinq" model in my template? I think it's a simple question but, I tried looking, looking and looking again from internet and I don't find anything about this.
I start to thing it's not possible to do it using django, I want to believe that I'm wrong, but as I said, I didn't find anything about this in internet.
I try:
{% for form in formsetItens %}
<tr>
<td> {{ form.nome }}</td>
<td> {{ form.idade }}</td>
<td> {{ form.brinq__descricao }}</td>
</tr>
{% endfor %}
and {{ form.brinq.descricao}} to, and nothing... :(
Can anyone help me with this problem?
Regards,
You are trying to iterate over a FormSet. As the docs say "The formset gives you the ability to iterate over the forms in the formset and display them as you would with a regular form".
So you can for example do the following to display all the fields included in the form:
{% for form in formsetItens %}
{{ form.as_table }}
{% endfor %}
..or if it fits your use case you could wrap each form into a form tag, and loop over the form fields:
{% for form in formsetItens %}
<form action="/contact/" method="post">
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
</div>
{% endfor %}
<p><input type="submit" value="Send message" /></p>
</form>
{% endfor %}