Use two models in ListView - django

I have a ListView for every budget category in my list of transactions. For each of these views, I'd like to show the actual budget for this category. For instance, my Bill budget has sub budgets for rent, insurance, phone, etc which is stored in a separate model from the transactions. The current ListView just sends the transactions filtered by budget type:
class BillListView(ListView):
model = Transaction
template_name = 'budget/base_transactions.html'
context_object_name = 'transactions'
paginate_by = 10
queryset = Transaction.objects.filter(budget_type__exact='bill')
Is there a way to send the sub budget data from my budget database as well so I can display it at the top of the template?
My models:
class Transaction(models.Model):
date = models.DateField(default=datetime.date.today)
description = models.CharField(max_length=100, default="")
category = models.CharField(max_length=100, default="")
amount = models.DecimalField(max_digits=10, decimal_places=2, default=0.0)
budget_type = models.CharField(max_length=100, default="")
def __str__(self):
return self.description + ' ' + str(self.amount)
class Budget(models.Model):
category = models.CharField(max_length=100, default="")
sub_category = models.CharField(max_length=100, default="")
amount = models.DecimalField(max_digits=10, decimal_places=2, default=0.0)

If you want to pass data of another model through the ListView, you might be looking for overriding the get_context_data method of ListView. Then you can be able to pass required data along with our model objects.
For example:
In your context, where you want to show data about the budget objects, you can change your BillListView view as:
class BillListView(ListView):
model = Transaction
template_name = 'budget/base_transactions.html'
context_object_name = 'transactions'
paginate_by = 10
queryset = Transaction.objects.filter(budget_type__exact='bill')
def get_context_data(self, **kwargs):
context = super(BillListView, self).get_context_data(**kwargs)
context['budgets'] = Budget.objects.filter(category__exact='bill') //filter as per required
return context
Then you can access the budget objects in the template by looping through budgets as:
{% for budget in budgets %}
{{ budget.amount }}
{{ budget.sub_category }}
{% endfor %}

Related

ManytoMany query and template rendering from one model to another

I'm new to Django. I had two different questions.
I can't query between one of my model and another model (ManyToMany). I can do this with the shell, but I couldn't handle it in the template.
I cannot assign a default value from one model to another model's field.
For the first question;
What I want to do is show values for multiple options. For this, I could make a query similar to this in the shell:
room[0].room_type_id.all()
But I can't do this in the template. On the other hand, when I want to show it with display, it returns empty. What I want to do here; returning the room types for each room or or accessing the room_cost of the RoomType class and displaying it in the template, repeated for each room type.
{% for room in rooms %}
<h3 class="card-title pricing-card-title"> {{room.room_type_id_display}} </h3>
{% endfor %}
My second question is;
To set the value from the property of a different model as default in the other model field. That is, to assign the value returned from the total_price of the Booking model to the price field in the Payment model by default.
I would appreciate it if anyone could provide documentation or resources on the subject.
class RoomType(models.Model):
ROOM_CHOICES = (
('1', 'O),
('2','T'),
('3', 'Th'),
('4','F'),
('5','Fi')
)
room_type = models.CharField(max_length=50,choices=ROOM_CHOICES)
room_type_des = models.TextField(blank=True,null=True)
room_cost = models.IntegerField()
def __str__(self):
return str(self.room_type)
class Room(models.Model):
room_number = models.IntegerField()
room_des = models.TextField(blank=True,null=True)
room_availabe = models.BooleanField(default=True)
room_type_id = models.ManyToManyField(RoomType)
def __str__(self):
return str(self.room_number)
class Booking(models.Model):
room_number_id = models.ForeignKey(Room,on_delete=models.DO_NOTHING)
customer_id = models.ManyToManyField(Customer)
check_in = models.DateTimeField(auto_now_add=True)
check_out = models.DateTimeField(auto_now_add=False,auto_now=False,auto_created=False, null=True)
status = models.BooleanField(default=False)
#property
def calculate_day(self):
day = self.check_out - self.check_in
return str(day.days)
#property
def total_price(self):
day = self.check_out - self.check_in
price = self.room_number_id.room_type_id.room_cost
return price*day.days
class Payment(models.Model):
booking_id = models.ForeignKey(Booking,on_delete=models.DO_NOTHING)
ACCEPT_CHOICES = (
('N','N'),
('K','K'),
)
payment_type = models.CharField(max_length=1,choices=ACCEPT_CHOICES)
price = models.IntegerField()
payment_detail = models.TextField()
Here's a small modification: don't use "_id", because it's not an id, it's a real instance of the foreign model.
Then, use "related_name", and think like "if I start from the opposite side, what name should I use?" (it's always plural).
And for your (2), you can't set a default value for a "in-between table": a ManyToMany field create a "join" table to join the two other tables. You can only set a default value for OneToOne and ForeignKey fields.
class RoomType(models.Model):
ROOM_CHOICES = (
('1', 'O),
('2','T'),
('3', 'Th'),
('4','F'),
('5','Fi')
)
room_type = models.CharField(max_length=50,choices=ROOM_CHOICES)
room_type_des = models.TextField(blank=True,null=True)
room_cost = models.IntegerField()
def __str__(self):
return str(self.room_type)
class Room(models.Model):
room_number = models.IntegerField()
room_des = models.TextField(blank=True,null=True)
room_availabe = models.BooleanField(default=True)
room_type = models.ManyToManyField(RoomType, related_name="rooms")
def __str__(self):
return str(self.room_number)
class Booking(models.Model):
room = models.ForeignKey(Room, related_name="bookings", on_delete=models.DO_NOTHING)
customer = models.ManyToManyField(Customer, related_name="bookings")
check_in = models.DateTimeField(auto_now_add=True)
check_out = models.DateTimeField(auto_now_add=False,auto_now=False,auto_created=False, null=True)
status = models.BooleanField(default=False)
#property
def calculate_day(self):
day = self.check_out - self.check_in
return str(day.days)
#property
def total_price(self):
day = self.check_out - self.check_in
price = self.room_number.room_type.room_cost
return price * day.days
class Payment(models.Model):
booking = models.ForeignKey(Booking, related_name="payments", on_delete=models.DO_NOTHING)
ACCEPT_CHOICES = (
('N','N'),
('K','K'),
)
payment_type = models.CharField(max_length=1,choices=ACCEPT_CHOICES)
price = models.IntegerField()
payment_detail = models.TextField()
If you want all your room types, it's:
RoomType.objects.all()
If you want to "send" all types to a template, use get_context_data like this:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["room_types"] = RoomType.objects.all()
return context
and in your template:
{% for room_type in room_types %}
{{ room_type }}
{% endfor %}
For your template (and with my models code above), you could do:
{% for room in rooms %}
<h3 class="card-title pricing-card-title"> {{ room.room_type }} </h3>
{% endfor %}
And if you want to show all options in a form, it's another subject, too long for a simple answer here, read the official documentation here.

How to properly use filter method with foreign key in django details view with multiple models

I have two model one model is being used for storing the blog posts and another model is being used for taking the ratings and comments. Below are two my models
# Models Code
class Products(models.Model):
name = models.CharField(max_length=50)
img = models.ImageField(upload_to='productImage')
CATEGORY = (
('Snacks','Snacks'),
('Juice','Juice'),
)
category = models.CharField(max_length=50, choices=CATEGORY)
description = models.TextField()
price = models.FloatField()
review = models.TextField()
# Rating Model
class Rating(models.Model):
product = models.ForeignKey(Products, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
stars = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)])
comment = models.TextField()
#Views Code
class ProductListView(ListView):
model = Products
template_name = 'products.html'
context_object_name ='Products'
class ProductDetailView(DetailView):
model = Products
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
context['Rating'] = Rating.objects.filter(self.product_id) # How can i get the comments only for that specific product?
return context
In details-view how should I filter to fetch the comments for that specific product only ?
no need to write separate context for that in ProductDetailView, you can do it as follows in templates
{% for rate in object.rating_set.all %}
{{ rate.comment }}
{% endfor %}

Django: transfering two primary keys to new detail view

I'm trying to create a detail view where I use employee and subject name to show the evaluations created in the specific subject.
I currently have this detail where, where I'm looping through the subject names and displaying all the evaluations for the subject for the employee. The view is using employee as the primary key.
So when I press on the subject name from the loop below, I wish to go to a new view where I show the evaluations for the subject by the specific employee.
Employee template
{% for subject in subject_list %}
<h5>{{ subject.subjectname }}</h5>
{% for evaluation in subject.evaluation_set.all %}
{{ evaluation.instructor }}
{{ evaluation.ma }}
{% endfor %}
{% endfor %}
I can't figure out what the best way to do this is. I believe using the employee primary key for the new view is correct, but how do I "transfer" the subject id from the loop to the next view?
Alternatively I can use the subject id for the view but then I don't understand how to "transfer" the employee over.
Employee view with subjects
class EmployeeEvalDetailView(DetailView):
template_name = 'evalsys/evalueringer/se_alle_evalueringer.html'
model = Employee
def get_context_data(self, **kwargs):
context = super(EmployeeEvalDetailView, self).get_context_data(**kwargs)
context['fagene'] = Subject.objects.all().prefetch_related(Prefetch('evaluation_set', queryset=Evaluation.objects.filter(ma=self.object)))
return context
Employee model
class Medarbejder(models.Model):
id = models.AutoField(primary_key=True)
slug = models.SlugField(max_length=200)
ma = models.IntegerField(help_text="Indtast medarbejderens MA-nummer. (F.eks 123456)")
firstname = models.CharField(max_length=30, help_text="Indtast medarbejderens fornavn.")
lastname = models.CharField(max_length=30, help_text="Indtast medarbejderens efternavn.")
subject = models.ManyToManyField('Subject', related_name='medarbejder', through='Evaluering')
Evaluering model
class Evaluering(models.Model):
id = models.AutoField(primary_key=True)
oprettet = models.DateTimeField(auto_now_add=True)
opdateret = models.DateField(auto_now=True)
ma = models.ForeignKey('Employee', on_delete=models.CASCADE, null=True)
subjectname = models.ForeignKey('Subject', on_delete=models.CASCADE, null=True)
instructor = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
Subject model
class Subject(models.Model):
id = models.AutoField(primary_key=True)
subjectname = models.CharField(max_length=255, help_text="Indtast navnet på faget.")
slug = models.SlugField(max_length=200, unique=True)
New detail view with multiple PK's
class FagEvalDetailView(DetailView):
model = Employee
template_name = 'evalsys/evalueringer/eksporter/detail_fag_eval.html'
def get_context_data(self, **kwargs):
context = super(FagEvalDetailView, self).get_context_data()
context['pk_alt'] = Subject.objects.get(id=self.kwargs.get('pk_alt', ''))
return context

Why can't I see user-added information with Django?

I'm using Django 2.2 and PostgreSQL. I want to display the product information that the user has added to the detail page. I see the information in the 'StoreOtherInfo' model, but I don't see the information in the 'Product' model. How can I do that?
store/models.py
class StoreOtherInfo(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,blank=True, null=True)
phone = models.CharField(max_length=11)
fax = models.CharField(max_length=11)
province = models.CharField(max_length=11)
district = models.CharField(max_length=11)
neighborhood = models.CharField(max_length=11)
def __str__(self):
return self.user.username
products/models.py
class Product(models.Model):
seller = models.ForeignKey(User, on_delete = models.CASCADE)
product_name = models.CharField(max_length = 50)
description = RichTextField()
added_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.seller
store/views.py
from store.models import StoreOtherInfo
from products.models import Product
def neighbor_detail(request,username):
neighbor_detail = get_object_or_404(User,username = username)
neighbor_list = StoreOtherInfo.objects.all()
product_list = Product.objects.all()
return render(request, 'store/neighbor_detail.html', {'neighbor_detail':neighbor_detail, 'neighbor_list':neighbor_list, 'product_list':product_list})
templates/neighbor_detail.html
<strong><p>{{neighbor_detail.first_name}} {{neighbor_detail.last_name}}</p></strong>
<p>{{neighbor_detail.username}}</p>
<p>{{neighbor_detail.email}}</p>
<p>{{neighbor_detail.storeotherinfo.phone}}</p>
<p>{{neighbor_detail.storeotherinfo.fax}}</p>
<p>{{neighbor_detail.storeotherinfo.province}}</p>
<p>{{neighbor_detail.storeotherinfo.district}}</p>
<p>{{neighbor_detail.storeotherinfo.neighborhood}}</p>
<p>{{neighbor_detail.product.product_name}}</p>
<p>{{neighbor_detail.product.description}}</p>
<p>{{neighbor_detail.product.added_date}}</p>
according to your Product model:
seller = models.ForeignKey(User, on_delete = models.CASCADE)
the relation between User model and Product model is one-to-many. This means every User(in this case seller) can have multiple Products.
So when you try to access the Product objects of a User object as you did in you template: <p>{{neighbor_detail.product.product_name}}</p> you end up giving an attribution error because neighbor_detail.product is not a single object of Product class it's a collection.
replace your template code with this and i hope you realize whats happening.
<strong><p>{{neighbor_detail.first_name}} {{neighbor_detail.last_name}}</p></strong>
<p>{{neighbor_detail.username}}</p>
<p>{{neighbor_detail.email}}</p>
<p>{{neighbor_detail.storeotherinfo.phone}}</p>
<p>{{neighbor_detail.storeotherinfo.fax}}</p>
<p>{{neighbor_detail.storeotherinfo.province}}</p>
<p>{{neighbor_detail.storeotherinfo.district}}</p>
<p>{{neighbor_detail.storeotherinfo.neighborhood}}</p>
{% for product in neighbor_detail.product_set.all %}
{{product.product_name}}<br/>
{{product.description}}<br/>
{{product.added_date}}<br/>
{% endfor %}
note that product_set is the default name that django associate with products related to each user.
A User can have multiple Products, so you can't do neighbor_detail.product because product isn't defined on a User. You need to loop through the list of products with {% for product in neighbor_detail.product_set.all %} and then you can display the properties of each product.
Read [this] for more information about one-to-many relationships.

Using two django model forms on the same view

I have a PatientRegistrationForm and a PatientBillingForm form in a single view RegisterPatient.
When when I submit the patient form (form), the submitted date is stored in the database, nut the billing form (form1) only updates the staff and patient fields and nothing is stored in the payment_type, amount and receipt_number.
Please can anyone help point out why the second form is not being updated on the database?
Here is the views, models, forms and template code:
views.py
def RegisterPatient(request):
# bills = obj.bill_set.all()
form = PatientRegistrationForm(request.POST or None)
form1 = PatientBillingForm(request.POST or None)
if form.is_valid() and form1.is_valid():
instance = form.save(commit=False)
instance1 = form1.save(commit=False)
payment_type = form1.cleaned_data["payment_type"]
amount = form1.cleaned_data["amount"]
receipt_number = form1.cleaned_data["receipt_number"]
first_bill = Billing()
first_bill.payment_type = payment_type
first_bill.amount = amount
first_bill.receipt_number = receipt_number
# first_bill.saff
# first_bill.patients
print first_bill.payment_type, first_bill.amount, first_bill.receipt_number
first_name = form.cleaned_data["first_name"]
last_name = form.cleaned_data["last_name"]
other_name = form.cleaned_data["other_name"]
phone_number = form.cleaned_data["phone_number"]
new_patient = Patient()
new_patient.patient_number = UniquePatientNumber()
new_patient.first_name = first_name
new_patient.last_name = last_name
new_patient.other_name = other_name
new_patient.save()
first_bill.save()
model.py
class Patient(models.Model):
patient_number = models.CharField(max_length=120, unique = True, )
first_name = models.CharField(max_length = 120)
last_name = models.CharField(max_length=120)
other_name = models.CharField(max_length = 120, blank=True, null=True)
phone_number = models.CharField(max_length=15)
def _unicode_(self):
return self.patient_number
class Billing(models.Model):
staff = models.ForeignKey(MyUser, default=1)
patients = models.ForeignKey(Patient, default=1)
payment_type = models.CharField(max_length=100)
amount = models.DecimalField(max_digits=100, decimal_places=2, default=0.00)
receipt_number = models.CharField(max_length=120)
payment_date = models.DateTimeField(auto_now=False, auto_now_add=True)
def _unicode_(self):
return self.staff.username
def new_user_receiver(sender, instance, created, *args, **kwargs):
if created:
new_patient, is_created = Billing.objects.get_or_create(patients=instance)
post_save.connect(new_user_receiver, sender=Patient)
def new_user_creator(sender, instance, created, *args, **kwargs):
if created:
new_user, is_created = Billing.objects.get_or_create(staff=instance)
post_save.connect(new_user_creator, sender=MyUser)
form.py
class PatientRegistrationForm(forms.ModelForm):
class Meta:
model = Patient
exclude = ["patient_number"]
class PatientBillingForm(forms.ModelForm):
class Meta:
model = Billing
fields = ["payment_type","amount","receipt_number"]
forms.html
<form method="POST action="">{% csrf_token %}
{{ form }}
{{ form1 }}
<input type="submit" value="Submit"/>
</form>
In your view function you always create new Billing to MyUser with pk=1 and Patients with pk=1 because you set the default values in Billing fields default=1. You should remove default=1 and set null=True,blank=True instead.
If I understand your logic. You want to create new Billing information to every new User oder new Patient. I guess that in your view function you want to update or create Billing information to a patient. If so you should call
Billing.objects.filter(patients__pk=new_patient.pk).update(payment_type=payment_type,amount=amount,receipt_number=receipt_number)
after new_patient.save() then you could comment out lines with first_bill.
Update
1) comment out the line Billing.objects.filter(...)
2) comment out post_save.connect(new_user_receiver, sender=Patient) in models.py
3) activate the lines with first_bill again and add:
first_bill.patients=new_patient after new_patient.save()