Display data from models in website - python

I am new to Django. I want to display latest data entered from models to the website.
models.py
class Service(models.Model):
service_name = models.CharField(max_length=200)
service_code = models.IntegerField(default=0, unique=True)
views.py
def Latest(return):
latest_services = Service.objects.order_by('service_name')
index.html
{{ service_name }}
Latest Services Goes here
When I run the code nothing is displayed!

You need to iterate over the queryset:
<ul>
{% for service in latest_services %}
<li>{{ service.service_name }}</li>
{% endfor %}
</ul>
Anyway, if you want to display the latest entries, you should add a new field to your model with the date. For example:
class Service(models.Model):
created_on = models.DateTimeField(auto_now=True)
service_name = models.CharField(max_length=200)
service_code = models.IntegerField(default=0, unique=True)
And then in your query:
latest_services = Service.objects.order_by('created_on')

Related

Objects have the same ID on production in Django App

I have project in Python Django. It has three models: Project, Files and Agreement.
class Project(models.Model):
project_name = models.CharField(max_length=50)
client_name = models.CharField(max_length=50)
agreement_number = models.CharField(max_length=20)
brief_status = models.CharField(max_length=20, choices=BRIEF_CHOICES, default='nieuzupelniony')
agreement_status = models.CharField(max_length=20, choices=AGREEMENT_CHOICES, default='niedostarczona')
resources_status = models.CharField(max_length=20, choices=RESOURCES_CHOICES, default='niedostarczone')
payment_status = models.CharField(max_length=20, choices=PAYMENT_CHOICES, default='nieoplacone')
message = models.CharField(max_length=200, default='Brak wiadomoĊ›ci')
project_date = models.CharField(max_length=10)
status = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="project")
modifications = models.CharField(max_length=15, default='2')
corrections = models.CharField(max_length=15, default='3')
def __str__(self):
return self.project_name
class Files(models.Model):
name = models.CharField(max_length=50)
upload = models.FileField(upload_to='uploads/', validators=[validate_file_extension])
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="files")
project = models.ForeignKey(Project, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Agreement(models.Model):
name = models.CharField(max_length=50)
upload = models.FileField(upload_to='uploads/', validators=[validate_file_extension])
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="agreement")
project = models.ForeignKey(Project, on_delete=models.CASCADE)
def __str__(self):
return self.name
In app we have an admin and users. Every user has welcome.html page which display every user project, every user agreement and objects from one additional model which isn't important. When user click on project (user goes to project_detail.html), he can see information about project and there are all files from this project.
def panel(request):
if request.user.is_authenticated:
queryset = Project.objects.filter(user=request.user)
queryset2 = Invoice.objects.filter(user=request.user)
queryset3 = Files.objects.filter(user=request.user)
queryset4 = Agreement.objects.filter(user=request.user)
return render(request, 'projects/welcome.html', {'project': queryset, 'invoice': queryset2, 'files': queryset3, 'agreement': queryset4})
else:
return render(request, 'projects/welcome.html')
Admin has user_detail.html page, and there are all files and projects and agreements for this user.
class UserDetailView(DetailView):
model = User
template_name = 'projects/user_detail.html'
context_object_name = 'user'
def get_context_data(self, **kwargs):
context_data = super().get_context_data(**kwargs)
context_data['invoice'] = Invoice.objects.all()
context_data['project'] = Project.objects.all()
context_data['files'] = Files.objects.all()
context_data['agreement'] = Agreement.objects.all()
return context_data
Here is a part of my template.
<div class="block bg-white rounded shadow-2xl text-indigo-800 m-2 p-4 w-full h-full">
<p class="text-3xl text-left mb-2 pb-2 border-b">Pliki</p>
{% for files in files.all %}
{% if files.user == user %}
<div class="flex justify-between mb-2 pb-2 border-b pr-32">
{{files.name}}
<p class="text-xl font-thin text-indigo-800 hover:text-indigo-600 text-left mb-2">{{files.project}}</p>
</div>
{% endif %}
{% endfor %}
</div>
Unfortunetly when I tried (as admin) edit any of file I've got an error:
Exception Type: MultipleObjectsReturned
Exception Value:
get() returned more than one Files -- it returned 8!
So to each project you can assign file and agreement. I have problem with my database. On my local environment everything is fine. On local SQlite3 every file object has unique ID, unfortunetly on my producton, on phpMyAdmin every object has the same ID = 0. Where I can find error? I tried working with my models and database, unfortunetly I can't find what is going on. So now I cannot update file for my user even by my Django Admin Dashboard, because I've got an error.
Hi you have a problem in your template you use files in files.all so when you do files.project you get more than one
{% for files in files.all %}
you need to do :
{% for file in files.all %}
....
{{file.project}}</p>

Display User teams in template

I have 3 models - Project, Team and a CustomUser model. I'm trying to display a list of teams which a user is part of on the user's detail page, and display a list of users who are part of the project team on the project's detail page but I'm at a stand-still.
# project/users/models.py
class CustomUser(AbstractUser):
name = models.CharField(max_length=255)
# Relationship Fields
team = models.ManyToManyField(
'users.Team',
related_name="teams",
)
class Team(models.Model):
# Relationship Fields
project = models.OneToOneField(
'projects.Project',
on_delete=models.CASCADE, related_name="projects",
)
# project/projects/models.py
class Project(models.Model):
name = models.CharField(max_length=255)
project/projects/templates/projects/project_detail.html
{% for user in project.team.user.all %}
{{ user.name }}
{% endfor %}
I've tried variations of the above such as
{% for user in users.teams.projects.all %}
{{ user.name }}
{% endfor %}
but I can't seem to make anything show. I think I'm doing something simple wrong - I've read through the docs for displaying ManyToManyFields but I'm at a loss! Can anybody point me in the right direction?
im not sure but i think related_name are missed used in this situation:
class Team(models.Model):
# Relationship Fields
project = models.OneToOneField(
'projects.Project',
on_delete=models.CASCADE, related_name="projects",
)
this means that in one object of the class Project will have an attribute with the name projects that will be a reference to the teams. I believe you want:
class Team(models.Model):
# Relationship Fields
project = models.OneToOneField(
'projects.Project',
on_delete=models.CASCADE, related_name="team",
)
So you will be able to call project.team.
Changing your code:
# project/users/models.py
class CustomUser(AbstractUser):
name = models.CharField(max_length=255)
# Relationship Fields
team = models.ManyToManyField(
'users.Team',
related_name="customers",
)
class Team(models.Model):
# Relationship Fields
project = models.OneToOneField(
'projects.Project',
on_delete=models.CASCADE, related_name="team",
)
class Project(models.Model):
name = models.CharField(max_length=255)
So in the template now you could:
{% for user in project.team.customers.all %}
{{ user.name }}
{% endfor %}

Django - filtering by user

I want to render data from the Route model that belongs to the Driver in their 'accounts' page - so displaying the leave_from, destination etc data they have saved in the database so far.
Models.py:
class Driver(models.Model):
user = models.OneToOneField(User, default=1)
first_name = models.CharField(max_length=120, blank=True, null=True)
last_name = models.CharField(max_length=120, blank=True, null=True)
tel = models.CharField(max_length=120, blank=True, null=True)
slug = models.SlugField(max_length=120, unique=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return self.user.username
def get_absolute_url(self):
return reverse("account", kwargs={"slug": self.slug})
def save(self, *args, **kwargs):
self.slug = slugify(self.first_name)
super(Driver, self).save(*args, **kwargs)
class Route(models.Model):
leave_from = models.CharField(max_length=120, blank=True, null=True)
destination = models.CharField(max_length=120, blank=True, null=True)
date = models.DateField(auto_now_add=False, auto_now=False)
time = models.TimeField(auto_now_add=False, auto_now=False)
driver = models.ForeignKey(Driver, on_delete=models.CASCADE)
def __str__(self):
return self.leave_from
I've played with various querysets and the below is the closest to getting there (I think... I'm new to coding and Django).
Views.py:
def route(request, slug):
routedetails = Driver.objects.filter(route=request.user.driver.route_set.all())
context = {
"routedetails": routedetails,
}
return render(request, "route.html", context)
With that I am able to get user to display the same number of instances of data in Route for that Driver.
Template:
{% for route in routedetails %}
<p>{{ route.user }}</p>
{% endfor %}
I've tried all different variations but I feel this has got me the closest as it is at least returning the user the same number of times there is data in Route for this user. In this case there are 2 routes saved in Route and so the username is returned twice. I have tested on other users and it always matches.
I've looked everywhere and this is as far as I've been able to get so appreciate any help.
If you want Route details it is best to query the Route model directly:
routedetails = Route.objects.filter(driver__user=request.user)
You can then iterate through the Route objects in your template:
{% for route in routedetails %}
<p>{{ route.leave_from }}</p>
<p>{{ route.destination }}</p>
...
{% endfor %}
Pocket Kings' solution is great and should be accepted. This is an example if you want to show routes for multiple drivers (admin page?) in order to avoid N+1 queries. This pre-fetches all the routes associated to the drivers and adds an attribute routes to each driver with their specific routes, so that it would eliminate the unneeded SQL queries later.
from django.db.models import Prefetch
drivers = Driver.objects.all()
queryset = drivers.prefetch_related(Prefetch('route_set', queryset=Route.objects.filter(driver_id__in=drivers), to_attr='routes'))
Template
{% for driver in drivers %}
{% for route in driver.routes %}
<p>{{ route.leave_from }}</p>
<p>{{ route.destination }}</p>
...
{% endfor %}
{% endfor %}
To get logged in driver's routes, the simplest approach is.
views.py
routes = request.user.driver.route_set.all()
template
{% for route in routes %}
{{ route.leave_from }}
{{ route.destination }}
{% endfor %}

django Get foreign-key model in view and show in html

So I have two models:
class UserMeasurements(models.Model):
user = models.CharField(max_length=20)
time = models.DateTimeField(blank=True, null=True)
set = models.ForeignKey(PhotoSets, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'user_measurements'
class PhotoSets(models.Model):
image_dir = models.CharField(max_length=200)
machine = models.ForeignKey(Machine, models.DO_NOTHING)
set_id = models.AutoField(primary_key=True)
photo_taken_time = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'photo_sets'
In the view.py I have :
def Main(request):
measurement_list = UserMeasurements.objects.order_by('-time')
photo_set_list = PhotoSets.objects.all()
a = measurement_list.set.get_field('PhotoSets').rel.to
//this is where I try to get the related models
print str(a)
return render(request, 'main.html', {'measurement_list': measurement_list})
I am trying to show the image_dir in the webpage with every User Measurement.
I checked other stackoverflow questions. But still I can't figure it out.
Thanks in advance.
I don't know what you're trying to do with that a variable, but you don't need to do any of this. You should just follow the foreign key when you output each measurement, eg in your template:
{% for measurement in measurement_list %}
User: {{ measurement.user }}
Time: {{ measurement.time }}
Image dir: {{ measurement.set.image_dir }}
{% endfor %}
Note that this is explained quite fully in the docs, especially in the tutorial where they use the example of poll questions and choices.
Would you give it a try in your main.html
{% for item in measurement_list %}
{{ item.image_dir }}
{% endfor %}

Django 1.8.3: Showing many-to-many additional fields in template

I have the following problem: A project can have multiple Roles, How do I show the roles field in a template? project.role shows blank and the problem is even after using _set.all in the template, I still do not get the contents from the database to show.
Model.py
class Project(models.Model):
"""
Information for each Project
"""
project_name = models.CharField(max_length=255, blank=True, null=True, unique=True)
project_description = models.TextField(null=True, blank=True)
project_url = models.URLField(max_length=200, null=True, blank=True)
#For Admin Purposes and filtering, to keep track of new and old in the database by administrative users
date_added = models.DateTimeField(auto_now_add=True, null=True, blank=True, verbose_name=_('Date added'))
last_modified = models.DateTimeField(auto_now=True, null=True, blank=True, verbose_name=_('Last modified'))
class Role(models.Model):
"""
Information for Role
"""
role = models.CharField(max_length=255, blank=True, null=True)
project_role = models.ManyToManyField(Project)
View.py
class ProjectView(ListView):
template_name = '_projects.html'
model = Project
def get_context_data(self, **kwargs):
context = super(ProjectView, self).get_context_data(**kwargs)
context['projects'] = Project.objects.all()
return context
Template
{% for project_info in projects %}
{{project_info.project_name}}
</br>
{{project_info.project_description}}
</br>
{{project_info.project_url}}
</br>
{% for rolling in project_info.project_role_set.all %}
{{rolling}}
{% endfor %}
{% endfor %}
Try this:
{% for rolling in project_info.role_set.all %}
{{rolling}}
{% endfor %}

Categories