Selecting one row from Foreign Key in Django - python

I have the following models in Django:
class Kingdom(models.Model) :
class Meta:
ordering = ('kingdom_name', )
kingdom_name = models.CharField(max_length=128, null=True, blank=True)
def __str__(self) :
return self.kingdom_name
class Phylum_Clade(models.Model) :
class Meta:
ordering = ('phylum_name', )
phylum_name = models.CharField(max_length=128, null=True, blank=True)
kingdom = models.ForeignKey(Kingdom, on_delete=models.CASCADE, null=True)
def __str__(self) :
return self.phylum_name
class Classe_Clade(models.Model) :
class Meta:
ordering = ('classe_name', )
classe_name = models.CharField(max_length=128, blank=True, null=True)
phylum_clade = models.ForeignKey(Phylum_Clade, on_delete=models.CASCADE, null=True)
kingdom = models.ForeignKey(Kingdom, on_delete=models.CASCADE, null=True)
def __str__(self) :
return self.classe_name
class Ordre(models.Model) :
class Meta:
ordering = ('ordre_name', )
ordre_name = models.CharField(max_length=128, blank=True, null=True)
classe_clade = models.ForeignKey(Classe_Clade, on_delete=models.CASCADE, null=True)
phylum_clade = models.ForeignKey(Phylum_Clade, on_delete=models.CASCADE, null=True)
kingdom = models.ForeignKey(Kingdom, on_delete=models.CASCADE, null=True)
def __str__(self) :
return self.ordre_name
class Famille(models.Model) :
class Meta:
ordering = ('famille_name', )
famille_name = models.CharField(max_length=128, blank=True, null=True)
ordre = models.ForeignKey(Ordre, on_delete=models.CASCADE, null=True)
classe_clade = models.ForeignKey(Classe_Clade, on_delete=models.CASCADE, null=True)
phylum_clade = models.ForeignKey(Phylum_Clade, on_delete=models.CASCADE, null=True)
kingdom = models.ForeignKey(Kingdom, on_delete=models.CASCADE, null=True)
def __str__(self) :
return self.famille_name
class Binomiale(models.Model) :
class Meta:
ordering = ('binomiale', )
nom = models.CharField(max_length=128, blank=True)
name = models.CharField(max_length=128, blank=True)
binomiale = models.CharField(max_length=128, blank=True)
famille = models.ForeignKey(Famille, related_name='famille_names', on_delete=models.CASCADE, null=True)
ordre = models.ForeignKey(Ordre, related_name='ordre_names', on_delete=models.CASCADE, null=True)
classe_clade = models.ForeignKey(Classe_Clade, related_name='classe_names', on_delete=models.CASCADE, null=True)
phylum_clade = models.ForeignKey(Phylum_Clade, related_name='phylum_names', on_delete=models.CASCADE, null=True)
kingdom = models.ForeignKey(Kingdom, related_name='kingdom_names', on_delete=models.CASCADE, null=True)
image = models.ImageField(blank=False, default='no_picture.png')
img_thumbnail = models.ImageField(blank=False, default='no_picture.png')
observations = models.ManyToManyField(settings.AUTH_USER_MODEL,
through='Observation', related_name='observations')
def __str__(self) :
return self.binomiale
In Views.py I have the following code:
class Famille1(OwnerListView):
model = Binomiale
template_name = 'database/famille1.html'
template_name2 = 'database/especes.html'
def get(self, request) :
strval = request.GET.get("search", False)
if strval :
query = Q(name__icontains=strval) | Q(nom__icontains=strval)
query.add(Q(name__icontains=strval) | Q(nom__icontains=strval), Q.OR)
data_list = Binomiale.objects.filter(query).select_related().distinct().order_by('nom')[:12]
ctx = {'data_list' : data_list, 'search': strval}
return render(request, self.template_name2, ctx)
else:
if request.user.is_authenticated:
famille_list1 = Binomiale.objects.select_related("famille").distinct().order_by("famille__famille_name")[:12]
ctx = {'famille_list1' : famille_list1, 'search': strval}
return render(request, self.template_name, ctx)
In my html file I use the following code:
{% if famille_list1 %}
<div class="row row-cols-12 g-3">
{% for data in famille_list1 %}
<div class="col-sm-6 col-lg-2">
<a class="linkStyles3" href="{% url 'database:data_detail' data.id %}">{{ data.famille }}</a><br/>
<h6 style="color:black">{{ data.nom }}</h6>
<img class="img-thumbnail" src="{% get_media_prefix %}{{data.img_thumbnail}}" style="width:50%">
</div>
{% endfor %}
</div>
{% endif %}
</p>
The output of this is similar to the following sqlite3 command, and output (partial):
sqlite> select famille_name, nom, name, img_thumbnail from database_binomiale inner join database_famille on database_famille.id = database_binomiale.famille_id order by famille_id;
Apidae|Bourdon terreste|Bumble bee|BumbleBee_thumb.jpg
Apidae|Abeille à miel|Honey bee|HoneyBee_thumb.jpg
Apidae|Abeille à longue corne|Long Horned Bee|LongHornedBee_thumb.jpg
Apidae|Bourdon fébrile|Common Eastern Bumble Bee|CommonEasternBumbleBee_thumb.jpg
Ardeidae|Héron cendré|Grey heron|Heron_thumb.jpg
Simuliidae|Mouche noire|Black fly|BlackFly_thumb.jpg
Muscidae|Mouche domestique|House fly|HouseFly_thumb.jpg
Culicidae|Moustique|Mosquito|Mosquito_thumb.jpg
Culicidae|Moustiques éléphants|Elephant mosquito|ElephantMosquito_thumb.jpg
Corvidae|Grand Corbeau|Common Raven|Raven_thumb2.jpg
Corvidae|Geai bleu|Blue jay|BlueJay_thumb.jpg
Cardinalidae|Cardinal à poitrine rose|Rose-Breasted Grosbeak|Grosbeak_thumb.jpg
Cardinalidae|Cardinal rouge|Northern Cardinal|Cardinal_thumb2.jpg
Mustelidae|Loutre de rivière|North American River Otter|Otter_thumb2.jpg
Mustelidae|Hermine|Stoat|Stoat_thumb.jpg
My problem is that I do not want repeats of each class "Apidae","Cardinalidae","Mustelidae" etc. I want just a single example, with its image to be displayed. I have banged my head against a wall on this for longer than I care to admit.
Can someone help me?
Thankyou!

I think that you should query on the Famille model and thus check the nom, name, etc. of the related Binomiale model objects with:
data_list = Binomiale.objects.filter(
Q(famille_names__name__icontains=strval) | Q(famille_names__nom__icontains=strval)
).distinct()
The famille_names__ lookup is due to the value for the related_name=.. parameter [Django-doc], which does not make much sense.
Note: The related_name=… parameter [Django-doc]
is the name of the relation in reverse, so from the Famille model to the Binomiale
model in this case. Therefore it (often) makes not much sense to name it the
same as the forward relation. You thus might want to consider renaming the famille_names relation to binomales.

Related

TypeError: __str__ returned non-string (type NoneType). Not sure how to solve this

[![Nurse admin page[![][1]][1][models.py
from django.db import models
#Work Related aka Department and Work Shift
class Department(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.name
class WorkShift(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
start_datetime = models.DateTimeField(null=True, blank=True)
end_datetime = models.DateTimeField(null=True, blank=True)
def __str__(self):
return self.name
#Personel Related aka Employees and Patients
class Doctor(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Nurse(models.Model):
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE)
reports_to = models.OneToOneField(Doctor, default="", blank=True, null=True, on_delete=models.CASCADE)
work_shift = models.OneToOneField(WorkShift, default="", blank=True, null=True, on_delete=models.CASCADE)
def __str__(self):
return str(name)
class Patient(models.Model):
STATUS = (
('Sick', 'Sick'),
('Healing', 'Healing'),
('Cured', 'Cured'),
('Deceased', 'Deceased'),
)
name = models.CharField(max_length=200, null=True, blank=True)
description = models.TextField(blank=True, null=True)
status = models.CharField(max_length=200, null=True, blank=True, choices=STATUS)
department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE)
care = models.ForeignKey(Nurse, default="", blank=True, null=True, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
def __str__(self):
return self.name
views.py
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from .models import Doctor, Nurse, Patient
from django.http import HttpResponse
# Create your views here.
def index(request):
patient = Patient.objects.all()
nurse = Nurse.objects.all()
doctor = Doctor.objects.all()
total_patient = patient.count()
sick = patient.filter(status='Sick').count()
healing = patient.filter(status='Healing').count()
cured = patient.filter(status='Cured').count()
total_nurse = nurse.count()
# if request.method == 'POST':
# form =
context = {
'patient':patient, 'nurse':nurse,
'doctor':doctor, 'total_patient':total_patient,
'sick':sick, 'healing':healing, 'cured':cured,
'total_nurse':total_nurse
}
return render(request, 'lifesaver/index.html', context)
def patient(request):
patient = Patient.objects.all()
total_patient = patient.count()
context = {
'patient':patient,
'total_patient':total_patient
}
return render(request, 'lifesaver/patient.html', context)][1]
forms.py
from django import forms
from .models import Doctor, Nurse, Patient
from django.auth.contrib.forms import UserCreationForm
class DoctorForm(forms.ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Doctor',
'class': 'form-control'
}
))
department = forms.ModelChoiceField(queryset=department.objects.all)
class NurseForm(forms.ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Nurse',
'class': 'form-control'
}
))
class PatientForm(forms.ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Patient'
'class': 'form-control'
}))
HTML for patient
{% extends 'lifesaver/main.html' %}
{% block content %}
<h1>SUPERSTAR</h1>
{% for patient in patient %}
{{patient.name}}
{% endfor %}
{% endblock content %}
I get this error when I go to try to add another Nurse. The URL is http://127.0.0.1:8000/admin/lifesaver/nurse/add/. Everything else behaves as expected, except the adding the Nurse part.
If I try to remove the def __str___ part, the error still displays. I believe the error lies in the:
work_shift = models.OneToOneField(WorkShift, default="",
blank=True,
null=True,
on_delete=models.CASCADE)
part since when I included that code, the error spawned. Furthermore, the code is to add a work shift to certain employees and the goal is that the employees shift will display in their profile.
How do I fix this issue?
EDIT: When accessing the HTML template, the web page behaves as expected and has no issues.
In your Nurse model replace this:
def __str__(self):
return str(Nurse.name)
with this:
def __str__(self):
return self.name

How to load a parameter from an object in an object?

class Product(models.Model):
subcategory = models.ManyToManyField(Subcategory, related_name="Category")
name = models.CharField(max_length=32, unique=True)
title = models.CharField(max_length=3000)
ean = models.PositiveIntegerField(blank=True, null=True, unique=True)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE, blank=True, null=True)
origin_name = models.CharField(max_length=32, blank=True, null=True)
quantity = models.PositiveIntegerField(blank=True, null=True)
highlights = models.TextField(max_length=3000, blank=True, null=True)
description = models.TextField(max_length=3000, blank=True, null=True)
delivery = models.TextField(max_length=3000, blank=True, null=True)
selling_price = models.DecimalField(max_digits=9, decimal_places=2)
slug = models.SlugField(unique=True)
class Infobox(models.Model):
name = models.CharField(max_length=32)
measurment = models.CharField(max_length=32)
resolution = models.CharField(max_length=32)
product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True)
I would like to display on my detail page all infobox objects that are linked to the device, do any of you know how to do this?
THANKSSSS <3
urls.py
Add below to your urlpatterns:
path('view_infoboxes/<int:product_id>', views.view_infoboxes, name='view_infoboxes'),
views.py
def view_infoboxes(request, product_id):
template = loader.get_template('page.html')
context = {"infoboxes": Infobox.objects.filter(product=product_id)}
return HttpResponse(template.render(context, request))
page.html
...
<div class="row">
{% for infobox in infoboxes %}
<p>{{ infobox.name }}</p>
{% endfor %}
</div>
...

Django Multiple classes in Model.py

I am new to Django and Python. I am trying to create a database of babysitters and one of the objects which can have multiple fields is Education. My first Babysitter has 2 qualifications which produces an error an will not display.
Error Message
views.py
from django.shortcuts import render, get_object_or_404, get_list_or_404
from .models import Babysitter, Education, Work, Reference
# Create your views here.
def all_babysitters(request):
babysitters = Babysitter.objects.all()
return render(request, "babysitters.html", {"babysitters": babysitters})
def babysitter_profile(request, id):
"""A view that displays the profile page of a registered babysitter"""
babysitter = get_object_or_404(Babysitter, id=id)
reference = get_object_or_404(Reference)
education = get_object_or_404(Education)
return render(request, "babysitter_profile.html", {'babysitter': babysitter, 'education': education, 'reference': reference} )
models.py
from django.db import models
from datetime import datetime
# Create your models here.
class Babysitter(models.Model):
list_display = ('firstName', 'lastName', 'minderType')
firstName = models.CharField(max_length=50, blank=True, null=True)
lastName = models.CharField(max_length=50, blank=True, null=True)
minderType = models.CharField(max_length=50, blank=True, null=True)
image = models.ImageField(upload_to='images')
phone = models.CharField(max_length=20, blank=True, null=True)
email = models.CharField(max_length=50, blank=True, null=True)
address1 = models.CharField(max_length=100, null=True)
address2 = models.CharField(max_length=100, null=True)
city = models.CharField(max_length=20, null=True)
county = models.CharField(max_length=100, null=True)
eircode = models.CharField(max_length=7, null=True)
biography = models.TextField(max_length=280,blank=True)
def __str__(self):
return self.firstName + ' ' + self.lastName
class Education(models.Model):
babysitter = models.ForeignKey(Babysitter)
school = models.CharField(max_length=50)
qualification = models.CharField(max_length=50)
fieldOfStudy = models.CharField(max_length=50)
dateFrom = models.DateField(auto_now=False, auto_now_add=False)
dateTo = models.DateField(
auto_now=False, auto_now_add=False, null=True, blank=True)
current = models.BooleanField(default=False)
graduated = models.BooleanField(default=False)
def __str__(self):
return self.school
class Work(models.Model):
babysitter = models.ForeignKey(Babysitter)
family = models.CharField(max_length=50)
role = models.CharField(max_length=50)
location = models.CharField(max_length=50)
dateFrom = models.DateField(auto_now=False, auto_now_add=False)
dateTo = models.DateField(
auto_now=False, auto_now_add=False, null=True, blank=True)
current = models.BooleanField(default=False)
def __str__(self):
return self.work
class Reference(models.Model):
babysitter = models.ForeignKey(Babysitter)
refFamily = models.CharField(max_length=50)
contact = models.CharField(max_length=50)
location = models.CharField(max_length=50)
email = models.CharField(max_length=50, blank=True, null=True)
reference = models.CharField(max_length=300)
date = models.DateField(auto_now=False, auto_now_add=False)
def __str__(self):
return self.refFamily
Can somebody help? I am going to pull my hair out. Thanks
You aren't passing enough information into the calls to get a Reference and Education object:
babysitter = get_object_or_404(Babysitter, id=id)
reference = get_object_or_404(Reference, babysitter_id=babysitter.id)
education = get_object_or_404(Education, babysitter_id=babysitter.id)
The get_object_or_404() function is a shortcut that calls get() underneath, and get() only ever returns a single object (returning more than one will result in the Exception you are seeing).
If you want to see more than one object, then don't use the get_object_or_404 shortcut method (I find those "shortcut" methods to be ugly, personally). Instead, change it to something like:
education_qs = Education.objects.filter(babysitter_id=babysitter.id)
Then loop over that queryset to get the results:
for ed in education_qs:
# Get some data
school = ed.school
You can loop over the queryset in your HTML template, if that's easier.
Update: Here's a better answer that shows how to use querysets:
def babysitter_profile(request, id):
"""A view that displays the profile page of a registered babysitter"""
babysitter = get_object_or_404(Babysitter, id=id)
reference_qs = Reference.objects.filter(babysitter_id=babysitter.id)
education_qs = Education.objects.filter(babysitter_id=babysitter.id)
return render(request, "babysitter_profile.html", {
'babysitter': babysitter,
'education_qs': education_qs,
'reference_qs': reference_qs}
)
Then, in your HTML template, you could do something like the following to show the schools the Babysitter has attended (in a bulleted list):
<ul>
{% for ed in education_qs %}
<li>{{ ed.school }}</li>
{% endfor %}
</ul>
You could do something similar for the Reference data.
I think you should set some parameters to get a specific object, rather than get a bunch of objects.
Just do it like the first instance for get_object_or_404.
reference = get_object_or_404(Reference,id=xx)
education = get_object_or_404(Education,id=yy)
get_object_or_404 returns just 1 object. Use get_list_or_404 if babysitter has "2 qualification" to prevent exception.
babysitter = get_object_or_404(Babysitter, id=id)
education = get_list_or_404(Education, id=babysitter.id)
To prevent MultipleObjectReturned exception.

Call another model field in url django

My problem is have two models job and company and i want to get all jobs in this company
My urls.py:
url(r'^jobs/(?P<slug>[\w-]+)/$', views.job_at_company, name='job_at_company'),
My views.py:
def job_at_company(request, slug):
return render(request, 'jobs.html')
My models.py:
class Company(models.Model):
title = models.CharField(max_length=100, blank=False)
slug = models.SlugField(blank=True, default='')
city = models.CharField(max_length=100, blank=False)
contact_info = models.CharField(max_length=100, blank=False, default=0)
facebook = models.CharField(max_length=100, blank=True)
twitter = models.CharField(max_length=100, blank=True)
linkedin = models.CharField(max_length=100, blank=True)
logo = models.ImageField(upload_to="logo", default=0)
class Jobs(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(blank=True, default='')
company = models.ForeignKey(Company, on_delete=models.CASCADE)
price = models.IntegerField(default='')
Description = models.TextField(blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
job_type = models.CharField(max_length=100, choices=(('Full Time', 'Full Time'),('Part Time', 'Part Time')),default='Full Time')
in the views.py we can add this
def job_at_company(request, slug):
results = Jobs.objects.filter(company__slug=slug)
context = {'items':results}
return render(request, 'jobs.html',context)
Suppose you pass id in the url. The id is the primary key of the company. You would have to modify your url to accept id like -
url(r'^jobs/(?P<slug>[\w-]+)/(?P<pk>[\d]+)$', views.job_at_company, name='job_at_company')
And modify your views.py -
def job_at_company(request, slug, pk):
jobs_qs = Jobs.objects.filter(company__id=pk)
return render(request, 'jobs.html', {'jobs': jobs_qs})
And use it in your html like -
{% for job in jobs %}
{{job.title}}
{% endfor %}
Look at this link. Django's documentation is helpful, follow that

Display only creator's files - Django/Python

I would like to display only the pictures uploaded by the creator (user) on their individual profiles.
How would I alter my code to display that?
Thank you!
models.py:
class Photo(models.Model):
creator = models.ForeignKey(MyUser, null=False, blank=False)
category = models.ForeignKey("Category", default=1, null=True, blank=True)
title = models.CharField(max_length=30, null=True, blank=True)
description = models.TextField(max_length=120, null=True, blank=True)
image = models.ImageField(upload_to='user/photos/', null=True, blank=True)
slug = models.SlugField(null=False, blank=False)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, null=True)
updated = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
class Meta:
unique_together = ('slug', 'category')
ordering = ['-timestamp']
def __unicode__(self):
return "%s" %(self.creator)
def get_image_url(self):
return "%s/%s" %(settings.MEDIA_URL, self.image)
def get_absolute_url(self):
return "%s/%s" %(self.creator, self.slug)
views.py:
#login_required
def account_home(request, username):
try:
u = MyUser.objects.get(username=username)
except:
u = None
photo_set = Photo.objects.all()
context = {
"photo_set": photo_set,
"notifications": notifications,
"transactions": transactions
}
return render(request, "accounts/account_home.html", context)
.html:
{% for photo in photo_set %}
<img src="{{ photo.get_image_url }}" class='img-responsive'>
<hr/>
{% endfor %}
You have a ForeignKey to user, so you can just filter the photos by that:
photo_set = Photo.objects.filter(creator=u)
or even better use the reverse relationship:
photo_set = u.photo_set.all()
Also, never ever ever ever use a blank except statement in your code. The only exception you are expecting the get to raise is MyUser.DoesNotExist, so you should catch that only.

Categories

Resources